principletypescriptMajor
DRY vs WET: Don't Repeat Yourself — But Not at the Cost of Wrong Abstractions
Viewed 0 times
DRYWETrule of threewrong abstractionduplicationpremature abstractionSandi Metz
Problem
Two code paths look similar so they are merged into one abstraction. Later, the two use cases diverge. The shared abstraction becomes a tangled mess of conditionals trying to serve both callers, making both use cases harder to change.
Solution
DRY applies to knowledge, not syntax. If two code fragments represent the same knowledge (same invariant, same rule), unify them. If they happen to look similar but represent different concerns, duplication is acceptable.
// Two similar-looking validators that represent DIFFERENT knowledge
// (shipping address rules vs billing address rules):
// Bad: forced unification because 'they look the same'
function validateAddress(addr: Address, type: 'shipping' | 'billing') {
if (!addr.line1) throw new Error('Address line 1 required');
if (type === 'shipping' && !addr.phone) throw new Error('Phone required for shipping');
if (type === 'billing' && !addr.taxId) throw new Error('Tax ID required for billing');
// grows with more conditionals as rules diverge
}
// Good: keep separate; each can evolve independently
function validateShippingAddress(addr: Address) {
if (!addr.line1) throw new Error('Address line 1 required');
if (!addr.phone) throw new Error('Phone required for shipping');
}
function validateBillingAddress(addr: Address) {
if (!addr.line1) throw new Error('Address line 1 required');
if (!addr.taxId) throw new Error('Tax ID required for billing');
}Why
The WET (Write Everything Twice) heuristic says: duplicate once, abstract on the third occurrence. This avoids premature abstraction. The Rule of Three gives time to understand the actual commonality before locking in a shared interface.
Gotchas
- Removing duplication by creating a wrong abstraction is worse than leaving duplication in place.
- DRY applies to knowledge/business rules, not just code text. Two identical-looking snippets that encode different rules should stay separate.
- Sandi Metz: 'duplication is far cheaper than the wrong abstraction'.
Revisions (0)
No revisions yet.