Case against single line if statements

… in curly bracket languages. I’ve always said – using single line ifs is dangerous, because a junior (or even a seasoned) developer might make a mistake and add an extra line of code which will not be executed in the if block.

I was watching this presentation of Kevlin Henney about Structured Programming – it talks that it’s good to use if and else if and fast returns and gotos are bad. It has a lot of examples with single line (non-curly bracket wrapped) ifs, and then this Apple’s SSL goto bug came along.

Let’s look at this simple example:

if (someBoolVar)
    doSomething();

Pretty simple – doSomething() is executed only if someBoolVar is true. Now say someone want’s to add another method call if someBoolVar is true:

if (someBoolVar)
    doSomething();
    doSomethingElse(); // This executes whether someBoolVar is true or not

We have a logical error, that will blow up on run-time. A better solution would be to actually write a single line of if statement:

if (someBoolVar) doSomething();

At least that would prevent adding additional statements without adding scope block. But curly bracket languages have curly brackets that define scope block and my way is to always use them:

if (someBoolVar)
{
    doSomething();
}

And when other developer adds it’s new method call it will actually work as expected:

if (someBoolVar)
{
    doSomething();
    doSomethingElse(); // Executes only if someBoolVar == true
}

So my rules of thumb are:

  • Always use curly brackets in if (or any other control structure) to define subsequent statements;
  • If you must use single line if statement – use just single line;
  • Leave wrapped single if statements to Python, because adding another line won’t make things blow up.

Leave a Reply

Your email address will not be published. Required fields are marked *