Core principle
DRY — Don't Repeat Yourself
Every piece of knowledge should have one authoritative source — duplicate it, and you'll eventually update one copy and forget the rest.
✗ The problem
The same rule, copy-pasted three times
// cart.js
const tax = price * 0.08;
// invoice.js
const tax = price * 0.08;
// report.js
const tax = price * 0.08;
cart.js
rate = 0.08
invoice.js
rate = 0.08
report.js
rate = 0.08
The tax rate changes → you must find and edit every copy.
Miss one file and you ship a silent pricing bug.
✓ Refactor
↑
Extract a single source of truth
One function owns the rule. Every caller imports it instead of restating it.
// tax.js
export const TAX_RATE = 0.08;
export function taxFor(price) {
return price * TAX_RATE;
}
taxFor()
single source
cart.js
imports it
invoice.js
imports it
report.js
imports it
✓ See it live
Change the rate — watch which side breaks
Duplicated copies must all be edited by hand. A single source updates every consumer at once, automatically.
✗ Duplicated (3 hand-edited copies)
cart.js
8%
invoice.js
8%
report.js
8%
✓ Single source (one edit)
TAX_RATE
8%
cart.js
8%
invoice.js
8%
report.js
8%
Rate: 8% everywhere — click to change
✓ Takeaway
One source of truth, edited with care
- Fewer bugs: a rule stated once can't drift out of sync with itself.
- Easier change: one edit, one place, every caller updates instantly.
- Caution: don't DRY out code that only looks similar — forcing a shared abstraction onto coincidental duplication costs more than the duplication did.
- Rule of three: wait until you've copied something a third time before extracting it. Two copies might just be a coincidence.
Back to all topics →