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.

4 comments:

  1. Better not use the checkAndDoSomething Method at all. Divide it into a check and a do. One task per method. Do not let 'getters' have side-effects. - RR

    ReplyDelete
  2. Maybe I should have named the method doSomethingAndReturnSuccessOrFailure, but that would break with my readability rule ;-)
    - JB

    ReplyDelete
  3. With custom ERP, the system is developed based on your company's experience. A programmer gets to design the ERP system in accordance what exactly you want the software to be able to do and ideally, the process it should follow in order to do perform and facilitate your operations.https://www.dbdesigner.net

    ReplyDelete
  4. Iron Titanium | Titsanium Art
    Iron titanium damascus knives titanium is an alloy of titanium vs stainless steel apple watch the finest titanium materials. The pure titanium earrings most popular is iron oxide. Iron, also called iron, is one where is titanium found of the oldest solid microtouch trimmer

    ReplyDelete