From time to time, I use the VBIDE library to generate code.
The process usually goes like this.
- Write a function or class module with lots of boilerplate.
- Later--a few minutes or a few months--reuse the code by copying, pasting, and replacing all the non-boilerplate bits.
- Later--a few minutes or a few months--realize that I'm using this code enough that I should extract the variable text and write a function to generate the code.
- Write said function in a Code Library module that I call DesignProcedures.
Sometimes I skip over steps 2 and 3, but I try not to. There are two major benefits to writing similar code three times before generalizing it.
YAGNI – You ain't gonna need it
More often than not, you never actually get to step 4. It's easy to assume while you're working on some problem, that this same problem is sure to appear again in the future. It's tempting to prepare for that situation by generalizing your code now. However, the situation is rarely identical the next time. It often varies in subtle but important ways.
Which brings me to the next benefit.
Build what you actually need
Once is a fluke. Twice is a coincidence. Thrice is a pattern.
If you generalize after the first usage of the class/routine, you will be making a lot of assumptions about the future. It's far better to wait for the future to arrive; hindsight, as they say, is 20/20.
For best results...copy and paste your code
I know, I know. Every programmer knows the first commandment of software development is, "Thou shalt not copy and paste code."
That's generally good advice. But this is a situation where copying and pasting your code is not only acceptable, but preferable. For this process to work most efficiently, steps 2 and 3 require copying and pasting the code before editing it.
When you copy and paste, you end up with a complete duplicate of the original code. Then, each edit you make is a variable for which your code-generating function would need to account. Do this twice and you will have a very good idea of how to construct your generic solution.
You may also realize that there are enough changes among the three versions of your class/routine that it does not make sense to generalize it at all.
Once you've arrived at step 4, you need some way to generate the boilerplate code from your code-generation function. I'll share the Notepad++ trick I use for doing that in tomorrow's article.