Evaluating when code duplication might be preferable to premature abstraction
Core Idea: Code duplication, while traditionally discouraged, can sometimes be less harmful than forcing inappropriate abstractions that don't correctly model the problem domain.
Key Elements
- Duplication is often viewed negatively in programming ("Don't Repeat Yourself" principle)
- However, Sandi Metz argues that "duplication is far cheaper than the wrong abstraction"
- Duplication preserves contextual clarity in each implementation
- Premature abstraction can obscure the true nature of the problems being solved
- Duplication allows code to evolve independently when concepts aren't truly identical
Decision Factors
-
Consider tolerating duplication when:
- The duplicated code serves similar but not identical purposes
- Future requirements might cause implementations to diverge
- The abstraction would require complex conditionals
- You lack sufficient examples to identify the true abstraction
-
Consider abstraction when:
- The code truly represents the same concept in all cases
- Changes would need to be synchronized across all instances
- The underlying concept is stable and well-understood
Practical Approach
- When in doubt, prefer duplication initially
- Look for patterns across 3+ examples before abstracting
- Be willing to revert to duplication if an abstraction proves incorrect
- Use duplication as a tool to reveal better abstractions
Connections
- Related Concepts: The Wrong Abstraction (shows how abstractions can deteriorate), DRY Principle (contrasting perspective on duplication), Rule of Three (when to abstract)
- Broader Context: Software Design Principles (framework for making design decisions)
- Applications: Evolutionary Design (using duplication as part of incremental development)
References
- Metz, Sandi. "The Wrong Abstraction." Blog post. Originally from Chainline Newsletter.
- Metz, Sandi. RailsConf 2014 "All the Little Things" talk.
#programming #software_design #refactoring #dry_principle
Connections:
Sources: