Track 04 · Lesson 9 of 15Code that stays easy to change

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.

3 files, 3 copies of one ruleWithout it
// 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

When does DRY tell you to merge two similar functions?