Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 671
Dean J Avatar asked Dec 16 '09 18:12

Dean J


1 Answers

The best counter argument I can offer is that the extra line(s) taken up by the space reduce the amount of code you can see at one time, and the amount of code you can see at one time is a big factor in how easy it is to spot errors. I agree with the reasons you've given for including braces, but in many years of C++ I can only think of one occasion when I made a mistake as a result and it was in a place where I had no good reason for skipping the braces anyway. Unfortunately I couldn't tell you if seeing those extra lines of code ever helped in practice or not.

I'm perhaps more biased because I like the symmetry of matching braces at the same indentation level (and the implied grouping of the contained statements as one block of execution) - which means that adding braces all the time adds a lot of lines to the project.

like image 138
Adam Bowen Avatar answered Sep 22 '22 22:09

Adam Bowen