13 Clean Code Principles Explained with Examples

Peng Cao
7 min readMay 21, 2023

DRY, WET, SRP, OCP, LSP, ISP, DIP, KISS, YAGNI, Fail Fast, LoD, CQS, Composition over Inheritance

1. Don’t Repeat Yourself (DRY)

This principle suggests that code should not have unnecessary duplication. Instead, it should be organized in a way that avoids redundancy and makes it easy to maintain. For example, instead of writing the same calculation in multiple places in the code, create a function that performs the calculation and call that function from the different places where the calculation is needed.

// bad example
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
console.log(total);
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
console.log(total);
// good example
function calculateTotal(prices) {
let total = 0;
for (let i = 0; i < prices.length; i++) {
total += prices[i];
}
return total;
}
console.log(calculateTotal(prices));
console.log(calculateTotal(prices));

2. Write Everything Twice (WET)

This is an opposite principle of DRY. It suggest that if you find yourself copy-pasting code multiple times, anticipating the identical code forking in different directions later on, having WET code may make that future change easier.

--

--

Peng Cao

Writing programming and tech guide; Help each other with followers, thanks mate! Let's version up @ v2.digital