Code Review: if statements
As part of my role as a developer I attend code reviews. On more than one occasion I’ve been struck by small details that have made a big difference.
A colleague once pointed out that I was giving myself an opportunity to get code wrong by missing out the braces in an if statement. In most C style languages, (C++, C#, Javascript etc) this is legal
if (someCondition)
performSomeAction();
However he asserted it was unwise to rely on indentation to indicate that the performSomeAction method will be called, its all to easy to add another indented statement or a semicolon to completely change the meaning. Consider these
if (someCondition);
performSomeAction();
and
if (someCondition)
performAnotherAction();
performSomeAction();
He said that its only a few extra characters to change the code to this
if (someCondition)
{
performSomeAction();
}
As a result I do try to always resist the shortcut of missing the braces out, I know that unit testing and advances in compilers can help but there are enough ways of getting bugs into code why look for another?