We have all written it. That bit of source code that uniquely solved the problem in as few lines as possible. Or maybe it uniquely used a feature of the programming language that would allow for the most efficient use of the CPU or memory. This is great for the college days when you need to impress the teacher. There is no place for this type of code in the work place, most of the time.
So how do you know when to use clever code? A piece of clever code usually has a specific benefit it provides. Clever code should only be used if the design requires it. Not if it would just benefit from it, but absolutely requires it. This can also be said as, don’t pre-optimize.
A great example of a implementation of clever code is Duff’s device. The code is a form of loop unrolling. The original use of it was a serial copy, but it could be applied to other loops. If the serial copy was only used once every few minutes on small amounts of data then this type of optimization wouldn’t provide enough benefits to outweigh the increased complexity in the code.
Another example is the Curiously recurring template pattern. The purpose of this pattern is to allow for static polymorphism. This provides decreased run-time and code size at the cost of a small amount of readability and the ability to have dynamic polymorphism.
The entire set of boost C++ libraries can fall under the category of clever code. Before selecting any of these libraries consider who else is responsible for maintaining the code and for how long. If those responsible for maintaining the code do not know boost then they will see any use of it as overcomplicated. In one sense they are right, and they may even be completely right.
In general, use the tool that is ‘just’ necessary for the job. To make an analogy, do not use a power screwdriver when a manual one will do. The screw may not need to be that tight. Also, just because you are trying to use a simpler tools doesn’t mean you should use the wrong one. To continue the analogy, do not use a hammer when a screwdriver is what is needed.
It takes practice and foresight to use the right set of tools. You need to also be prepared to be wrong. Which means making sure that the implementation is easily changed. If you figure out how to do this then please let me know. I think its good to continually remind yourself to continue to learn when to think outside the box and when not to.
thoughts by our engineer Ron – Check out his blog!!