Track 04 · Lesson 9 of 15Code that stays easy to change
- 01Principles at a glance
- 02SOLID principles at a glance
- 03S: Single responsibility
- 04O: Open/closed
- 05L: Liskov substitution
- 06I: Interface segregation
- 07D: Dependency inversion
- 08Separation of concerns
- 09DRY: Don't repeat yourself
- 10KISS: Keep it simple
- 11YAGNI: You aren't gonna need it
- 12Composition over configuration
- 13Fail fast
- 14Least surprise
- 15When they disagree
Track 04 · Code that stays easy to change
DRY: Don't repeat yourself
Lesson 9 of 15· 5 min
Every piece of knowledge should live in exactly one place.
Change the tax rate
Move the slider in both versions
Cart
$96.00
subtotal * 1.2
Checkout
$96.00
subtotal + subtotal * 0.2
Invoice email
$96.00
Math.round(subtotal * 120) / 100
Move the slider. The rate is copied into three files, written three different ways.
// Cart.tsx
const total = subtotal * 1.2;
// Checkout.tsx
const total = subtotal + subtotal * 0.2;
// emails/invoice.ts
const total = Math.round(subtotal * 120) / 100;
// Same rule, written three different ways, so search won't even find them all.
// When the rate changes, someone has to remember every copy.Knowledge, not lines#
The three copies in the demo were written three different ways: * 1.2, + subtotal * 0.2, * 120 / 100. Searching for "0.2" finds one of them. That's what makes duplicated knowledge dangerous: you can't reliably find all the copies when the rule changes.
Give the rule one home, a TAX_RATE constant and a withTax() function, and every caller uses it. Change it once and they all agree.
Watch out for false duplication#
DRY is about repeated knowledge, not repeated-looking code. Two snippets that look alike but change for different reasons should stay separate. Merging them early is how a component ends up with ten boolean flags, each one for a single caller.
Check yourself