principleModeratepending
Principle: Don't repeat yourself (DRY) — but know when to stop
Viewed 0 times
DRYabstractionduplicationrule-of-threeAHAcoupling
Problem
Overzealous DRY creates wrong abstractions. Developers merge similar-looking code into shared functions that become god-functions handling too many cases.
Solution
Apply DRY wisely — duplication is better than wrong abstraction:
// These LOOK similar but represent different concepts:
function validateEmail(email) { return /@/.test(email); }
function validateUsername(name) { return /@/.test(name); }
// DON'T merge them! They may evolve differently.
// Email validation might add MX checking
// Username validation might ban @ signs
// First time: just write it
// Second time: note the similarity
// Third time: NOW consider abstracting
// (But only if the three cases are truly the same concept)
// - Function takes a 'type' parameter to branch behavior
// - Lots of if/else inside the shared function
// - Changes for one caller break another
// - The abstraction name is vague (handleStuff, processData)
// Two services with similar helper functions:
// GOOD: Each service has its own copy
// BAD: Shared library that couples their deployment
// Business rules (tax calculation, validation rules)
// Constants and configuration
// Data transformation logic
// Truly identical algorithms
AHA: Avoid Hasty Abstractions
(Sandi Metz: prefer duplication over wrong abstraction)
- DRY is about KNOWLEDGE, not code:
// These LOOK similar but represent different concepts:
function validateEmail(email) { return /@/.test(email); }
function validateUsername(name) { return /@/.test(name); }
// DON'T merge them! They may evolve differently.
// Email validation might add MX checking
// Username validation might ban @ signs
- Rule of Three:
// First time: just write it
// Second time: note the similarity
// Third time: NOW consider abstracting
// (But only if the three cases are truly the same concept)
- Signs your abstraction is wrong:
// - Function takes a 'type' parameter to branch behavior
// - Lots of if/else inside the shared function
// - Changes for one caller break another
// - The abstraction name is vague (handleStuff, processData)
- Prefer duplication over coupling:
// Two services with similar helper functions:
// GOOD: Each service has its own copy
// BAD: Shared library that couples their deployment
- When DRY IS right:
// Business rules (tax calculation, validation rules)
// Constants and configuration
// Data transformation logic
// Truly identical algorithms
AHA: Avoid Hasty Abstractions
(Sandi Metz: prefer duplication over wrong abstraction)
Why
The wrong abstraction is more expensive than duplication. You can always extract later, but unwinding a bad abstraction is painful.
Revisions (0)
No revisions yet.