I know this topic has been debated over and over and it's largely a personal preference... but I just thought of something on the topic that I've never thought of before, and felt like sharing.
Duoas linked this in another thread:
http://www.joelonsoftware.com/articles/Wrong.html
I've seen this before... but I skimmed it again until I saw this part:
Even more subtle:
In this case the code is 100% correct; it conforms to most coding conventions and there’s nothing wrong with it, but the fact that the single-statement body of the ifstatement is not enclosed in braces may be bugging you, because you might be thinking in the back of your head, gosh, somebody might insert another line of code there
1 2 3
|
if (i != 0)
bar(i);
foo(i);
|
… and forget to add the braces,
|
Do people actually DO that? By which I mean... add additional lines to clearly single-line if statements without adding braces? Apart from having to be practically blind... you also would have to manually tab over because the IDE wouldn't tab properly (or rather... it
would tab properly which would be an indication that you're messing up).
I have always
hated the "always use braces even for single-line if statements" rule. I've worked in places where it was a rule and it always irritated me. It adds a lot of unnecessary clutter, especially in code that has a lot of such conditionals.
I can't think of a single time in my life where I've made the mistake of adding a new line to an if block and thinking there were braces when there weren't. Even when I was a noob I never made that mistake. So why are people so worried about it?
Well I think I know why. I suspect it's because of this stupid brace style:
1 2 3
|
if( something ){
thisIsStupid();
}
|
It's not immediately obvious that the brace exists because it's on the same line as the conditional. Someone used to that style might get confused:
1 2 3 4 5
|
if( foo ) // <- this
biff();
if( bar ){ // <- looks similar to this
blam();
|
On the other hand... if you are a sane person and put the brace on a newline, it much more clear:
1 2 3 4 5 6
|
if( foo ) // <- now this looks totally different
biff();
if( bar ) // <- from this
{
blam();
|
I have used the latter style for pretty much my entire life (except for a time when I was a noob and tried to cram everything on as few lines as possible because I was dumb)... which I really feel is a big part of the reason why I never made the mistake mentioned in Duoas' linked article.
EDIT:
To elaborate further... the article is talking about coding style to make wrong code look wrong... but then shows this as an example of why you should do that:
1 2 3
|
if (i != 0)
bar(i);
foo(i);
|
When that code
already does clearly look wrong. This is a glaring indentation error in my brain and it's almost impossible for me to miss the mistake.