In Making Wrong Code Look Wrong Joel writes:
Even more subtle:
if (i != 0)
foo(i);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)
bar(i);
foo(i);… 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.
Now I have heard this argument before: that even single statements after if (and while and for) statements should be in braces to prevent some klutz coming along and really breaking something. Now I don’t buy this at all. Why?
- Any programmer who would add the above statement without realising the implications should not be touching any of your code for any reason. If they are truly that terrible then the above problem is the least of your worries. What is going to happen when that programmer tries to code something non-trivial? Backup your codebase and keep the media handy. You are going to need it. (Oh sorry, I meant branch your codebase using the SCM tool you use, right?)
- I think these “mandatory” braces makes the code look awful: crowded, verbose, and … well .. wrong. Just why is that single statement in braces? Oh that’s right – they all are. It is bad enough that the ambiguity of if-if-else requires extra braces. I like my code minimalist – I like to see everything. A lot of refactoring is all about making the behavious of an if statement a single line [1]; don’t waste that effort.
- Martin Fowler formats “guard clauses” with the entire if statement on one line (“guard clauses” have no else leg). I like this format, and he describes why this makes the programmer’s intention clearer. Braces? Blech! [2]
- This technique is really a piece of flim-flammery to create a syntactic tarpit. I believe there are more important drivers for how code if formatted and organised. Screen space is valuable.
I get that this is going to be “horses for courses”. I suppose you like this idea or you don’t. I hate it.
I think doing things that aren’t right to compensate for (to put it bluntly) incompetence is not the right way to go. You can never compensate for incompetence. It just finds new means of expression.
I am going to put this up there with the One True Brace Style argument, about which I have equally strong and pointless opinions.
[1] Refactoring, Martin Fowler.
[2] Refactoring, Marting Fowler. pp 250-254.
No Comments so far ↓
There are no comments yet...Kick things off by filling out the form below.