Introduction
In the world of software development, one of the most pervasive mantras is code reuse. However, Sandi Metz, in her famous 2016 article, highlighted a crucial point: "Duplication is far cheaper than the wrong abstraction." But why did this idea elicit such strong reactions? And more importantly, how can it be practically applied to your projects?
The Temptation of Abstraction
Software development is often a delicate dance between simplicity and complexity. When a developer encounters redundant code segments, the natural instinct is to abstract this code into a reusable function or class. On paper, this approach makes sense: it reduces duplicated code and simplifies maintenance. However, hasty abstraction can lead to major issues if not well-designed.
Consider a concrete example. Imagine an order management system where several modules calculate taxes. Each module has its own specificities. If you create an overly general abstraction to handle these calculations, you might end up with complex conditional logic that makes the code hard to read and maintain.
The Dangers of the Wrong Abstraction
The wrong abstraction can turn simple code into a nightmare. Over time, developers add parameters and conditions to accommodate new use cases, making the code increasingly incomprehensible. This is what Sandi calls the "fallacy of sunk cost": the more complex the code, the more reluctant we are to modify or delete it because we've already invested too much into it.
Quantitative Example
According to a 2021 Stripe study, developers spend an average of 42% of their time managing technical debt and wrong abstractions, costing the industry billions each year. This is time and budget that could be invested in innovation rather than maintenance.
When Duplication Becomes an Asset
Choosing duplication over a wrong abstraction is not a plea for code anarchy but an invitation to caution and reflection. Duplication can sometimes offer more clarity and flexibility. For instance, in a project where specifications are likely to change frequently, it might be wiser to maintain controlled duplications rather than lock yourself into a rigid abstraction.
Strategies to Avoid Wrong Abstractions
- Delay Abstraction: Do not create abstractions too soon. Allow the code to evolve and patterns to emerge.
- Regular Code Reviews: Involve other developers to assess the clarity and relevance of abstractions.
- Unit Testing: Ensure that each abstraction is well covered by tests to avoid regressions during modifications.
Conclusion
Code duplication, though often frowned upon, can be a valuable ally in software development. It can help you avoid the pitfalls of premature abstraction and ensure that your code remains flexible and easy to understand.
Let's discuss your project in 15 minutes.