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

There are a few keys to ensure you are investing your time wisely:

  1. Avoid premature generalization by sticking to the Rule of Thrice
  2. Make sure any additional time spent building a generic solution is worth it
  3. Build only what you need at first; don't try to anticipate future use cases
  4. 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.

The Rule of Thrice: Know When to Build Generic Solutions in Code
Once is a fluke. Twice is a coincidence. Thrice is a pattern.

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:

"Don't forget the time you spend finding the chart to look up what you save. And the time spent reading this reminder about the time spent. And the time trying to figure out if either of those actually make sense. Remember, every second counts toward your life total, including these right now."

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
Adding Procedure Parameters Without Breaking Backwards Compatibility in VBA
Sometimes you need to add a parameter to a Function or Sub in VBA. But you don’t need to break all of your calling code to do it.
Backward-Compatible Refactoring
How can you completely change the way you interact with a class without breaking backward compatibility? Interfaces.

Cover image created with Microsoft Designer

All original code samples by Mike Wolfe are licensed under CC BY 4.0