I have seen different ways of writing an if
statement.
Which one do you prefer and why?
Example 1:
if (val % 2 == 1){output = “Number is odd”;}else{output = “Number is even”;}
Example 2:
if (val % 2 == 1)
{
output = “Number is odd”;
}
else
{
output = “Number is even”;
}
Example 3:
if (val % 2 == 1)
output = “Number is odd”;
else
output = “Number is even”;
Example 4:
if (val % 2 == 1){
output = “Number is odd”;
} else {
output = “Number is even”;
}
It's strange that nobody mentioned this:
To me, this is the only correct way, of course :-)
I use a #2 with a minor change
I prefer #2. Easy readability.
I'd always use #2. #4 is a truly awful layout and would only be done by someone who believes that a method must be one screen size in length and will do anything to cram it in, rather than refactor the code!!!
Version #2 for me - easiest to see, easiest to read, easy to see where the if starts and ends, same for else, you dont have to worry about putting in brackets if you want to add more than one statement.
Example 2 is without a doubt the least error prone approach. Please see this answer I gave to a similar question for the reason why:
What is the prefered style for single decision and action statements?
Although the Visual Studio default for brace usage is to put braces on a newline (my preferred method), the Framework Design Guidelines book (first edition) by Krzysztof Cwalina and Brad Abrams propose a different convention, example 4, placing the opening brace at the end of a preceding
if
statement (Page 274). They also state "Avoid omitting braces, even if the language allows it".Not having the second edition at hand, I couldn't say if these conventions have changed or not.