Explore Topics
boolean validateUsername(String s) {
if (s == null) return false;
if (s.isEmpty()) return false;
if (s.trim().length() == 0) return false;
return true;
}
boolean validateEmail(String s) {
if (s == null) return false;
if (s.isEmpty()) return false;
if (s.trim().length() == 0) return false;
return s.contains("@");
}
boolean validateCity(String s) {
if (s == null) return false;
if (s.isEmpty()) return false;
if (s.trim().length() == 0) return false;
return true;
}Hunt and Thomas, in The Pragmatic Programmer (1999), wrote: "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system." DRY is about knowledge, not characters. Two methods that LOOK the same but encode different business rules should stay separate; their resemblance is coincidence. Two encodings of the SAME rule โ in code and in a database trigger, or copied across three validators โ are duplication. Find the rule, name it once, call it from everywhere. The trap: premature DRY creates the wrong abstraction, which is much harder to fix than honest duplication.
- Hunt & Thomas โ The Pragmatic Programmer (1999), the canonical source
- DRY of KNOWLEDGE, not characters โ two same-looking methods can both be correct
- Sandi Metz: "duplication is far cheaper than the wrong abstraction"
- Rule of three โ wait for the third occurrence before extracting
- Cousin principle: SRP (a class has one reason to change โ one place to change)
- โฆSingle source of truth โ change in one place propagates to all callers
- โฆReveals intent: extracted name documents the rule
- โฆCuts maintenance cost when the rule genuinely evolves
- โฆAligns with SRP and Information Expert from GRASP
- โณPremature DRY creates the wrong abstraction โ much harder to unwind than duplication
- โณCan couple callers that should evolve independently
- โณEasy to over-apply by spotting syntactic similarity instead of semantic identity
- โณOften fights YAGNI ("don't generalize speculatively")