tags:

views:

1446

answers:

40

This isn't a holy war, this isn't a question of "which is better".

What are the pros of using the following format for single statement if blocks.

if (x) print "x is true";

if(x) 
    print "x is true";

As opposed to

if (x) { print "x is true"; }
if(x) {
    print "x is true";    
}

If you format your single statement ifs without brackets or know a programmer that does, what led you/them to adopt this style in the first place? I'm specifically interested in what benefits this has brought you.

Update: As the most popular answer ignore the actual question (even if it presents the most sane advice), here's a roundup of the bracket-less pros.

  1. Compactness
  2. More readable to some
  3. Brackets invoke scope, which has a theoretical overhead in some cases
+29  A: 

I strongly dislike any style that places the if's test and body on the same line.

This is because sharing the line makes it impossible to set a breakpoint on the if's body in many debuggers because breakpoints are typically line number based.

Don Neufeld
I agree, but tons of programmers seem to disagree. They must have their reasons.
Alan Storm
Visual Studio 2008 (2005?) is able to debug per statement, not per line.
spoulson
What about "if (blah) { return; }"? Seems pretty harmless to me, even if you're trying to set a breakpoint there.
Parappa
Yeah, but if you split up every if-statement in test and instruction on separate lines, then you should do so for if-x-return statemnts, for the sake of consistenncy.
Aleksandar Dimitrov
There are always exceptions (talk about a logic knot...) "A foolish consistency is the hobgoblin of little minds."
Matt Dillard
+3  A: 

Whitespace is your friend ....

but, then again, I like:

if (foo)
{
    Console.WriteLine("Foobar");
}
MagicKat
+34  A: 

I find this:

if( true ) {
    DoSomething();
} else {
    DoSomethingElse();
}

better than this:

if( true )
    DoSomething();
else
    DoSomethingElse();

This way, if I (or someone else) comes back to this code later to add more code to one of the branches, I won't have to worry about forgetting to surround the code in braces. Our eyes will visually see the indenting as clues to what we're trying to do, but most languages won't.

Matt Dillard
Also, if 'DoSomething' happens to a multi-line macro you can run into problems.
Trent
I also like the convention of starting and ending all if statements with brackets, even if it only contains 1 command... By the way the reason why this 'feature' was introduced was (probably) because back in the early days of programming, it was desired to have to type as little as possible...
Sven
I agree, but less important these days when auto-formatting editors like Eclipse and NetBeans will fix your indenting for you which will tell you right away that something is wrong (assuming you hit the "fix code" key sequence often.)
Bill K
I prefer the second block. All the brackets just tangle up the code and make it easy to spot the error if you bung them up. I've been "braketless" if statement approach for years and have never had the problem of forgetting to add brackets when adding a new line.
nbv4
+17  A: 

I always use

if(x) 
{
    print "x is true";    
}

leaving out the braces can result in someone maintaining the code mistakenly thinking they are adding to the if clause if they add a line after the current line.

Aside: Which is why I also like Python's indention awareness. You're going to indent anyway, might as well make it mean something. This argument only occurs in languages that make blocking characters ({ } in this case) optional/conditional.
toast
I agree with Ferruccio (http://stackoverflow.com/questions/97506/formatting-of-if-statements/98569#98569) that your argument is pretty weak. This is such an easy mistake to make that it's also drilled into the heads of new programmers to the point where they (at least, I) recognize and correct it unconsciously.
Chris Lutz
+6  A: 
if
{
// code
}
else 
{
// else code
}

because i like when blocks of code line up (including their braces).

Darren Kopp
That's terrorism against code aesthetics! I wouldn't want to work with that code.
piotr
If the comments (code) were indented, this is the form I find most legible. If the code inside the braces was not indented, then it is horrid. I usually don't put the braces in place unless there are several statements in the block - but I don't mind when they are inserted uniformly.
Jonathan Leffler
ewwww I hate that. :( sorry.
micmoo
A: 

For me, braces make it easier to see the flow of the program. It also makes it easier to add a statement to the body of the if statement. When there aren't braces, you have to add braces to add another statement.

I guess the pros of not using braces would be that it looks cleaner and you don't waste a line with a closing brace.

yjerem
A: 

Lines spacing and indentation can do alot for readability.

As far as readability I prefer the following:

// Do this if you only have one line of code
// executing within the if statement
if (x)
    print "x is true";

// Do this when you have multiple lines of code
// getting executed within the if statement    
if (x)
{
    print "x is true";
}
Chris Pietschmann
+6  A: 

If I code:

if(x) 
    print "x is true";

and 6 months later need to add a new line, the presence of curly braces makes it much less likely that I'll type

if(x) 
    print "x is true";
    print "x is still true";

which would result in a logical error, versus:

if(x) { 
    print "x is true";
    print "x is still true";
}

So curly braces make such logical errors easier to read and avoid, I find.

ConroyP
THIS. A million times: THIS.
Zack Peterson
+1  A: 

I prefer the bracketed style, mainly because it gives the eyes a clear start and stop point. It makes it easier to see what is actually contained in the statement, and that it actually is an if statement. A small thing, perhaps, but that's why I use it.

Alex King
+1  A: 

so long as it is consistent amongst the team you work in then it doesnt matter too much

that everyone does the same is the main thing

Christo Fur
See, I disagree with the "as long as you're consistent" rule. There are certain styles that can help you eliminate errors from your programming, and most programmers are human beings who will occasionally be inconsistent in their style.
Alan Storm
+4  A: 

I use

if (cond) {
  ...
} else {
  ...
}
  • Everything should always have braces. Even if now I only have one line in the if block, I made add more later.
  • I don't put the braces on their own lines because it's pointless waste of space.
  • I rarely put the block on the same line as the conditional for readability.
Lucas Oman
+2  A: 
if (x)
{
    print "x is true";
}

Opening and closing brace in same column makes it easy to find mismatched braces, and visually isolates the block. Opening brace in same column as "if" makes it easy to see that the block is part of a conditional. The extra white space around the block created by the rows containing just braces makes it easy to pick it out the logical structure when skimreading code. Always explicitly using braces helps avoid problems when people edit the code later and misread which statements are part of the conditional and which are not - indentation may not match reality, but being enclosed in braces always will.

moonshadow
+1  A: 

Bracketing your one-liner if statements has the considerable sane-making advantage of protecting you from headaches if, at some later point, you (or other coders maintaining or altering your code) need to add statements to some part of that conditional block.

Josh Millard
+5  A: 

Single statement if blocks lacking braces:

Pros:

  • fewer characters
  • cleaner look

Cons:

  • uniformity: not all if blocks look the same
  • potential for bugs when adding statements to the block: a user may forget to add the braces and the new statement would no be covered by the if.

As in:

if(x) 
    print "x is true";
    print "something else";
Matthew Jaskula
+1  A: 

No matter what, this is the way I go ! It looks the best.

If(x)
{
   print "Hello World !!"
}
Else
{
   print "Good bye!!"
}

+1  A: 

If you're curious what the names for the various code formatting styles are, Wikipedia has an article on on Indent Styles.

Schnapple
+4  A: 
Zack Peterson
I find this argment non-compelling. I always have.
Jonathan Leffler
+1  A: 

If you do something like this:

if(x)
{
    somecode;
}
else
{
    morecode;
}

This works out better for source control and preprocessor directives on code that lives a long time. It's easier to add a #if or so without inadvertently breaking the statement or having to add extra lines.

it's a little strange to get used to, but works out quite well after a while.

mike511
A: 

I wish the IDE would enforce this behaviour. As you correctly pointed out there is no "right" behaviour. Consistency is more important ... it could be either style.

Learning
+10  A: 

I use

if (x)
{
    DoSomething();
}

for multiple lines, but I prefer bracketless one liners:

if (x)
   DoSomething();
else
   DoSomethingElse();

I find the extraneous brackets visually offensive, and I've never made one of the above-mentioned mistakes not adding brackets when adding another statement.

Matt
+1. It seems the main argument people seem to have against bracket-less if statements is fear that they'll forget to add the brackets when adding a new line of code. Yet I've never heard any real world instances of someone having a problem with doing that. I've been "bracket-less" pretty much since I started programming and have never had a problem forgetting to add the brackets.
nbv4
+1 - I agree that one-liner if()s are perfectly okay. Anyone adding to your code should be experienced enough to know that they have to add brackets if they add more lines. Anyone who doesn't know at least that much will not be working anywhere near my code.
Chris Lutz
+2  A: 

Seriously, when's the last time you had a bug in any code anywhere that was cause someone did:

if (a)
  foo();
  bar();

Yeah, never...* The only real 'pro' here is to just match the style of the surrounding code and leave the aesthetic battles to the kids that just got outta college.

*(caveat being when foo(); bar(); was a macro expansion, but that's a problem w/ macros, not curly braces w/ ifs.)

Jeff
Not a lot, but I have seen it
johnc
I've done it more than once. In one case, a beta version of a bot I was writing had a rather nasty security bug because of the lack of braces.
epochwolf
yep, I've seen that happen too.
nickf
I've never had a bug because of that......because I'm smart enough to always use braces so it can't happen. If you don't...it will.
Cody Hatch
Visual Studio would correct the misleading format with it's auto format feature (not sure if other IDE's have similar features). Still the only time I really leave out the brackets is when my if condition either returns, breaks, or throws an exception.
ebrown
+4  A: 

I tend only to single line when I'm testing for break conditions at the beginning of a function, because I like to keep this code as simple and uncluttered as possible

public void MyFunction(object param)
{
     if (param == null) return;

     ...
}

Also, if I find I do want to avoid braces and inline an if clause code, I may single line them, just so it is obvious to anyone adding new lines to the if that brackets do need to be added

johnc
+6  A: 

Like Matt (3 above), I prefer:

if (x)
{
    ...statement1
    ...statement2
}

and

if (x)
    ...statement
else
    ...statement

I think its pretty strange to think that someone may come along later and NOT realise they have to add the braces to form a multi-line if block. If that's beyond their capabilities, I wonder what other things are!

Jason Hanford-Smith
+4  A: 

I dislike using braces when they're not required. I feel like it bloats the number of lines in a method and makes it unreadable. So I almost always go for the following:

if (x)
   print "x is true"
for (int i=0; i<10; i++)
   print "y is true"

And so forth. If someone needs to add another statement then he can just add the braces. Even if you don't have R# or something similar it is a very small deal.

Still, there are some cases that I would use braces even if there is only one line in the statement, and that is if the line is especially long, or if I need comments inside the that 'if'. Basically, I just use whatever seems nicer to my eyes to look at.

Doron Yaacoby
+1  A: 

If it's one line of if (and optionally one line of else) I prefer to not use the brackets. It's more readable and concise. I say that I prefer it because it is purely a matter of preference. Though I think that trying to enforce a standard that you must always use the braces is kind of silly.

If you have to worry about someone adding another line to the body of the if statement and not adding the (only then required) braces, I think you have bigger problems than sub-byzantine coding standards.

Arthur Vanderbilt
I wish I could give this more than one upvote - this sums up how I feel exactly.
Bill Forster
+3  A: 
if (x) {
    print "x is true";    
}
else {
    do something else;
}

I always type braces. It's just a good habit. Compared to thinking, typing is not "work".

Note the space before the conditional. That helps it look not like a method call.

Kevin Conner
+18  A: 

Always using braces is a good idea but the standard answer that's always given "what if somebody adds a line of code and forgets to add the braces?" is a rather weak reason.

There is a subtle bug which can be introduced by not having the braces from the start. It's happened to me a few times and I've seen it happen to other programmers.

It starts out, innocently enough, with a simple if statement.

if (condition)
    do_something();
else
    do_something_else();

Which is all well and good.

Then someone comes along and adds another condition to the if. They can't add it using && to the if statement itself because the logic would be incorrect, so they add another if. We now have:

if (condition)
    if (condition2)
        do_something();
else
    do_something_else();

Do you see the problem? It may look right but the compiler sees it differently. It sees it like this:

if (condition)
    if (condition2)
        do_something();
    else
        do_something_else();

Which means something completely different. The compiler doesn't care about formatting. The else goes with the nearest if. Humans, on the other hand, rely on formatting and can easily miss the problem.

Ferruccio
Good thinking - I guess that's one of the advantages of something like Python where indentation does have syntactical value.
Rich Bradshaw
...Or just reformat often.
Bill K
ps... NEVER nest ifs without adding braces if they aren't already there. The concept that someone might do what the author said hurts my soul.
Bill K
A: 

I feel like outvoted so far, but I'll vouch for one of:

if (expr) {
   funcA();
}
else {
   funcB();
}

Or, shorthand in limited cases for readability:

if (expr) funcA();
else funcB();

To me, the shorthand format is nice when you want it to read like English grammar. If the code doesn't look readable enough, I'll break out the lines:

if (expr)
   funcA();
else
   funcB();

With careful consideration I don't put nested conditionals within the if/else blocks to avoid coder/compiler ambiguity. If it's any more complex than this, I use the braces on both if and else blocks.

spoulson
+1  A: 
/* I type one liners with brackets like this */
if(0){return(0);}
/* If else blocks like this */
if(0){
    return(0);
}else{
    return(-1);
}

I never use superfluous whitespace beyond tabs, but always including the brackets saves heaps of time.

jbcreix
I wouldn't consider adding a space between the "if" and its bracket as "superfluous". I bet you're one of those people who write "if(x=1){x=y+z;}" I find that one of the most hard-to-read coding styles there is...
nickf
+2  A: 

About the only time no-bracing seems to be accepted is when parameter checking variables at the start of a method:

public int IndexOf(string haystack, string needle)
{
    // check parameters.
    if (haystack == null)
        throw new ArgumentNullException("haystack");
    if (string.IsNullOrEmpty(needle))
        return -1;

    // rest of method here ...

The only benefit is compactness. The programmer doesn't have to wade throught un-necessary {}'s when it's quite obvious that:

  • the method exits on any true branch
  • it's fairly obvious these are all 1-liners

That said, I would always {} for program logic for the reasons stated by others. When you drop the braces it's too easy to mentally brace when it's not there and introduce subtle code defects.

Robert Paulson
A: 

Any formatting of this type is fine. People will argue with you black and blue over this because it is something easy to understand. People like to talk about things they understand instead of dealing with bigger problems such as good design and solving hard problems with new algorithms. I tend to prefer no brackets for simple one-liners. However, I am also happy to read it with brackets. If there is a particular style guide for a given project I prefer to follow that. I believe in consistency over some subjective ideal of correctness.

My personal choice for no brackets for one-liners is due to typing less characters, shorter code and succinctness.

cdv
A: 

Use a real language like Visual Basic!!1!1!

/snark

Zack Peterson
A: 

Of the options provided, I'd go with

if (x) {
  print "x is true";    
}

simply by virtue of the braces being habit to type.

Realistically, though, as a mostly-Perl programmer, I'm more likely to use

print "x is true" if x;

(Which always trips me up when I'm working in a language which doesn't support postfix conditionals.)

Dave Sherohman
A: 

I prefer single line statements with out brackets, I know that there is the danger that I can forget to add them when I insert a new line of code, but I cannot remember the last time this happened. My editor (vim) prevents me to write things like this:


if (x)
    x = x + 1;
    printf("%d\n", x);

because it will indent it differently. The only thing I had problems with, are bad written macros:


#define FREE(ptr) {free(ptr); ptr = NULL;}

if (x)
    FREE(x);
else
    ...

This doesn't work of course, but I think it is better to fix the macro, to avoid those possible bugs or problems instead of changing the formating style.

So there are possible problems with that way of formating, but they are imho not fatal. It ends up to be a matter of taste.

quinmars
A: 

I haven't seen anyone mention the most useful reason to place the bracket on the same line as the if -- bracket matching in emacs. When you place the cursor on the ending bracket, emacs shows the line with the matching start bracket. Placing the start bracket on its own line, negates the feature.

David Medinets
A: 

I prefer the following...i think it looks cleaner.

if(x)
{
    code;
}
else
{
     other code;
}
Dan Adams
A: 

I dislike closing braces on the same line with the follow keyword:

if (x) {
    print "x is true";    
} else {
    do something else;
}

This makes it harder to remove/comment-out just the else clause. By putting the follow keyword on the next line, I can take advantage of, for example, editors that let me select a range of lines, and comment/uncomment them all at once.

if (x) {
    print "x is true";    
}
//else {
//    do something else;
//}
Chris Noe
+1  A: 

I always prefer this:

if (x) doSomething();

if (x) {
    doSomthing();
    doOtherthing();
}

But always depend on the language and the actions you're doing. Sometimes i like to put braces and sometimes not. Depend on the code, but i coding like a have to write once, re-write ten times, and read one hundred times; so, just do it like you want to and like you want to read and understand more quickly

unkiwii
A: 

I guess I'm more of an outlier than I thought; I haven't noticed this one yet.

I'm a fan of

if (x)
{ foo(); }

It feels compact & readable (I hate sprawling braces), but it makes the scope of the condition explicit.

It's also more breakpoint-friendly than single-line if's. It also feels more at home in my braces-on-newline world:

if (x)
{ foo(); }
else
{
   bar();
   baz();
}

Edit: it appears I misread the original question, so this answer off-topic. I'm still curious about any response, though.

TSomKes
A: 

One liners are just that... one liners and should remain like this :

if (param == null || parameterDoesNotValidateForMethod) throw new InvalidArgumentExeption("Parameter null or invalid");

I like this style for argument checking for example,it is compact and usually reads easily. I used to put braces with indented code all the time but found that in many trivial cases it just wasted spaces on the monitor. Dropping the braces for some cases allowed me to get into the meat of methods faster and made the overall presentation easier on the eyes. If however it gets more involved then I treat it like everything else and I go all out with braces like so :

if (something)
{
    for(blablabla)
    {
    }
}else if
{
 //one liner or bunch of other code all get the braces
}else
{
  //... well you get the point
}

This being said... I despise braces on the same line like so :

if(someCondition) { doSimpleStuff; }

of worst

if(somethingElse){
  //then do something
}

It is more compact but I find it harder to keep track of the braces.

Overall it's more a question of personal taste so long as one does not adopt some really strange way to indent and brace...

    if(someStuff)
        {
  //do something
        }
Newtopian