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?
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.
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.
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.
I am using the code formatter of the IDE I use. That might differ, but it can be setup in the Preferences/Options.
I like this one:
I prefer putting a curly brace. But sometimes, ternary operator helps.
In stead of :
One should simply do :
int x = condition ? 30 : 20;
Also imagine a case :
It would be much better if you put the curly brace in.
My personal preference is using a mixture of whitespace and brackets like this:
I think this looks clean and makes my code very easy to read and most importantly - debug.
Personally I use the first style only throw an exception or return from a method prematurely. Like argument Checking at the beginning of a function, because in these cases, rarely do I have have more than one thing to do, and there is never an else.
Example:
Otherwise I use the second style.
From my experience the only (very) slight advantage of the first form is code readability, the second form adds "noise".
But with modern IDEs and code autogeneration (or autocompletion) I strongly recommend using the second form, you won't spend extra time typing curly braces and you'll avoid some of the most frequent bugs.
There are enough energy consuming bugs, people just shoudn't open doors for big wastes of time.
One of the most important rule to remember when writing code is consistency. Every line of code should be written the same way, no matter who wrote it. Being rigorous prevents bugs from "happening" ;)
This is the same with naming clearly & explicitly your variables, methods, files or with correctly indenting them...
When my students accept this fact, they stop fighting against their own sourcecode and they start to see coding as a really interesting, stimulating and creative activity. They challenge their minds, not their nerves !