I've seen code like this:
if(statement)
do this;
else
do this;
I don't like that, I think this is cleaner and more readable
if(statement){
do this;
}else{
do this;
}
Is this simply a matter of preference or would one way be recommended over the other?
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:
From this:
I prefer using braces. Adding braces makes it easier to read and modify.
Here are some links for the use of braces:
Prefer Multiline if
Omitting Braces: Not Just A Matter Of Style
Stack Overflow
I have always tried to make my code standard and look as close to the same as possible. This makes it easier for others to read it when they are in charge of updating it. If you do your first example and add a line to it in the middle it will fail.
Won't work:
if(statement) do this; and this; else do this;
It is a matter of preference. I personally use both styles, if I am reasonably sure that I won't need to add anymore statements, I use the first style, but if that is possible, I use the second. Since you cannot add anymore statements to the first style, I have heard some people recommend against using it. However, the second method does incur an additional line of code and if you (or your project) uses this kind of coding style, the first method is very much preferred for simple if statements:
However, I think the best solution to this problem is in Python. With the whitespace-based block structure, you don't have two different methods of creating an if statement: you only have one:
While that does have the "issue" that you can't use the braces at all, you do gain the benefit that it is no more lines that the first style and it has the power to add more statements.
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
Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:
Looks much nicer like this:
But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!