views:

4317

answers:

51

Why does everyone tell me writing code like this is a bad practice?

if (foo)
    Bar();

//or

for(int i = 0 i < count; i++)
    Bar(i);

My biggest argument for omitting the curly braces is that it can sometimes be twice as many lines with them. For example, here is some code to paint a glow effect for a label in C#.

using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
{
    for (int x = 0; x <= GlowAmount; x++)
    {
        for (int y = 0; y <= GlowAmount; y++)
        {
            g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));
        }
     }
 }
 //versus
using (Brush br = new SolidBrush(Color.FromArgb(15, GlowColor)))
    for (int x = 0; x <= GlowAmount; x++)
        for (int y = 0; y <= GlowAmount; y++)
            g.DrawString(Text, this.Font, br, new Point(IconOffset + x, y));

You can also get the added benefit of chaining usings together without having to indent a million times.

using (Graphics g = Graphics.FromImage(bmp))
{
    using (Brush brush = new SolidBrush(backgroundColor))
    {
        using (Pen pen = new Pen(Color.FromArgb(penColor)))
        {
            //do lots of work
        }
    }
 }
//versus
using (Graphics g = Graphics.FromImage(bmp))
using (Brush brush = new SolidBrush(backgroundColor))
using (Pen pen = new Pen(Color.FromArgb(penColor)))
{
    //do lots of work
}

The most common argument for curly braces revolves around maintance programming, and the problems that would ensue by inserting code between the original if statement and its intended result:

if (foo)
    Bar();
    Biz();

Questions:

  1. Is it wrong to want to use the more compact syntax which the language offers? The people that design these languages are smart, I can't imagine they would put a feature which is always bad to use.
  2. Should we or Shouldn't we write code so the lowest common denominator can understand and have no problems working with it?
  3. Is there another argument that I'm missing?
+2  A: 

Let's say you have some code:

if (foo)
    bar();

and then someone else comes along and adds:

if (foo)
    snafu();
    bar();

According to the way it's written, bar(); is now executed unconditionally. By including the curly braces, you prevent this kind of accidental error. Code should be written in such a way as to make such mistakes difficult or impossible to make. If I was doing a code review and saw the missing braces, especially spread across multiple lines, I would create a defect. In cases where it is justified, keep it on one line so that the chance of making such an error is again kept to a minimum.

Elie
That point was already made in the question.
Mike Scott
Not quite, actually. Yes, he mentioned the potential for this kind of bug, but I was talking about making your code bug-proof and removing potential for error as part of best practices.
Elie
Is there really such a thing as bug proof code?
Bob
@Bob, only in RAID systems.
Robert S.
No, but you can make it more difficult. Read "Best Kept Secrets of Peer Code Review" by Jason Cohen (see link at the side of some pages here) to get a better idea of why you do this.
Elie
Who is this Mike Scott and why is he the answer police? It always cracks me up that people have to state what's obvious. So why didn't Mike continue to comment on the added description that users are posting about this issue. Aren't all answers referring to the question?
bruceatk
A: 

Your maintanence programmer may forget to add curly braces later if he/she adds logic to the app. So the following happens:

if(foo)
bar();
bar(delete);

Instead of

if(foo) {
bar();
}
 bar(delete);
George Stocker
That point was made in the question.
Mike Scott
Mike: Then shouldn't it be closed as 'not a real question'? Others made that point, did you vote them down as well? In the end, that's the actual answer as to why it's a bad practice.
George Stocker
I think he's trying to get more badges
Elie
That indentation is horrible.
recursive
+7  A: 

There are always exceptions, but I would argue against omitting braces only when it's in one of the forms:

if(x == y)
   for(/* loop */)
   {
      //200 lines
   }

//rampion's example:
for(/* loop */)
{
   for(/* loop */)
      for(/* loop */)
      {
         //several lines
      }
}

Otherwise, I have no problem with it.

Tom Ritter
Bad examples. In both of those cases, I would factor that 200 line for loop into its own method, or preferably several methods.
Adam Jaskiewicz
True, but it DOES happen. Plus, any time a block is longer than the reader's screen is high, you'll have this issue. And you can't control your code reader's screen height. They might only see a couple lines on each side.
rampion
It does happen. That doesn't mean it *should* happen.
Adam Jaskiewicz
+82  A: 

Actually, the only time that's ever really bit me was when I was debugging, and commented out bar():

if(foo)
  // bar();
doSomethingElse();

Other than that, I tend to use:

if(foo) bar();

Which takes care of the above case.

EDIT Thanks for clarifying the question, I agree, we should not write code to the lowest common denominator.

Zachary Yates
That's rough of course, but I think the biggest problem for maintainers is that they will add a second line, and not realize it's not a part of the conditional statement even though it REALLY looks like it should be.
danieltalsky
I don't like the one liner style because I always go looking for the loop body below.
Nosredna
I find the one-liner style more irritating than helpful because (especially in deep nesting -- ugh) the statement can be easily overread and confusion may ensue. I almost exclusively use such single-statement ifs for input validation (i.e. early returns) or loop control (e.g. ignoring irrelevant file names in filesystem walks), though, where blank lines help setting them off from the main code.
Alan
+7  A: 

I occasionally use the very bottom code (multiple using statements), but other than that I always put the braces in. I just find it makes the code clearer. It's blatantly obvious from more than just indentation that a statement is part of a block (and thus probably part of an if etc).

I have seen the

if (...)
    foo();
    bar();

bug bite me (or rather "me and colleagues" - I didn't actually introduce the bug) once. This was despite the fact that our coding standards at the time recommended using braces everywhere. It took me a surprisingly long time to spot - because you see what you want to see. (This was about 10 years ago. Maybe I'd find it faster now.)

Of course if you use "brace at the end of the line" it reduces the extra lines incurred, but I personally dislike that style anyway. (I use it at work, and have found it less unpleasant than I expected, but it's still a bit unpleasant.)

Jon Skeet
I always argue the case that consistency is more important than actual style, why should we make an exception only in the case of usings?
Bob
@Bob: Good point, and I do only do it occasionally. I wouldn't like to pretend that I have actual reasons here :) Actually, there's a reasonable reason - nesting the usings (and only usings) like that is fairly obvious, and you still end up with *a* block. I can't immediately see the danger.
Jon Skeet
Which is not to say that there *isn't* any danger, of course.
Jon Skeet
Best solution to this bug: Use Python. (Kidding, of course.)
Joel Wietelmann
+4  A: 

Most times it is ingrained as a coding standard, whether for a company or an FOSS project.

Ultimately someone else will need to grok your code and it is a major time drain for each developer to have to figure out the specific style of the section of code they are working on.

Also, imagine that someone is going between Python and a Cish language more than once a day... In Python indenting is part of the block symantics of the language and it would be quite easy to make a mistake like the one you quote.

joshperry
+1 for comment about python. I'm always amazed how "stupid" I can be when continuously switching between languages.
Kena
+6  A: 

One of the main issues is when you have regions of one-liners and non-one liners, along with separation from the control statment (for, if, what have you) and the end of the statment.

For example:

for (...)
{
  for (...)
    for (...) 
    {
      // a couple pages of code
    }
  // which for block is ending here?  A good text editor will tell you, 
  // but it's not obvious when you're reading the code
}
rampion
Why do you have a couple pages of code in your for loop anyway?
Adam Jaskiewicz
b/c I'm an insensitive clod, and I'm obsessed with getting rid of the "cost" of function calls. :)
rampion
The couple of pages of code should be in a separate function, usually.
Jonathan Leffler
excuse me, I meant I was playing the role of such a clod. However, I hold that the same problem can occur for shorter regions, when viewed through a small viewport. And that's outside the coder's control.
rampion
+6  A: 

I agree that "if you are smart enough to get someone to pay you to write code, you should be smart enough to not rely solely on indentation to see the flow of the code."

However... mistakes can be made, and this one is a pain to debug... especially if you're coming in looking at someone else's code.

chills42
A: 

It is a tradeof, shorter code (better readable) versus more secure code (less error prone).

My 2 cents:

  1. There is a reason for this rule. It has been developed by countless programmers through long working hours, stretching into the night or next morning, trying to fix a bug that was caused by a little oversight.
  2. You have t decide for yourself if the tradeof is worth it.
  3. In my experience it is, I am one of those countless programmers who was working into the night to find the cause for a nasty bug. The cause was me being lazy.
Treb
The countless programmers in point 1, are they industry leaders that we should be following, or the LCD type of programmer?
Bob
They are our forefathers, those mythical figures who in ancient times laid the foundation of our craft as we know it today. We will forever be in their dept. One of the many important works they did was the abolishment of the evil know as GOTO. (Ancient times = 1970s to 1990s)1970s to 1990s
Treb
+2  A: 

in order to keep the code with braces from taking up lots of space, I use the technique recommended in the book Code Complete:

if (...) {
    foo();
    bar();
}
else {
    ...
}
Nathan Prather
I dont get why it was downmodded it saves one line for every bracket pair i use it all the time
Eric
jmucchiello
Thanks! I figured it was just personal taste. I used to find this syntax annoying myself, but I adopted it after reading Code Complete, and really enjoy it now.
Nathan Prather
i was reading all the answers above this one thinking "why has no one suggested this yet???" It makes the closing bracket align with the block which it is closing, that is "if" or "while", etc, not a meaningless "{". +1.
nickf
+3  A: 

I always omit them when appropriate, such as in your first example. Clean, concise code I can see and understand by glancing at is easier to maintain, debug and understand than code I have to scroll through and read line by line. I think most programmers will agree with this.

It is easy for it to get out of hand if you start doing multiple nesting, if/else clauses and so on, but I think most programmers should be able to tell where to draw the line.

I see it kind of like the argument for if ( foo == 0 ) vs if ( 0 == foo ). The latter may prevent bugs for new programmers (and maybe even occasionally for veterans), while the former is easier to quickly read and understand when you're maintaining code.

Marc Charbonneau
+6  A: 

Your main arguments against using braces are that they use additional lines and that they require additional indenting.

Lines are (almost) free, minimizing the number of lines in your code shouldn't be an objective.

And indentation is independent of brace usage. In your cascading 'using' example I still think you should be indenting them even when you omit the braces.

Paul Mitchell
+6  A: 

I used to be a huge supporter of "curly braces are a MUST!", but since adopting unit testing, I find that my unit tests protect braceless statements from the scenarios like:

if (foo)
    snafu();
    bar();

With good unit tests, I can confidently omit curly braces for simple statements to improve readability (yes, that can be subjective).

Alternatively, for something like the above, I would likely inline that to look like:

if (foo) snafu();

That way, the developer who needs to add bar() to the condition, would be more apt to recognize the lack of curly braces, and add them.

Liggy
You said "I don't need it" then gave a reason for using it: readability!
tvanfosson
I wouldn't rely on a Unit Test to find that. LINT maybe, Unit test no!
Kristen
@Kristen - The idea of the unit test is to assert the behavior of the method. If the behavior changes (as described above) the unit test will fail. I don't see the problem in that.
Liggy
+34  A: 

If it's something small, write it like this:

if(foo()) bar();

If it's long enough to break into two lines, use braces.

Adam Jaskiewicz
yeah, that's what I do too. It forces you to add braces if you add another line, and it's pretty clear to see that bar() is actually part of the if, so bad things will happen if you just comment it out.
jalf
Not very debugger-friendly, though. How do you set up a breakpoint on the "bar" part?
Nemanja Trifunovic
@Nemanja: Just put your cursor on bar(); and hit F9. Both VS2005 and VS2008 handle intra-line breakpoints, if they're separate "statements".
GalacticCowboy
GalanticCowboy: There are more environments than those you know. :-)
DeletedAccount
Sure, but since the context is C#, that should cover a significant majority of the users...
GalacticCowboy
+26  A: 

I prefer the clarity that the curly brace offers. You know exactly what is meant and don't have to guess if someone just goofed and left them off (and introduced a bug). The only time I omit them is when I put the if and action on the same line. I don't do that very often either. I actually prefer the whitespace introduced by putting the curly brace on its own line, though from years of K&R C-like programming, ending the line with a brace is a practice I have to work to overcome if the IDE doesn't enforce it for me.

if (condition) action();  // ok by me

if (condition) // normal/standard for me
{
   action();
}
tvanfosson
+8  A: 

My philosophy is if it makes the code more readable, why not do it?

Obviously you have to draw the line somewhere, like finding that happy medium between concise and overly descriptive variable names. But brackets really do avoid errors and improve the readability of the code.

You can argue that people smart enough to be coders are going to be smart enough to avoid bugs that stem bracketless statements. But can you honestly say you've never been tripped up by something as simple as a spelling error? Minutia like this can be overwhelming when looking at large projects.

James McMahon
Of course this is very subjective. Leaving them off sometime improves the readability.
Brian Knoblauch
True, if I ever leave the brackets out, I keep one line, like others have mentioned. I've been bitten too many times but multi line bracketless statements. Even if you know to look out for it, it can still occasionally get you.
James McMahon
A: 
TcKs
Closing brackets should always be at the level of the block, never trailing the end of the last line.
recursive
+15  A: 

This is not always considered a bad practice. The Mono Project Coding Guidelines suggests not to use curly braces if it's not necessary. The same for the GNU Coding Standards. I think it's a matter of personal taste as always with coding standards.

Manuel Ceron
Looking at Mono code seems quite **foreign** to me after reading the whole guideline.
Sung Meister
A: 

I don't think that omitting braces is always a bad practice but whether is should be allowed and under what circumstances must be agreed in the team.

I find this very readable:-

if (foo)
    bar();

and this:-

if (foo)
    bar()
else
    snafu();

If an extra line is added to these:-

if (foo)
    bar();
    snafu();

This looks all wrong, there is a block of code, indented. but not braced.

A similar argument holds for a for loop. However when I start nesting:-

if (foo)
    if (bar)
        snafu()

Now I'm running into trouble, it looks like a block of statements. Personally I would only skip the use of braces for one level only any deeper an I'd make the outer code use braces:-

if (foo) {
   if (bar)
       snafu()
}

As I'm typing this I've seen the answers jump from 1 to 17, clearly this going to be an emotive question (I suggest you add subjective to the tag list (my ability to do this has gone missing whats up with that?)).

The most important thing is to have agreement in the team as to if and how its acceptable and stick with it.

AnthonyWJones
Brian
A: 

AFAIR curly braces are always a scope, so for that it is good to use them everytime.

Without the braces:

if(DoSomething)
    MyClass myClass = new MyClass();

myClass.DoAnythingElse();

This will compile, but lead to null references easily. (C# compiler does not compile this, good thing!)

Whereas this way:

if(doSomething)
{
    MyClass myClass = new MyClass();
}

myClass.DoAnythingElse();

won't even compile.

It is far better than minize Exceptions at compiletime already, than finding them at runtime.

BeowulfOF
Your first example will not compile, this is the compile error you will recieve:Embedded statement cannot be a declaration or labeled statement
mockedobject
damn, youre right, c# compiler is smart enough for that.
BeowulfOF
+7  A: 

I think it's a matter of guidelines for the project you are working on and personal taste.

I usually omit them when they are not needed, except some cases like the following:

if (something)
    just one statement; // i find this ugly
else
{
    // many
    // lines
    // of code
}

i prefer

if (something)
{
    just one statement; // looks better:)
}
else
{
    // many
    // lines
    // of code
}
Maghis
+10  A: 

One of the instances where this can bite you is back in the old days of C/C++ macros. I know this is a C# question, but often coding standards carry over without the reasons why the standard was created in the first place.

If you aren't very careful when you create your macros, you can end up causing problems with if statements that don't use the {}.

#define BADLY_MADE_MACRO(x) function1(x); function2(x);

if (myCondition) BADLY_MADE_MACRO(myValue)

Now, don't get me wrong, I'm not saying that you should always do {} just to avoid this problem in C/C++, but I have had to deal with some very strange bugs because of this.

Torlack
if only all code declared itself as such... *sigh*
Nathan Strong
+1  A: 

Err on the side of more secure - just one more bug you potentially won't have to fix.

I personally feel more secure if all of my blocks are wrapped in curlys. Even for one-liners, these are simple notations that easily prevent mistakes. It makes the code more readable in the sense that you clearly see what is in the block as not to confuse the body of the block with the following statements outside of the block.

If I have a one-liner, I typically format it as follows:

if( some_condition ) { do_some_operation; }

If the line is just too cumbersome then use the following:

if( some_condition )
{
    do_some_operation;
}
j0rd4n
A: 

Ok it has always seemed to me that this is more of personal preference to me. I have noticed however for readability it is better to have { } then to not have them. I have notice using ReSharper that ReSharper tends to delete them and do most of you if statements like this

if(this == yes)
      DoSomething();

But for readability sake I always do

if(this == yes)
{
 DoSomething();
}

Although with only one line of code in the "if" statement readability isnt really different but if you put 20-30 lines of code in one if statement then it is easier to read with the {} there and it leaves less room for error and bugs in your code.

Ironsides
+13  A: 

I also used to think it's better to only use braces when really needed. But not anymore, the main reason, when you have a lot of code, it does make it more readable and you can parse over the code quicker when you have a consistent bracing style.

Another good reason for always using braces, besides someone adding a second statement to the if, is something like this could happen:

if(a)
   if(b)
     c();
else
   d();

Did you notice that the else clause is actually that of the "if(b)"? You probably did, but would you trust anyone to be familiar with this gotcha?

So, if just for consistency and because you never know what unexpected things might happen when someone else (it's always the others that are stupid) changes the code, I always put braces, because it makes the source code more readable, quicker to parse by your brain. Only for the most simple if statements, like an if where a delegation is made or is switch-like, where you know the clause will never be extended, I would leave out the braces.

FredV
This is one of the two cases where I do use braces. Otherwise not.
Andrei Rinea
A: 

Have you thought about exploring this option for single line if else statement:

(!a) ? Foo(); : Bar();
Michael Kniskern
That's distasteful to some because the ternary operator is intended to calculate values. The flow control in your example is a side effect.
recursive
@recursive - you are right. It looks like the common practice to use this for calculating value: http://en.wikipedia.org/wiki/%3F:
Michael Kniskern
+3  A: 

I'm a strong believer in writing tidy and concise code, but I would always use curly braces. I find that they are a convenient way of quickly seeing the scope in which a particular line of code exists. There is no ambiguity, it's just explicitly set out in front of you.

Some may say it is a case of preference, but I find the logical flow of a program much easier to follow if it is internally consistent, and I don't believe that it is consistent to write one IF statement like this;

if(x < y)
    x = y;
else
    y = x;

And another like this;

if(x < y)
{
    x = y;
    x++;
}
else
{
    y = x;
    y++;
}

I prefer to just pick one general style and stick with it :)

C.McAtackney
A: 

I am always perplex when I see "this style saves space".
Since I rarely, if ever, print out code, gain of space has no obvious advantage for me: saving some bytes on disk doesn't worth it, and I don't pay for space taken on screen.
Some people find compact code more readable, I won't argue no this (highly subjective), but as amateur artist and typograph, I highly value whitespace use...

I won't repeat the above arguments, but I will add, I think, consistency: I dislike code like

if (foo)
{
  // Lot of code
}
else
  DoStuff();

Having said that, sometime I indulge in no braces: in guard conditions, when I do early exit:

if (somethingBadHappened)
  return;

To summarize, I think adding (almost) systematically braces around significant code improves readability (code "breathes", isn't cramped), consistency, and might avoid some stupid mistakes (yes, this kind of error is obvious, but coder is human (in general), can be tired, newbie, under stress...).

I have made a Lua macro for SciTE to add these braces around any block of code or current line, with one keystroke and correct indentation: it really costs nothing for me.

Now, I won't sue you if you chose to omit these braces. As others point out, one option or the other can be set in coding rules. To each their owns.

PhiLho
"I don't pay for space taken on screen." You do pay for it by not being able to see other code simultaneously.
recursive
+3  A: 

Reducing lines is not really a good argument for dropping braces. If your method is too big, it should probably be refactored into smaller pieces or restructured. Doing that will no doubt increase readability more than simply taking out braces.

plinth
+13  A: 

Lines are cheap. Processor power is cheap. Developer time is very expensive.

As a general rule, unless I am developing some absolutely resource / speed critical application, I would always err on the side of writing code that is

(a) Easy for any other developer to follow what I am doing

(b) Comment specific parts of the code that may need it

(c) Easy to debug if something goes wrong

(d) Easy to modify if it needs to be in future (i.e. adding / removing code)

The speed or academic elegance of the code is secondary to these factors from a Business perspective. This is not to say I set out to write clunky or ugly code, but this is MY order of priority.

By omitting curly braces in most instances, it for me makes (b), (c) and (d) more difficult (note not impossible however). I would say that using curly braces or not has not effect on (a).

Jayden
A: 

On the one hand, I leave the braces out for a single statement. On the other hand, I check all C code with PC-Lint (http://www.gimpel.com/), which flags two or more indented lines following an if() statement as "suspicious indentation".

By the way, putting single statements on the same line as the if() looks like a good idea.

mkClark
+3  A: 

I am impressed and humbled that my peers in this field of computer programming (you lot) are not daunted by the prospect of potential bugs when you skip the braces on single line blocks.

I suppose it means I'm not smart. I have made mistakes around this multiple times. I have debugged others' mistakes around this. I have watched software ship with bugs because of this (RDP to a machine running VS2002 and your watch window font will go wonky).

If I look at all the mistakes I've made that could have been avoided with a change in coding style, the list is very long. If I hadn't changed my approach in each of these cases, I probably would never have made it as a programmer. Again, I guess I'm not smart. To compensate, I have been a staunch user of braces on single-line blocks for a long time.

That said, some things have changed in the world that make the "thou shalt use braces on single-line blocks" rule less relevant today than when Moses brought it down to us:

  • Some popular languages make the issue go away by making the computer read the indentation, just like the programmer does (e.g. Python).

  • My editor automatically formats for me, so the chances of me getting mislead by indentation is much reduced.

  • TDD means that if I introduce a bug because I get confused by a single-line block, I'm much more likely to discover the bug quickly.

  • Refactoring and language expressiveness mean that my blocks are much shorter, and single-line blocks happen much more often than the used to. Hypothetically, with a ruthless application of ExtractMethod, I could possibly have only single-line blocks in my whole program. (I wonder what that would look like?)

In fact, there's a distinct benefit can come of refactoring ruthlessly & omitting braces on single-line blocks: when you see braces, a little alarm can go off in your head that says "complexity here! beware!". Imagine if this was the norm:

if (condition) Foo();   // normal, everyday code

if (condition) 
{
    // something non-trivial hapening; pay attention!
    Foo();
    Bar();
}

I'm opening myself to the idea of changing my coding convention to something like "single-line blocks may never have braces" or "if you can put the block on the same line as the condition, and it all fits within 80 characters, omit the braces". We'll see.

Jay Bazuzi
As a former Java programmer, I have to fully agree with automated formatting being the real answer to the problem. You don't even have to have your editor add braces automagically -- auto-indenting alone can help avoiding ambiguities a lot. Of course now that I have switched to Python, I've become used to formatting my code properly in the first place.
Alan
A: 

I always use curly braces except on the inner most statement, assuming the inner most statement is a single-liner. So my code looks like:

for (int i=0; i<10; i++) 
{
    for (int x=0; x<20; x++) 
    {
        if (someBoolValue)
            DoThis(x,y);
    }
}

The other exception is of course, stacked using statements.

There's absolutely no sense in writing

using (Stream x = File.Open(...)) 
{
    using (Stream y = File.Create(...)) 
    {
        ...
    }
}

when you can write

using (Stream x = File.Open(...))
using (Stream y = File.Create(...)) 
{
    ....
}
Chris
A: 

Paul said:

And indentation is independent of brace usage.

That's not true with some coding styles. Where I work, the company's coding standard allows us to do without braces if they're not strictly necessary; however, the coding standard makes us indent the braces as well as what's in them, so we end up with something like this:

if (something)
  {
    for (i = 0; i < count; i++)
      {
        foo();
      }
  }

Without the braces, this becomes:

if (something
  for (i = 0; i < count; i++)
    foo();

With this coding style, when there is deep nesting, together with long variable and function names and you always use braces, you either get lots of code going off the right side of the screen or a lot of line wrapping, both of which, IMO, make the code cumbersome to read or debug. For this reason, I always tend to leave the braces out whenever I can get away with doing so.

As for putting a single statement on the same line as the if, some companies' coding standards (ours included) forbid that, so it's not always an option.

If it were my choice, I would change the company coding standard to have the braces level with the if, for, etc. and have the first line (or comment) in the body on the same line as the opening brace, thus:

if (something)
{ for (i = 0; i < count; i++)
  { foo();
  }
}

I'd be much more willing (and much more likely) to always use braces then (and would even go so far as to support an 'always use braces' rule), because each pair of braces would add only one extra line and no indentation, making it almost as compact as having no braces at all.

RobH
+5  A: 

Out of the three conventions:

if(addCurleyBraces()) bugFreeSofware.hooray();

and:

if(addCurleyBraces())
    bugFreeSofware.hooray();

and (which represent any indentation style using an opening and a closing brace):

if(addCurleyBraces()) {
    bugFreeSofware.hooray();
}

I prefer the last one as:

  • I find it easier to read if all the if-statements are written in a uniform way.
  • It may make the software a tiny bit more robust and bug free. However all modern IDE's and advanced text editors have nice auto-indenting features which I think everyone should use as long as it doesn't mess up comment formatting or go against team standards (in a lot of cases it's possible to create a custom formatting scheme and share it with the team). My point here is that if indentation is done correctly risk of bug introduction is reduced a bit.
  • I prefer the boolean expression and statement(s) to execute to be on different lines. I like to be able to mark a row for debugging purposes. Even if I'm using an IDE where I may mark a statement and step to it, it's an interactive operation and I might forget where I started to debug or at least it will take me a little bit more time to step through the code several times (as I have to mark the position manually each time during debugging).
DeletedAccount
+53  A: 

Speed of reading...

Aside from what has already been mentioned. At this point, I've already been conditioned to parse if statements with braces and white space. So I read:

if (condition)
{
    DoSomething();
}

DoSomethingElse();

Slightly faster than I read:

if (condition) DoSomething();

DoSomethingElse();

I read it a little slower if it looks like this:

if (condition) DoSomething();
DoSomethingElse();

I read this significantly slower than the prior:

if (condition) 
    DoSomething();
DoSomethingElse();

beause I can't help but read it again just in-case and wonder if the author intended:

if (condition)
{
    DoSomething();
    DoSomethingElse();
}

Already covered in general, but when it comes to reading the below, I'll be looking into this for quite a while to make sure what the author intended. I may even hunt down the original author to confirm.

if (condition) 
    DoSomething();
    DoSomethingElse();
CrashCodes
The problem is solved when, in your 4th sample, you just put an empty line after if statement to seperate it from DoSomethingElse()That's what I do and readability is practically the same as with the 1st sample (if not better ;-P)Another thing is that putting lines in groups of 2 or 3 signifficantly helps readibility, you just scan through the code much faster.
Piotr Owsiak
How about `if (condition) {newline} DoSomething(); {newline x2} DoSomething();` ? I find that less verbose than 2 curlies for a single if. I find (when they're long) one line `if (condition) dosomething` harder to read but I think I'm in the minority there
Chris S
I agree that curly braces may be faster to read, but when you want to see more stuff at once, it increases reading speed of the individual stuff but decreases comprehension speed and requires more re-reads. And things become plain painful when you have curly braces for serial errorchecking code with many lines like, `if (badCondition) return;` It is not always practical to refactor such code into an `or` conditional.
Brian
Maybe it's because I'm used to Python, but putting the first curly brace on the same line as the if statement allows me to read+understand it even quicker.
Wallacoloo
The problem with the braceless style it makes you waste your precious concentration thinking about whether or not the block has braces rather than more important things. This alone is a good enough reason to use the simplest possible convention, which is braces always.
Nate C-K
A: 

I think it all boils down to preference and readability. Generally adding curly braces will make your code a lot more readable because of the extra space between the actual lines with code. Also, consider this example (not indented on purpose):

if (condition1)
if (condition2)
doSomething();
else
doSomethingElse();

When does doSomethingElse get called? When condition1 is true but condition2 is false, or when condition1 is false? Adding curly braces quickly solves this readability problem and avoids confusion.

Aistina
+1  A: 

An alternative method which combines the best of both worlds is this:

if(foo)
   {DoSomething();}

This avoids any confusion if the line is commented out, or another line is added below it.

Also, we use MISRA-C as a coding standard, which requires all constructs like this to use braces under all circumstances.

Steve Melnikoff
A: 

I prefer braces in most situations. Often you'll come back to the code to add more lines of code and you'll have to add them anyway.

alex
A: 

There's a lot of good answers here about why you shouldn't -- and I'm on the side that agrees that you shouldn't omit braces.

If you're looking for more terse code, I'd actually work with a ternary statement. They provide compactness with a certain amount of unambiguity and are more resistant to accidents.

The problem with omitting braces, as mentioned, is the likelihood of mistakes after the fact. Most programmers will agree that they can read:

if( foo )
    bar();

The problem comes when people come and change the statement and don't pay attention. At the last place I worked, there was actually a problem that arose from someone modifying the statement or commenting out a line. A coding standard was put in place to make sure bugs like that never happened again.

As someone else said, programmer time is the expensive bit. Like commenting your code, it's often faster to just leave out bits because they're optional, but easily maintainable code often relies on those 'optional' things.

Lastly, some people have mentioned that modern editors and IDEs should auto-indent and show you scope automatically. My answer is to not use such things as a crutch. There are times when you're looking at code out of a source repository or over a remote connection or even in an email -- these are the realities of development. You may not have an IDE or advanced editor to show you what you're doing wrong. Always write your code so that it's understandable no matter what you load it in.

A: 

I used to hate the braces myself. Until one day I found a use for them. I work on different platforms porting the application from platform to platform (work on 6 in total). On UNIX if you have vim installed, then you can easily jump to the ending or beginning of a code block by pressing 'Shift + 5'. These mostly are if/else blocks or loops.

So if i were looking at Rampion's problem on vim, I'd be totally lost and would take me a while to fully understand the code.

fasih.ahmed
+4  A: 

Use some personal judgement.

if (foo)
  bar();

is fine by itself. Unless you're really worried about morons putting in something like this later:

if (foo)
  bar();
  baz();

If you're not worried about morons, you're fine (I'm not -- if they can't get basic code syntax right, this is the least of their problems)>

In exchange, it's a lot more readable.

The rest of the time:

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

Which has been my favorite as long as I can remember. Additionally:

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

Works for me.

Vertical space by itself isn't terribly relevant, readability is. The opening brace on a line by itself just stops the conversation for a syntactic element, until your eye moves down to the next line. Not what I like.

+1  A: 
  1. Whitespace is free.
  2. Depending on indentation for future readability means depending on tab settings, which is not a good idea. Ever worked on ten-year-old code that wasn't under revision control?
  3. My experience is that any time you saved by not typing curly braces is more than lost by the extra time it takes me to figure out what you meant.
kajaco
A: 

I like the more compact formatting too. This is why I'm constantly hitting Ctrl+K, Ctrl+D to reformat in Visual Studio. I just wish I could make it do this for me after every keypress.

Atario
+5  A: 

I use to think the same way.

Until one day ( why is there always that "one day" that changes your life forever? ) we spend from 24 - 36 hours straight without sleep debugging production code only to find out someone didn't put braces combined with a search/replace change.

It was something like this.

 if( debugEnabled ) 
      println( "About to save 1 day of work to some very important place.");
 saveDayData();

What came after was

 if( debugEnabled ) 
 //     println( "About to save 1 day of work to some very important place.");
 saveDayData();

It turns out that the system was generating 500 mb of logs daily and we were asked to stop it. The debug flag was not enough so a search and replace println was in order.

Still when the app went to production the debug flag was off and the important "saveDayData" was never called.

EDIT

Now the only place where I don't use the braces is in if/try construct.

if( object != null ) try { 
     object.close();
} catch( .....

After watching a superstar developer doing that.

OscarRyz
+2  A: 

Okay, this is an old question that has been answered to death. I have something to add.

First I just have to say USE THE BRACES. They can only help readability, and readability (for yourself and others!) should be very high on your priority list unless you're writing assembly. Unreadable code always, always leads to bugs. If you find that braces make your code take up too much space, your methods are probably too long. Most or all of any method should fit within one screen height if you're doing it right, and Find (F3) is your friend.

Now for my addition: There is a problem with this:

if (foo) bar();

Try setting a breakpoint that will only be hit if bar() is going to run. You can do this in C# by putting the cursor on the second half of the code, but that is not obvious and is a bit of a pain. In C++ you couldn't do it at all. One of our most senior developers working on C++ code insists on breaking 'if' statements into two lines for this reason. And I agree with him.

So do this:

if (foo)
{
    bar(); //It is easy to put a breakpoint here, and that is useful.
}
skypecakes
Right click on bar and choose Insert Breakpoint... Not hard at all. Know your tools.
Bob
Right clicking the indicator bar does nothing; do you mean right click the text? Anyway, if you only want the break point to be hit when the "if" statement is true, and "bar()" is on its own line, you can put the cursor anywhere in that line and press F9, or left click the indicator margin. If, however, all of the code is on a single line, you have to position the cursor on "bar()" or right click exactly there before pressing F9, and clicking the indicator margin won't work (places breakpoint on the 'if'). It's not "hard," but it requires less concentration when the code is on two lines.
skypecakes
Oh, ha ha, right click on "bar()." You did mean the text. Gotcha. Sure, or just press F9...
skypecakes
>>you have to position the cursor on "bar()" or right click exactly there before pressing F9,(I meant position the cursor exactly there before either pressing F9 or right clicking)
skypecakes
A: 

Because StyleCop says so.

Joe
A: 

If you feel "sometimes" it is useful to have braces, you should aways add braces to be consistant. Programs should be written to be read by people not computers. I prefer braces like:

if (mybool)
{
  doMyStuff();
}
else
{
  doMyOtherStuff();
  checkStuff();
}

and NOT like

if (mybool) {
  doMyStuff();
}
else {
  doMyOtherStuff();
  checkStuff();
}

and not like

   if (mybool)
     doMyStuff(); 
   else 
   {  
     doMyOtherStuff();
     checkStuff(); 
   }
Mark Schultheiss
A: 

On other thought, if you are removing/not using braces to save lines, you need to refactor the code.

Mark Schultheiss
A: 

They tell you because they still use ancient or generic (not language-aware) source code editors. If you use an editor with auto-indent, you will never make a mistake that could have been avoided by using curly brackets all the time.

Marian
+1  A: 

To be blunt I see it as:

Good programmers program defensively, Bad programmers don't.

Since there are several examples above and my own similar experiences with bugs related to forgetting braces then I learned the hard way to ALWAYS PUT BRACES.

Anything else is choosing personal style over safety and that's clearly bad programming.

Joel even mentions this in Making Wrong Code Look Wrong

Once you get bit by a bug because of missing braces you learn that missing braces look wrong because you know it's a potential place for another bug to occur.

gman