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
Another advantage of always using braces is that it makes search-and-replace and similar automated operations easier.
For example: Suppose I notice that functionB
is usually called immediately after functionA
, with a similar pattern of arguments, and so I want to refactor that duplicated code into a new combined_function
. A regex could easily handle this refactoring if you don't have a powerful enough refactoring tool (^\s+functionA.*?;\n\s+functionB.*?;
) but, without braces, a simple regex approach could fail:
if (x)
functionA(x);
else
functionA(y);
functionB();
would become
if (x)
functionA(x);
else
combined_function(y);
More complicated regexes would work in this particular case, but I've found it very handy to be able to use regex-based search-and-replace, one-off Perl scripts, and similar automated code maintenance, so I prefer a coding style that doesn't make that needlessly complicated.
The one big advantage I see is that it's easier to add more statements to conditionals and loops that are braced, and it doesn't take many additional keystrokes to create the braces at the start.
I stand on the ground that braces should match according to indentation.
// This is right.
if (foo)
{
// bar
}
else
{
// baz
}
while (things)
{
// stuff
}
As far as your two examples, I'd consider yours slightly less readable since finding the matching closing parentheses can be hard, but more readable in cases where indentation is incorrect, while allowing logic to be inserted easier. It's not a huge difference.
Even if indentation is incorrect, the if statement will execute the next command, regardless of whether it's on the next line or not. The only reason for not putting both commands on the same line is for debugger support.