Showing posts with label rant. Show all posts
Showing posts with label rant. Show all posts

Thursday, 22 May 2008

Rant: Curly Braces

I bumped into an writing called Java: Braces are your friend. While I can see that there are good reasons to use braces after every if statement (or after for, while, do...), the reasoning seemed a bit off.

First of all, it states that the following is allowed, but dangerous:

if (condition)
Exactly one statement to execute if condition is true
else
Exactly one statement to execute if condition is false

Well, all fine and dandy and I can see where it's aiming to. The thing is, that very form is the only form that exists. The braces just serve to gather several statements up to form a single statement, they're by no means part of 'if' syntax.

The first actual reason stated, as to why not leave the braces out, is the following situation

if (condition);
do_something();

Well, OK. I can see how one can accidentally type the semicolon after the if clause. But then again... Hello, it's 2008 calling! You won't believe what cool things our program editors nowadays have. They colour the different parts of code with different colours and you know what: they even indent your code for you! Amazing, ain't it?

if (condition);
do_something();

That certainly doesn't look like such a big error anymore. Also, if one can go and write an extra semicolon after the if clause, why couldn't this happen as well?

if (condition); {
do_something();
}

Even automatic indenting won't save you from that!

The other reason is one, I think I've seen quoted a few too many times:

if (condition)
do_something();
do_something_else();

Yes, the old case of "What if someone later on wants to add more functionality to the if block?" Well, 2008 calling again and all that. Try writing that to any even semi-decent programming editor. It becomes this:

if (condition)
do_something();
do_something_else();

Not so dangerous error anymore, either. You can clearly see that the second statement doesn't belong to the if block.

Also, it crossed my mind that both these errors become invalid code, if you have an else block after that if. That's pretty much a corner case though.