views:

591

answers:

16

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?

A: 

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;

Joe
+35  A: 

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.

clee
And you should always code for maintainability. After all, I'm pretty sure the compiler doesn't care which form you use. Your coworkers, however may be pist if you introduce a bug because of a silly curly brace error.
Esteban Araya
Or you could use a language that doesn't use brackets for code blocks...
Tor Valamo
@Tor Valamo: Pascal uses `begin`/`end` instead of curly braces and you can run into exactly the same problems. I assume you really mean languages in which you have to explicitly close if statements with something like an `end if`.
lins314159
@lins314159 - No, I mean like python. Because I'm chauvinistic in this regard.
Tor Valamo
+6  A: 

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:

if (statement)
{
    // comment to denote in words the case
    do this;
    // keep this block simple, if more than 10-15 lines needed, I add a function for it
}
else
{
    do this;
}
Pentium10
This being an entirely subjective style issue, I personally don't like the redundancy of the brace-only lines. But hey.
Matchu
I support this style. Most people read code from left to right and it sort of makes our eyes anchored to left edge of screen. It helps to visually separate and extract code to logical blocks of steps.
mloskot
I've always preferred this style. Much easier to find the corresponding closing parenthesis. So it takes a lot of space ? Use a smaller font.
timday
I'm with mloskot and timday - I've always found that embedding the braces (essentially 'control' characters) in the rest of the code makes code harder to read. Splitting them out on separate lines helps make the logical blocks more distinct.
Mark Brittingham
This is the only style I consider readable.
Daniel Daranas
I always find it easier to "scan" through code when the braces are on separate lines. That goes for everything; classes, methods, if- and while-statements, et cetera. Never liked having that first brace on the same line...
Svish
Whitespace is cheap, especially when you have a code folding capable IDE.
Moo
+6  A: 

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.

Matchu
+3  A: 

Having the braces right from the first moment should help to prevent you from ever having to debug this:

if (statement)
     do this;
else
     do this;
     do that;
Matt Bishop
That seems to be the accepted rationale, but (to play devil's advocate here) wouldn't a single additional syntax-highlighting rule also solve this, while saving one line?
Ken
So will having an IDE that corrects the indentation when you hit `;` :)
280Z28
+1  A: 

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:

if(statement)
{
    do this;
}
else
{
    do this;
}

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:

if statement:
    do this
else:
    do this

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.

chpwn
I by myself think the way how Python handles if-else statements is very ugly, but then again, I'm no Python programmer (yet)
Helper Method
Why do you think that?
chpwn
A: 

I prefer the first...

if(true){
    doSomething;
}
doSomethingElse;
//follow blank line
Alexander
A: 

I agree with most answers in the fact that it is better to be explicit in your code and use braces. Personally I would adopt a set of coding standards and ensure that everyone on the team knows them and conforms. Where I work we use coding standards published by IDesign.net for .NET projects.

Kane
+1  A: 

Use braces for all if statements even the simple ones. Or, rewrite a simple if statement to use the ternary operator:

if (someFlag) {
 someVar= 'someVal1';
} else {
 someVar= 'someVal2';
}

Looks much nicer like this:

someVar= someFlag ? 'someVal1' : 'someVal2';

But only use the ternary operator if you are absolutely sure there's nothing else that needs to go in the if/else blocks!

pygorex1
A: 

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:

if (argument == null)
    throw new ArgumentNullException("argument");

if (argument < 0)
    return false;

Otherwise I use the second style.

Nate Heinrich
A: 

I prefer using braces. Adding braces makes it easier to read and modify.

Here are some links for the use of braces:

mangoDrunk
+2  A: 

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();
doynax
A: 

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 !

luxquarta
A: 

It looks like more people are wondering about good and bad practices related to braces for statements: Style of curly brackets--just personal preference?

Here are older very related questions with plenty of answers:

mloskot
A: 

My personal preference is using a mixture of whitespace and brackets like this:

if( statement ) {

    // let's do this

} else {

    // well that sucks

}

I think this looks clean and makes my code very easy to read and most importantly - debug.

Simon
A: 

I prefer putting a curly brace. But sometimes, ternary operator helps.

In stead of :

int x = 0;
if (condition) {
    x = 30;
} else {
    x = 10;
}

One should simply do : int x = condition ? 30 : 20;

Also imagine a case :

if (condition)
    x = 30;
else if (condition1)
    x = 10;
else if (condition2)
    x = 20;

It would be much better if you put the curly brace in.

fastcodejava