How can you change a programming trick into a programming treat? Try this algorithm:
- If you develop a clever snippet of code, squirrel it away. This snippet is a "trick."
- If you use the trick a second time, copy and modify the code. The trick has become a "treat."
- If you use the trick a third time, generalize the idea and write a self-contained function. The trick has become a technique.
When I write a program, I decide whether the program is for my own use or is intended for others to use.
If the program is for a one-time analysis, I don't bother to add many comments, I don't check for error conditions, and I hardcode constants such as filenames and dimensions of matrices. Sometimes I don't even save those programs. I create the program, run it, look at the answer, and move on.
But sometimes I come up with a fiendishly clever programming trick, and I decide to save the program in case I ever need to use the trick again.
When I do have an opportunity to reuse a trick, I find the old program. (This is not always an easy task since I've written and saved more than 8,000 SAS/IML programs! Thank goodness for grep!)
Change a value here and a constant there, modify the IF condition, and...voila! Problem solved. I have given myself a sweet treat: a program that solved the problem but required almost no work. What could be better?
Actually, there is something better, and that's to turn the treat into a technique. To do this, I generalize the idea, remove the hardcoded constants, add comments, handle error conditions, and break the code into self-contained functions.
Now I can share my trick-turned-treat with others.