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.
![4 Keys to Building Generic Solutions in Code](/content/images/size/w2000/2023/07/Building-Generic-Solutions.jpeg)
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.
![](https://nolongerset.com/content/images/2023/06/Rule-of-Thrice.jpeg)
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:
![](https://nolongerset.com/content/images/2023/07/image-24.png)
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
![](https://nolongerset.com/content/images/2022/11/egg-70494.jpg)
![](https://nolongerset.com/content/images/2020/10/typewriter-5626841_1920.jpg)
Cover image created with Microsoft Designer