Tuesday, August 18, 2009

stick to your language

Very often I see code fragments where programmers try to be smart. Don't!

Obviously there is nothing against being smart, but don't try to be smarter than necessary.

Most of the time these smart tricks have to do with compiler optimizations.

An example:

Imagine you have a method doSomething() that only has to be performed if another method checkAndDoSomething() returns true. That method in its turn only has to be performed if switch boolDoIt is set to true. Some programmers like to take advantage of the fact that most compilers optimize the code so, that in an and operation if the first element evaluates to false, the second element isn't evaluated at all and write code like this:

if (boolDoIt and checkAndDoSomething()) {
doSomething();
}

If you can rely on that optimization, you know that if boolDoIt evaluates to false, the checkAndDoSomething() method isn't performed, and neither will doSomething().

But what if the compiler vendor decides to drop that optimization for some reason? Then all of a sudden both elements are evaluated, so the method checkAndDoSomething() will be performed no matter the value of boolDoIt! Completely changing the behaviour of your code and violating the meaning of the switch.

A better, more stable way, would be:

if (boolDoIt) {
if (checkAndDoSomething()) {
doSomething();
}
}

I know, this looks like kindergarten code and is not fancy. But the code is easy to read and compiler independent. And probably after optimization by the compiler exactly the same ;-)

In other words:
write your code and functionality using the specifications of your programming language, not of your compiler.