4 Keys to Building Generic Solutions in Code
Building and maintaining a library of custom code procedures is an investment that provides compounding benefits over time.
There are a few keys to ensure you are investing your time wisely:
- Avoid premature generalization by sticking to the Rule of Thrice
- Make sure any additional time spent building a generic solution is worth it
- Build only what you need at first; don't try to anticipate future use cases
- Maintain backward compatibility as you add features
Rule of Thrice
The Rule of Thrice goes like this,
Once is a fluke. Twice is a coincidence. Thrice is a pattern.
To follow the Rule of Thrice, you don't spend any time generalizing a solution until the problem has appeared at least three times.
Invest Your Time Wisely
How often will the situation come up? How much time will the generic solution save? How much additional time will it take you to build a generic solution versus the solution you have to build anyway?
Once you have those three values, use this handy chart from XKCD.com to decide whether a generic solution is worth doing:
Just-In-Time Development
Add features to your generic solution only as you need them.
Don't try to anticipate future use cases; you'll likely guess wrong. Instead, add new features only when the need arises. This has several benefits:
- Initial development will be faster
- You'll avoid creating (and having to maintain) unused features
- You'll have real-world situations to guide your development
Maintain Backward Compatibility
When you do add features to your solution, make sure you add them in a backward-compatible way. There are several techniques you can use to do that:
- Add optional parameters to generic procedures
- Add methods or properties to a generic class
- For major refactoring, create interfaces that act as a middleman to an existing class
Cover image created with Microsoft Designer