maintainabilitycoding-style

Mandatory use of braces


As part of a code standards document I wrote awhile back, I enforce "you must always use braces for loops and/or conditional code blocks, even (especially) if they're only one line."

Example:

// this is wrong
if (foo) 
    //bar
else 
    //baz
while (stuff)
    //things

// This is right.
if (foo) {
    // bar
} else {
    // baz
}
while (things) {
    // stuff
}

When you don't brace a single-line, and then someone comments it out, you're in trouble. If you don't brace a single-line, and the indentation doesn't display the same on someone else's machine... you're in trouble.

So, question: are there good reasons why this would be a mistaken or otherwise unreasonable standard? There's been some discussion on it, but no one can offer me a better counterargument than "it feels ugly".


Solution

  • I enforce this to a point, with minor exceptions for if statements which evaluate to either return or to continue a loop.

    So, this is correct by my standard:

    if(true) continue;
    

    As is this

    if(true) return;
    

    But the rule is that it is either a return or continue, and it is all on the same line. Otherwise, braces for everything.

    The reasoning is both for the sake of having a standard way of doing it, and to avoid the commenting problem you mentioned.