Tuesday, March 6, 2007

if blocks

I've never understood why some programmers continue to write C code in the form:


if (someCondition)
doSomething();
else
doSomethingElse();

as opposed to


if (someCondition) {
doSomething();
} else {
doSomethingElse();
}

Beyond saving a couple of keystrokes, the first example has absolutely no advantage over the second. While the second is much more bullet proof.

When working on code written by others that cling to the first form, I continue to run across code like this:


if (someCondition)
doSomething();
doMore();
doOtherthings();

Where the intention is that doMore() is intended to be executed only when someCondition is true.

When you look at the history of the code it almost always starts out as


if (someCondition)
doSomething();
doOtherthings();

and then later the doMore() is added.

Please, please, please take the extra split second it takes to type in the safe form of the if from day one.