Coding Style: Chained If Statements

What should you do when you have several if statements in a row? Some people like to nest if statements like this:

foo = 0;
if (x)
{
    // Do work
    …
    if (y)
    {
        // More work
        …
        if (z)
        {
            // Final calculation
            …
            foo = x + y + z;
        }
    }
}

return foo;

Others prefer to check conditions one after another, like this:

foo = 0;

if (!x)
{
    return foo;
}

// Do work
…
if (!y)
{
    return foo;
}

// More work
…
if (!z)
{
    return foo;
}

// Final calculation
…
return x + y + z;

I prefer the second method. Nesting if statements can get confusing; the second style looks cleaner and tells the reader immediately when they can return. I also feel that the second style is more concise. It helps keep code within an 80-character width limit.

Some programmers might argue that the second style leads to duplication of code (“return foo” is copied three times). However, if that fragment (“return foo”) becomes complex, it could be moved to a separate method and called three times. I think that’s a fair price to pay for readability. After all, the compiler will optimize both styles into the same machine code.

Which style do you prefer, and why?

Advertisements
This entry was posted in Software and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s