Concept · Code design
DRY: don't repeat yourself
Every piece of knowledge should have one authoritative home — which is about duplicated rules, not about code that merely looks alike.
DRY — "Don't Repeat Yourself" — comes from The Pragmatic Programmer (Hunt and Thomas, 1999): "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." It's usually misquoted as "never write similar code twice", which leads to worse code than the duplication it removes.
Knowledge, not text
Real duplication is the same rule written in two places:
// checkout
if total >= 500_000 { fee = 0 }
// cart preview
freeShipping := subtotal >= 500_000When the threshold changes, someone updates one and misses the other, and the system contradicts itself. Give the rule one home — a constant and a QualifiesForFreeShipping function — and both callers use it.
Coincidental similarity is not duplication. A username validator and a SKU validator that both allow 3–30 characters encode different rules that happen to match today. Merging them couples two things that will change for different reasons.
The test: if this rule changes, must every copy change too? If yes, deduplicate. If they could reasonably diverge, leave them apart.
DRY beyond code
The principle covers any knowledge: a database schema and a hand-written struct describing the same table (generate one from the other), API documentation that drifts from the handlers (generate it from the code or schema), configuration values copied into several services, or a business rule implemented in both frontend and backend validation (share a schema, or accept the duplication deliberately and test both).
Knowing when to stop
- Rule of three: tolerate the second copy; extract on the third, when you can see what actually varies.
- Duplication is cheaper than the wrong abstraction (Sandi Metz). A shared helper that has grown flags and special cases for each caller is worse than a few short copies — inline it back and start over.
- AHA ("avoid hasty abstractions") and WET ("write everything twice") are names for this caution.
DRY is one force among several; it often trades off against KISS and coupling. The design principles lesson works through the balance.