Joel on braces
Zef blogs about how much he likes the works of Joel Spolsky and thinks we should head over and read Joel’s latest piece called Making Wrong Code Look Wrong. It’s a good read and coming from Joel, it is likely to influence more people than if say, I were to write up something similar. I generally agree with what Joel says, but there’s one thing I would like to comment on. Joel says:
if (i != 0)
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
if (i != 0)
… and forget to add the braces, and thus accidentally make foo(i) unconditional! So when you see blocks of code that aren’t in braces, you might sense just a tiny, wee, soupçon of uncleanliness which makes you uneasy.
I’ve seen this argument a thousand times before and I still don’t get it. I’ve been developing software in a variety of programming languages for quite some time now and I’ve never used braces for one-statement conditionals such as the if clause above. The reason for this is that proper indentation of the code makes problems such as the above very, very unlikely. Anyone who has any kind of eye for programming notices instantly that there is something wrong with the code after the introduction of bar(i). If the intent of the programmer was to make foo(i) unconditional, it would not be indented and there would be whitespace between bar(i) and foo(i). If the programmer wanted to include both bar(i) and foo(i) in the same block, there would be some whitespace above bar(i). The latter is of course only true if you put your curly braces in the right place :) Personally, I have never encountered a problem with this and truly believe that this old argument is completely unfounded.