I've been contemplating this for a while now. I thought I would finally write on the subject and see what other people thought.
Do you really need blocks after if statements?
It has always been a best practice, in my opinion, to put opening and closing brackets after an if statement. Even if it has only one statement following.
The reasoning behind this best practice goes something like this: If someone later modifies this code and adds a line inside the if, having the block will prevent them from doing something like this:
Which, of course, will result in way too much love making, even on stormy days when the sky is mostly gray.
All those { } in if blocks add up to a lot of overhead
I’m not sure it is worth it anymore.
Most of the code I write now has one statement after an if block.
If I have some code like:
It is pretty much always going to get refactored to:
So, what is the real value of the { } here? If someone modifies this code, they are most likely going to modify the method DanceALittleDance; they really shouldn’t be adding anything to the if block. Even if they do, I think I’m paying a pretty high curly bracket tax all over my code to prevent someone from doing something stupid later on.
Is this really that bad?
Perhaps there is a better best practice?
How about if we forgo all the extra curly braces and instead say:
Whenever possible replace an if block with a single statement.
Hmm, I think I like that better. We won’t run the risk anymore of accidentally adding a statement after the if block if we are used to thinking of an if block itself as a code smell.
Almost always you can describe what is being done in an if block with a better name and encapsulate it in a method.
Of course there are exceptions here. In a method with a void return type when you early return in an if block you can’t really replace that with a single statement. (Although sometimes you can avoid the early return by using an if else statement instead.)
We can apply the same thinking to anything that has a block statement.
Strangely though, try and catch require block statements to follow. You cannot have a single statement following a try.
Anyway, at this point I am pretty well convinced that including the { } “just because” is a pretty archaic practice and is unnecessarily cluttering up our code. If I am wrong, tell me why I am wrong, but as far as I can tell, if we prefer to extract statement blocks into methods, we can avoid the curly bracket tax everywhere.