Is it a bad practice to use an if-statement without curly braces? [closed]
I've seen code like this:
if(statement)
do this;
else
do this;
However, I think this is more readable:
if(statement){
do this;
}else{
do this;
}
Since both methods work, is this simply a matter of preference which to use or would one way be recommended over the other?
The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.
Maintainability-wise, it's always smarter to use the second form.
EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html
One problem with leaving out statement blocks is the else-ambiguity. That is C-inspired languages ignore indentation and so have no way of separating this:
if(one)
if(two)
foo();
else
bar();
From this:
if(one)
if(two)
foo();
else
bar();
My general pattern is that if it fits on one line, I'll do:
if(true) do_something();
If there's an else clause, or if the code I want to execute on true
is of significant length, braces all the way:
if(true) {
do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}
if(false) {
do_something();
} else {
do_something_else();
}
Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.
The "rule" I follow is this:
If the "if" statement is testing in order to do something (I.E. call functions, configure variables etc.), use braces.
if($test)
{
doSomething();
}
This is because I feel you need to make it clear what functions are being called and where the flow of the program is going, under what conditions. Having the programmer understand exactly what functions are called and what variables are set in this condition is important to helping them understand exactly what your program is doing.
If the "if" statement is testing in order to stop doing something (I.E. flow control within a loop or function), use a single line.
if($test) continue;
if($test) break;
if($test) return;
In this case, what's important to the programmer is discovering quickly what the exceptional cases are where you don't want the code to run, and that is all coverred in $test, not in the execution block.