When duplication beats the wrong abstraction
Evaluate the trade-offs of code reuse versus premature abstraction, identify accidental duplication, and apply Sandi Metz's rule that duplication is cheaper than the wrong abstraction.
Contentsand lesson path
On this page
- The Dogma of DRY and the Hazard of Accidental Duplication
- Sandi Metz's Rule: Duplication is Cheaper than the Wrong Abstraction
- YAGNI, The Rule of Three, and Justified Abstraction Timing
- Practice check
- Review prompt
Lessons of Software Design Principles
- Why structure matters: paradigms, modules and the cost of change Concept · 20 min
- Measuring coupling with connascence Concept · 20 min
- SOLID, inversion of control and command-query separation Concept · 25 min
- Untangling an order service one refactoring at a time Worked example · 30 min
- When duplication beats the wrong abstraction Concept · 15 min
- Principles check: diagnose and justify Knowledge check · 8 questions
What you will learn
- Judge when DRY, YAGNI or abstraction-first advice should be overridden, giving a concrete reason.
01. The Dogma of DRY and the Hazard of Accidental Duplication
Among all software design acronyms, DRY (Don't Repeat Yourself) is perhaps the most universally celebrated and the most destructively misunderstood. Introduced by Andy Hunt and Dave Thomas in The Pragmatic Programmer, the actual formulation states: Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
Hunt and Thomas were speaking of knowledge and business intent, not identical lines of code. In junior and mid-level engineering teams, however, DRY is frequently degraded into a syntactic crusade: whenever two 10-line blocks of code share similar syntax or structure, a reviewer immediately demands extracting a shared helper function or base class. This mechanical reflex is the primary factory of catastrophic architectural coupling.
Accidental Duplication versus Essential Duplication Architects must draw a strict boundary between two fundamentally different phenomena:
- Essential Duplication (Knowledge Duplication): The same core business rule is duplicated in multiple places. For example, if both the frontend shopping cart and the backend billing service implement independent, hand-rolled algorithms to calculate VAT tax, a bug fix in one leaves the other inconsistent. This is true duplication of business knowledge and must be unified.
- Accidental Duplication (Incidental Similarity): Two separate subsystems possess routines that happen to look identical today by pure coincidence. For example, a customer billing address validator and a warehouse freight shipping validator might both check for valid postal codes and five-digit numbers. However, billing address rules are driven by tax statutory compliance, whereas freight shipping rules are dictated by carrier logistics (FedEx, DHL). If an architect merges them into a shared
AddressValidator, tax policy changes become artificially coupled to carrier logistics changes. Modifying tax handling risks breaking freight delivery.
02. Sandi Metz's Rule: Duplication is Cheaper than the Wrong Abstraction
In 2014, Sandi Metz crystallized a profound architectural insight: Duplication is far cheaper than the wrong abstraction.
The Degradation Lifecycle of a Premature Abstraction A wrong abstraction rarely starts out looking toxic. It evolves through an incremental, tragic lifecycle:
- Day 1: Developer
Anotices that Module 1 and Module 2 share similar 15-line routines. Guided by mechanical DRY dogma, DeveloperAextracts a shared helper class, celebrating a reduction in code lines. - Day 90: A new business requirement emerges that applies exclusively to Module 1. Developer
Bcannot modify the shared helper without breaking Module 2, so they introduce a boolean flag:process(data, is_module_1=True). - Day 200: Module 3 arrives. It needs 80% of what the helper does, but with a different error handling policy. Developer
Cadds two more parameters and anif/elseblock inside the loop. - Day 500: The once-elegant 15-line helper has metastasized into a 250-line monster with eight parameters, four conditional branches, and dozens of hidden temporal dependencies. Nobody understands what it does, yet every team depends on it.
The Sunk Cost Fallacy of Abstractions Why do teams tolerate toxic abstractions? Developers succumb to the sunk cost fallacy. Because an engineer spent three sprints designing an intricate inheritance hierarchy or generic reflection-based mapper, the team feels compelled to preserve it. Admitting that an abstraction was premature feels like wasted effort. In reality, keeping a flawed abstraction alive costs exponentially more in bug investigations, onboarding friction, and cognitive fatigue than the initial effort to build it.
The Remedy: Re-Inlining the Abstraction When an abstraction becomes burdened with flags and conditional branches catering to specific callers, architects must possess the courage to re-inline the code. Copy the shared logic back into each caller, delete the bloated abstraction, and observe each caller’s actual requirements. Once the code is duplicated in-place, the true domain boundaries become visible, allowing clean, minimal abstractions to emerge naturally. Re-inlining is frequently the highest-ROI refactoring an engineering team can perform.
03. YAGNI, The Rule of Three, and Justified Abstraction Timing
Two complementary heuristics protect architectures from premature generalization: YAGNI and The Rule of Three.
- YAGNI (You Aren't Gonna Need It): Coined in Extreme Programming (XP), YAGNI dictates that engineers should implement features and abstractions only when they are needed for current requirements, never in anticipation of speculative future needs. Building a generic multi-tenant plugin architecture when you have only a single database engine wastes capital and introduces needless indirection. Common speculative anti-patterns include building multi-database abstraction wrappers for internal microservices that will never migrate away from PostgreSQL, or designing dynamic workflow engines when hardcoded sequential scripts fulfill business needs.
- The Rule of Three: The first time you write code, write it cleanly. The second time you write similar code, duplicate it without shame. Only when you write it a third time should you extract an abstraction, because three concrete data points provide the geometric perspective needed to understand the true variation.
When to Override YAGNI YAGNI targets speculative guessing. An architect is justified in overriding YAGNI and introducing an abstraction seam today only when supported by concrete, verifiable business evidence: a committed client contract requiring a secondary payment provider next quarter, or a regulatory deadline requiring multi-region data sovereignty by year-end.
# Demonstrating Accidental Similarity vs Wrong Abstraction
from dataclasses import dataclass
# Tax compliance domain rule: changes under state tax laws
@dataclass(frozen=True)
class TaxAddress:
postal_code: str
state_code: str
def validate_tax_jurisdiction(self) -> bool:
# Validates statutory tax district compliance
return len(self.postal_code) == 5 and len(self.state_code) == 2
# Logistics freight domain rule: changes under carrier routing
@dataclass(frozen=True)
class ShippingDestination:
postal_code: str
dock_access: bool
def validate_freight_delivery(self) -> bool:
# Validates delivery vehicle dimensional clearance
return len(self.postal_code) == 5 and self.dock_access
# Retaining separate models avoids coupling tax law to shipping
tax_addr = TaxAddress("90210", "CA")
tax_ok = tax_addr.validate_tax_jurisdiction()
freight_ok = ship_dest.validate_freight_delivery()
print(f"Tax: {tax_ok} | Freight: {freight_ok}")04. Practice check
05. Review prompt
Explain the true definition of DRY (Don't Repeat Yourself) from The Pragmatic Programmer, and differentiate essential duplication of business knowledge from accidental syntactic similarity.
Articulate Sandi Metz's rule that "duplication is far cheaper than the wrong abstraction." Trace the lifecycle of a wrong abstraction from well-intentioned helper to boolean-bloated monster, and explain why re-inlining code is the correct architectural remedy.
Explain the Rule of Three and YAGNI (You Aren't Gonna Need It). Describe the rigorous business criteria that justify introducing an abstraction seam in advance of current requirements.
Finally, describe how architects should evaluate code review pull requests: resisting reflexive demands to eliminate incidental similarity, and defending intentional duplication when disparate domain modules happen to share matching lines of code today.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.