Notifications
Mark all as read
Q&A

Is omitting braces for single statements bad practice?

+5
−2

Consider this code:

while(arr[index] != 0)
    index++;

vs

while(arr[index] != 0) {
    index++;
}

Personally, I prefer the first. The fact that the braces are not needed makes them -- unnecessary. :)

To me, it's just clutter that wastes a line. Or 2 if you're one of them that also want the opening brace on a new line. The line waste can be avoided though, if you do like this:

while(arr[index] != 0) index++;

I often do that, and I like the style. Partially because it makes those loops stand out from loops with braces.

One argument I've heard for always using braces is that if you want to add another statement, then you need to remember adding braces or you will have bugs that can be hard to find. For instance, this would be an endless loop:

while(arr[index] != 0) 
    println("No zero found");
    index++;

While this is technically true that this mistake can be done, I find it a bit meh as an argument. If you're using an editor that autoindents the code, this mistake would be spotted immediately. And since using such an editor is something that you should do anyway, the point of this argument is a bit moot.

Plus, even though I have often coded without such an editor, I cannot remember ever doing that mistake. It feels like a mistake that one could do if you're used to Python. But adjusting coding standards of C, C++, Java and such to not confuse Python coders does not really seem like the right path to go.

Apart from this argument, I have not really seen anything else than the consistency argument. That always using the same style is consistent. Well it's true, but consistency is not ALWAYS good.

Have I missed something here? What do you say? Is omitting braces for single statements bad practice?

Why does this post require moderator attention?
You might want to add some details to your flag.
Why should this post be closed?

5 comments

With full-feature IDEs becoming common-place you might think the argument for always-braces is weakened. I'm not so sure. However, the legendary goto fail bug still looms as a mammoth counterexample. One assumes that Apple's developers used a full-featured IDE and still this mistake happened. With braces it would have been much harder to make that mistake. But not impossible! President James K. Polk‭ about 1 month ago

While that example is pretty interesting, it's anecdotal evidence. I understand that it's still possible to produce bugs like this. One could also reasonably argue that it could have been avoided if they used else if instead of if or didn't use goto. klutt‭ about 1 month ago

To me it sounds a bit like "you should not use i and j as counters in a nested for loop, because you CAN use the wrong one by accident" ;) klutt‭ about 1 month ago

If you enforce a style that always uses braces you can check it with static analysis tools though. Unlike using the wrong variable and similar application level bugs. Lundin‭ about 1 month ago

I've heard the "we don't need to do this anymore because modern editors are wonderful" argument a bunch of times, but I've found that these editors struggle in C++ with hokey macros, build scripts that set include directories that the IDE can't understand, and other weird tricks like that. Combine all that and my "modern IDE" isn't much better than Notepad++ and is filled with red squiggles and false positives and it takes about 10 seconds worth of idle time to parse the code. jrh‭ 29 days ago

5 answers

+9
−0

While [the Apple "goto fail bug"] is pretty interesting, it's anecdotal evidence. I understand that it's still possible to produce bugs like this. One could also reasonably argue that it could have been avoided if they used else if instead of if or didn't use goto.

Aviation safety is built, pretty much completely, on that kind of "anecdotal evidence"; and, on the whole, it's pretty successful (it's part of why virtually every airliner accident makes headlines, but very few car accidents do, even though in aggregate, far more people die in car accidents than in airliner accidents). So are many other safety regulations. Basically, when something goes wrong, a bunch of very smart people sit down and try to figure out what went wrong, what allowed it to go wrong, and what change to the existing regulations or practices would have prevented it from going wrong.

I can't help but notice that, in your example, you suggest that

while(arr[index] != 0) {
    index++;
}

should be shortened to

while(arr[index] != 0)
    index++;

because the compound statement delimeters are "unnecessary". But you don't take the obvious next step and suggest to instead write

while(arr[index++] != 0);

which will save you yet another line. It also saves you from, completely unnecessarily, naming the iterator variable separately on that second line. Why not?

I'll hazard a guess: because that will trip people up. It's perfectly valid code. It'll accomplish the same thing. It'll almost certainly have the same side effects in all of C, C++ and Java. And because people aren't used to that kind of construct, at a minimum, it will require expending additional effort to parse. Just because it's valid doesn't make it good.

Yes, in an ideal world, people wouldn't make mistakes, and everyone would do exactly what they intended to do and nothing else. Unfortunately, we don't live in that world, nor do I think we are likely to inhabit any world like it any time soon. If we accept this, it stands to reason that we should look at what can be done to reduce the likelihood of mistakes.

And let's face it, it's a lot harder to accidentally add a statement to the wrong level if every level is laid out with curly braces, begin/end, or whichever other construct the particular language uses to combine statements into compound statements. It's far easier to accidentally (and without noticing it afterward) go from

if (x)
    y();
z();

to

if (x)
    y();
    y2();
z();

than from

if (x)
{
    y();
}
z();

to

if (x)
{
    y();
}
    y2();
z();

when you meant to make both the y() and y2() calls conditioned on x. No matter what tooling you're using, that last example immediately stands out as "it just looks plain wrong", whereas the variant without the curly braces doesn't. Likewise, if you were to write

if (x)
{
    y();
}
y2();
z();

(correct indentation, but the y2() call placed in the wrong spot) it is also immediately clear that the call to y2() is not conditioned on x, even though that was the original intent.

If we can make syntactically valid but semantically wrong code actually look wrong, it greatly reduces the risk of semantically wrong code slipping through the cracks. The compiler will already catch things that are syntactically wrong, but it can't catch those things where what the programmer wrote is valid, just not what was intended.

Indeed, this "costs" a few extra lines for the braces (or equivalent keywords in languages that don't derive basic syntactical elements from B, such as for example Python or SQL). But if your code is so deeply nested, with so many separate short snippets, that this is actually a problem, maybe you should consider refactoring it anyway. Individual preferences aside, it's not like we're still using VT52 terminals as our primary display devices.

Why does this post require moderator attention?
You might want to add some details to your flag.

2 comments

Yes, I could write it as a oneliner, but don't get stuck on the specific example. It was just made as an example, and actually, I would have written it as a oneliner, but I would do it by just removing the newline and have while(arr[index]) index++; as a single line. Actually I'm pretty fond of doing that for single statement blocks. klutt‭ about 1 month ago

"Aviation safety is built, pretty much completely, on that kind of "anecdotal evidence"" Well, not really. Rather a group of experts getting together and agreeing on how things should be done. If you can quote for example DO-178, then that's a well-respected standard and canonical source. Lundin‭ 30 days ago

+7
−0

Not using braces is considered bad practice by widely recognized industry coding standards (MISRA-C:2012 rule, 15.6, CERT C EXP19-C and others).

Once upon a time I liked to skip out braces too, but every C (or other language) programmer using that style will ultimately write missing brace/indention goof-up bugs. Someone mentioned the "Apple goto fail" bug as one example, which I think is the single-most expensive software bug ever written. I used to write such bugs too now and then, until I abandoned that style. Particularly in long and complex else-if chains and such.

The CERT-C link above gives an excellent example:

if (invalid_login())
  if (allow_guests())
    privileges = GUEST;
else
  privileges = ADMINISTRATOR;

The else here ties to the inner if statement. Oops.


It is true that auto-indenting, auto-completion IDEs should reduce the chance for such bugs, but in my experience such IDEs are not nearly as smart as they could be - they often cause more bugs than they fix. For example if I delete a { in the start of a statement in existing code, then type it again (because I replaced the whole if condition), the stupid auto-complete IDE will give you this:

if(x) {}
  foo();
}

And if I don't notice that extra } and continue to type:

if(x) {}
  if(y) {
    foo(); 
}

Not quite what I intended.

Why does this post require moderator attention?
You might want to add some details to your flag.

3 comments

But in the end experienced C programmers have already been through missing semicolon, missing brace hell. It's an initiation rite that everyone learning C must go through. After you have coded for some 5+ years you can spot and fix these kind of bugs even if you wake up in the middle of the night with your face stuck to the keyboard. ("Uuuh... where am I... oh, statement missing, meh *click click*... uuuh what time is it...") Lundin‭ about 1 month ago

Your first example is also something that would be solved by autoindentation. Plus that if I wrote that , I would put braces around the outer if plus the else. Like if(x) { if(y) a=k; } else { a=m; }. And also, autoindentation would solve the problem. It was autocompletion that caused the problem in the second example. :) klutt‭ about 1 month ago

"the single-most expensive software bug ever written" I think the Mars Climate Orbiter is up there, too (no pun intended). ghost-in-the-zsh‭ 30 days ago

+3
−0

Already good answers, but I can provide a slightly different perspective here: always use braces if there is a risk of getting into a pitfall.

Examples (from C#, but the language is less relevant).

  • omit if the inner instruction fits on a single line and an extra blank line is inserted after:

    if (some_condition_here)
        return;
    
    var x = call(param1, param2);
    
  • include if the inner instruction does not fit on a single line:

    if (some_condition)
    {
        var someResult = DoSomeSpecialProcessingWithLotsOfParams(
            param1, param2, param3, param4);
    }
    

Of course, it is easier to just always put them, but I see no point is having them for simple cases such as my first example.

Why does this post require moderator attention?
You might want to add some details to your flag.

0 comments

+1
−0

I'm in the "Use the braces. Just use them every time" camp [1]. As others have suggested you or your tooling will catch a lot of cases where you screw up on this, but the ones that slip through can really hurt.

So, I was surprised to hear Robert "Uncle Bob" Martin opine that he's "on a mission to destroy all braces" (video link, but to the quote).

Now it was clear from the context that his preference is to get all the while statements into a form like

while ( someClearlyNamedCondition() )
    takeClearlyNamedAction();

and similarly for if, so that there is never a need to have more than one line following the condition (changes to the named action should be made in takeClearlyNamedAction(), right?) and the code can be read aloud without ambiguity or difficulty.

Making that work is going to take some serious dedication to clean code and refactoring as you go, but elsewhere in the video series, Uncle Bob talks about the importance that he sees in adopting a discipline in your coding (he has TDD in particular in mind and gives an enlightening demonstration of how he goes about that).


  1. This is a change for me and one that has been slow in coming. I'm old enough to have done most of my formative programming in terminals with a severely limited number of lines (hey but at least they were CRTs: many of the people I learned from had learned on punch cards and line printers). For a long time I was a proponent of formatting decisions that saved vertical space (K&R braces, leaving off unnecessary brackets, and so on). Even then I would sometimes print code so that I could examine it in the large. ↩︎

Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment

The problem with the someClearlyNamedCondition()/takeClearlyNamedAction() approach is when, to take that action, you need access to a variety of variables that are in scope for the while statement, but won't be in scope in a different function. It gets even worse if takeClearlyNamedAction() needs to mutate more than one piece of state. Now you're potentially introducing additional functions (which means mental context switching) just to avoid { }. Seems to me like a bad trade-off. Canina‭ 1 day ago

+1
−1

Advantages of Mandatory Braces

  • When in Rome, do as the Romans do. Since every popular coding standard for java mandates the use of braces, and every popular code style checking tool enforces their use, omitting these braces is highly unusual, making your code slightly harder to maintain for those unused to that.
  • Omitted braces have contributed to some rather serious bugs.

Disadvantages of Mandatory Braces

  • Additional programmer effort for writing the braces. Can be largely mitigated by tooling (for instance by configuring an eclipse save action to add them automatically)
  • Additional programmer effort for skipping over braces when reading code. This effect is likely very small, since java programmers are highly used to dealing with braces anyway.

Conclusion

While the advantages of mandatory braces are usually small, the cost of using them seems even smaller. So if I had to decide, I'd write those braces.

However, since the difference is so small, I'd not expend significant effort or political capital on this.

Why does this post require moderator attention?
You might want to add some details to your flag.

1 comment

Feel free to give constructive feedback when downvoting ... meriton‭ about 1 month ago

Sign up to answer this question »