59
votes

Which is better/more generally accepted?

This:

if(condition)
{
  statement;
}

Or:

if(condition)
  statement;

I tend to prefer the first one, because I think it makes it easier to tell what actually belongs in the if block, it saves others from adding the braces later (or creating a bug by forgetting to), and it makes all your if statements uniform instead of some with braces and some without. The second one, however, is still syntactically correct and definitely more compact. I'm curious to see which is more generally preferred by others though.

8
  • 2
    But you have your opening brace in the wrong position. That much is certain. Nov 6, 2010 at 7:38
  • In many languages, a block is a statement, hence, syntactically, it is always if (expresion) statement
    – Ingo
    Sep 9, 2011 at 8:57
  • 2
    Since you didn't specify a language... What about statement if condition;? Sep 9, 2011 at 11:44
  • @Christian - good one. That would be another question separate from this, no? Sep 9, 2011 at 22:01
  • @Ingo - good point. Sep 9, 2011 at 22:01

17 Answers 17

131
votes

The first is better because the second is error-prone. For example, let's say you are temporarily commenting out code to debug something:

if(condition) 
//      statement;
otherStatement;

Or adding code in a hurry:

if(condition) 
    statement;
    otherStatement;

This is obviously bad. On the other hand, the first one does feel too verbose at times. Therefore, I prefer to just put everything on one line if it's sufficiently short and simple:

if(condition) statement;

This cuts down on syntactic noise while making the construct look like it does what it actually does, making it less error-prone. Provided that this syntax is only used for very simple, short conditions and statements, I find it perfectly readable.

21
  • 35
    Good point about putting everything on one line. Nov 3, 2010 at 14:50
  • 7
    @artjomka: If statement is long, and has to go on its own line, then I use braces for readability. The point is that you want the shortest, least syntactically noisy construct that is unambiguous to a human who is reading it quickly rather than scrutinizing it.
    – dsimcha
    Nov 3, 2010 at 14:56
  • 15
    I prefer the one with braces for the reasons already mentioned. I don't like the one-liner, because it is not immediately obvious what happens when I step over the line in the debugger. I have to take the separate step to see what condition evaluates to.
    – Jim A
    Nov 3, 2010 at 16:25
  • 10
    @TMN whitespace is free, monitors are big and your brain learns to recognise the shape which helps you parse the code.
    – Murph
    Nov 3, 2010 at 20:52
  • 5
    @Murph: whitespace is free? I must have missed that. On my screen, it takes up really much space. Much more than 50% actually. Which in my book seems like a big waste. Personally, I like to maximize content per square centimeter in code. Nov 4, 2010 at 16:56
44
votes

I always use brackets just to be safe.

It's fine when you write it, but you know somebody will come along in the future and insert another statement without putting brackets around it.

9
  • 20
    Have people really seen this happen? I don't think I've ever seen this in 10 years of programming. Maybe I've just been too sheltered. :)
    – David
    Nov 3, 2010 at 15:35
  • 9
    I'd love to say no, but sadly I have seen it. Nov 3, 2010 at 15:58
  • 13
    You always use brackets so that you never forget to use brackets - its as simple as that.
    – Murph
    Nov 3, 2010 at 20:49
  • 12
    +1 to @Murph. Same reason I use my turn signals when nobody's around--and in parking lots!
    – Dan Ray
    Nov 3, 2010 at 23:58
  • 7
    This is good practice to help prevent errors when merging from branch-to-trunk or across branches. Nov 4, 2010 at 11:01
27
votes

I prefer the version without braces where possible.

The following explanation is longish. Please bear with me. I will give a compelling reason for me to prefer this style. I will also explain why I think that the usual counter-argument doesn’t hold.

(Near-) empty lines are a waste

The reason for this is that the closing brace requires an extra line of code – and so does the opening brace, depending on style.1

Is this a big deal? Superficially, no. After all, most people also put empty lines in their code to separate logically slightly independent blocks, which vastly improves readability.

However, I detest wasting vertical space. Modern monitors actually have ample horizontal space. But vertical space is still very, very limited (unless you use a monitor turned upright, which isn’t that uncommon). This limited vertical space is a problem: it’s widely acknowledged that individual methods should be as short as possible, and that corresponding braces (or other block delimiters) should be no more than a screen height in difference so that you may see the entire block without scrolling.

This is a fundamental problem: once you can’t see the entire block on your screen any longer, it gets complicated to grasp.

As a consequence, I detest redundant empty lines. Where single empty lines are crucial to delimit independent blocks (just look at the visual appearance of this text), consecutive empty lines are a very bad style in my book (and in my experience they are usually a sign of novice programmers).

Likewise, lines which simply hold a brace, and which could be economised, should be. A single-statement block which is delimited by braces wastes one to two lines. With only 50-ish lines per screen height, this is noticeable.

Omitting braces maybe does no harm

There is just one argument against omitting braces: that someone will later add another statement to the block in question and will forget to add the braces, thus inadvertently changing the semantics of the code.

This would indeed be a big deal.

But in my experience, it isn’t. I’m a sloppy programmer; and yet, in my decade of programming experience, I can honestly say that I have not once forgotten to add the braces when adding an extra statement to a singleton block.

I even find it implausible that this should be a common mistake: blocks are a fundamental part of programming. Block level resolution and scoping is an automatic, ingrained mental process for programmers. The brain just does it (otherwise, reasoning about programming would be much harder). There is no additional mental effort required to remember putting the braces: the programmer also remembers to indent the newly added statement correctly, after all; so the programmer has already mentally processed that a block is involved.

Now, I am not saying that omitting braces doesn’t cause mistakes. What I’m saying is that we have no evidence one way or the other. We simply don’t know whether it causes harm.

So until someone can show me hard data, collected from scientific experiments, demonstrating that this is indeed an issue in practice, this theory remains a “just-so story”: a very compelling hypothesis that has never been put to the test, and that must not be used as an argument.


1 This problem is sometimes solved by putting everything – including the braces – on the same line:

if (condition)
{ do_something(); }

However, I believe it’s safe to say that most people despise this. Furthermore, it would have the same problems as the variant without braces so it’s the worst of both worlds.

12
  • 6
    Omitting braces harms readability and can easily cause issues when the code is modified.
    – Josh K
    Nov 3, 2010 at 16:20
  • 15
    @Josh: the first claim is ridiculous, as languages such as Python show (back it up with evidence if you think otherwise). The second has been countered in my answer. Do you have evidence to back it up? Otherwise your comment is an indication that you haven’t actually read my text. Please do so before criticising it. Nov 3, 2010 at 16:25
  • 8
    +1 for your thoughts, but I think your position is self-defeating. You say "show me hard data, collected from scientific experiments, showing that this is indeed an issue in practice" and yet fall back on anecdotal experience (your own) to defend your position. You say, "in my experience...in my decade of experience...I find it implausible..." and so forth. Can you show hard data, collected from scientific experiments, supporting your claim, "Omitting braces does no harm"? Personal experience is fine when supporting an opinion, but don't ask for more "evidence" than you're willing to give.
    – bedwyr
    Nov 3, 2010 at 18:59
  • 3
    @bedwyr: there’s a qualitative difference, though. First, I make it clear that I will actually be persuaded by data, and I make it equally clear that mine is merely a hypothesis, not backed up by data. Secondly, I have stated an (at least to me) plausible argument for my belief that the claim is false and why it needs to be corroborated. Which leads me to thirdly: the onus here is on the opposition to prove their claim, not on me to disprove it. And in addition to the plausibility problem, I have shown one unrelated factual argument supporting my coding style. Nov 3, 2010 at 19:52
  • 4
    @Konrad - python does not show otherwise because the indentation is significant and hence the braces are implicit. Good bright programmers, the type who are here, probably won't make the mistake often if at all (in a lot of years I've probably seen issue with on only a couple of occasions) but there are a lot of rather less good programmers out there who do do stupid things which is one of the reasons why coding standards are needed in the first place. (And because deadlines and stress can make the best of us less good.)
    – Murph
    Nov 3, 2010 at 21:02
19
votes

I go with the second. It's more succinct and less verbose.

I try not to write to the lowest common denominator, so I expect that other developers know how to write one of the single most common control flow structures in programming today.

7
  • 11
    absolutely! after all, if the code was hard to write, it should be hard to maintain, too! ;-) Nov 3, 2010 at 23:52
  • 3
    @Steven If you forget braces, I think there are other problems here.
    – TheLQ
    Nov 4, 2010 at 1:06
  • more succint == less verbose
    – UncleZeiv
    Nov 4, 2010 at 16:42
  • 5
    @SnOrfus: somewhat sarcastic, since the extra 2 characters are trivial overhead and prevent a very common maintenance mistake. Your Mileage May Vary ;-) Nov 8, 2010 at 4:32
  • 1
    To me the indenting makes it clear what's going on. The first form burns extra screen space and thus is a negative to me. Jul 27, 2012 at 16:58
16
votes

I'd use the following (the consensus here):

if (condition) {
    any_number_of_statements;
}

Also possible:

if(condition) single_compact_statement;

Not so good, especially in C/C++-like languages:

if(condition) 
    single_compact_statement;

(No choice here in Python ;-)


In Perl, you'd use:

$C = $A**3 if $A != $B;

or

$C = $A**3 unless $A == $B;

(This is not pseudocode ;-)

5
  • 1
    My thoughts exactly. If the single statement looks good on a single line after the if clause, I don't use braces. For any other if statement (or any statement that uses multiple lines), I always use braces. In particular, if there's an else clause, each case always has braces.
    – eswald
    Nov 3, 2010 at 17:33
  • 9
    I've never seen somebody confuse perl with pseudocode before. Random characters yes, pseudocode - no.
    – Joe D
    Nov 3, 2010 at 20:24
  • 3
    I wonder if anyone's made a Perl program generator just by hooking up /dev/random to a Perl interpreter... Nov 6, 2010 at 7:40
  • I like ruby's approach here. It offers the perl style single-line <statement> if <condition> or a multiline block style if <condition> / <do something> / end (ruby avoids braces, so here the opening brace is implied by if and the end brace is replaced by a literal end). It doesn't even offer the weird multiline-but-really-just-single-line if statement.
    – Ben Lee
    Dec 30, 2013 at 23:33
  • The one-liner does not work with most debuggers (it is not possible to trigger a break when the content of the 'if' clause is about to be executed). May 31, 2014 at 18:52
11
votes

I use the braces method - for all the reasons above plus one more.

Code merges. It's been known to happen on projects I've worked on that single-statement ifs have been broken by automatic merges. The scary thing is the indentation looks right even though the code is wrong, so this type of bug is hard to spot.

So I go with braces - on their own lines. It's easier to spot the levels that way. Yes, it does waste vertical screen real estate and that's a genuine downside. On balance though, I think it's worth it.

0
10
votes

No braces. If some other programmer adds a second statement to my code it's no more my fault than if I let someone drive my car and they went over a cliff.

3
  • 3
    Exactly! It's not our fault he/she doesn't know the syntax. Nov 11, 2010 at 3:44
  • 3
    Bad example. A good one is a car with misplaced pedals - gas instead of brake. It's your car, so you don't care about anybody else. It's there problem that they don't know about your unique positioning of pedals. Are you a good car engineer in this case?
    – yegor256
    Jan 30, 2013 at 14:33
  • It'd be your fault if you gave them your car knowing they may be drunk. Similarly we should try to assume as little as possible about future developers to help ease maintenance. Jan 11, 2014 at 1:35
8
votes

We have had this argument more than once here, and the overall consensus is to always use braces. The main reasons are about readability/maintainability.

If you need to add code to the if block, you don't need to remember/search for braces. When future programmers read the code, the braces are always unambiguous.

On the plus side, ReSharper will automatically add the braces for lazy programmers in Visual Studio, and I assume there are addons for other IDEs that will do so as well.

7
  • 3
    I categorically don’t buy the readability claim. Python is one of the most readable languages there is and it doesn’t need delimiters. That claim is just not true. I also don’t buy the maintainability claim because it’s so far unproven and still repeatedly rehashed. But in this case I’m actually very interested in empirical evidence. This is something that a study could very easily find out, and settle once and for all. Nov 3, 2010 at 16:42
  • As Python uses indentation instead of delimiters they are implicit its not a valid comparison.
    – Murph
    Nov 3, 2010 at 20:57
  • @Konrad - empirical evidence: When I was a new programmer I personally added code to an un-braced if block without realizing that the previous programmer had not bothered with braces. I have personally seen other people do this with my own eyes. Granted, only once did I see someone need help to find the problem after running their code, but that had more to do with bad testing skills.
    – shimonyk
    Nov 4, 2010 at 13:14
  • @shimonyk: so basically your observations support my assertion that this problem is inconsequential? By the way, personal observations are anecdotes, they don’t count as empirical evidence. Nov 4, 2010 at 13:17
  • @Konrad very well, please cite your sources also. I assume you have a peer reviewed double-blind study that you are referencing? If not, than merely flouting your own anecdotes in an attempt to prove others wrong while demanding other poster refer to 'evidence' is hypocritical at best. As someone further down on this very topic wrote "the onus here is on the opposition to prove their claim, not on me to disprove it".
    – shimonyk
    Nov 4, 2010 at 13:31
7
votes

I use the first syntax, almost without exception. Because it cannot be misinterpreted.

"Don't make me think" doesn't just apply to user-interfaces, y'all ;-)

2
  • 4
    I used to do this, but I was won over by the argument that programmers need to know the language and they should be made to think. Nov 11, 2010 at 3:46
  • 2
    I consider it common courtesy...to my future self. Nov 11, 2010 at 6:36
5
votes

I personally prefer the second. The first one looks ugly, awkward, and wastes horizontal space. The main problems with the second one are macros and people modifying your code at a later point getting it wrong.

To this, I say "don't use macros". I also say, "indent your damn code correctly". Considering how every text editor/IDE used for programming does indentation automatically, this shouldn't be that hard to do. When writing code in Emacs, I would use the auto-indent to identify if I wrote something wrong on a previous line. Anytime Emacs starts screwing up indentation, I usually know I've done something wrong.

In practice, I end up following whatever coding convention has been set before me. But these ones annoy me (and makes me much happier when I code in Python and this entire bracket disaster is gone):

if (condition) {
    statement;
} // stupid extra brace looks ugly

Then

if (condition) // the brackets have now just become noise
{ statement; } // also can't see the indentation, harder to read

Although honestly, two statements in an if statement annoy me far more than a single statement. Mostly because then brackets are required and it still looks funny with only two statements in the if statement.

1
  • If you're going to write macros you should write them to make sure they can be inserted into any part of the code without breaking anyway.
    – Covar
    Nov 5, 2010 at 19:01
4
votes

I use the two-line version without braces (the 2nd form), but not to save space.

I use that form because I find it more readable, more visually appealing, and easier to type. I only use that form if those conditions are met; i.e. the if condition has to fit nicely on a single line, and the corresponding statement has to fit nicely on the following line. If that is not the case, then I will use braces to improve readability.

If I use this form, I make sure that there is an empty line (or a line containing only a brace) before and after the if statement (or above the comment, if present). While this is not a rule that I consciously follow, I notice it now after reading this question.

Conserving screen space is not a priority for me. If I needed more space I would use a larger monitor. My screen is already large enough for me to read anything that I might need to focus my attention on. It's unlikely that I would need to focus on so many lines of code at one time that they take up my entire screen. If there is so much nesting going on with a chunk of code that I can't understand it without viewing more of it at one time, then I would have to consider whether the logic could be better represented by refactoring.

Below are some examples that demonstrate how I use this form of the if statement.

    string GuardConditions(Plan planForWorldDomination)
    {
        if (planForWorldDomination == null)
            throw new ArgumentNullException("planForWorldDomination");

        if (!planForWorldDomination.IsComplete())
            return "Doh!";

        planForWorldDomination.Execute();
    }

    void ProcessingLogic()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
        OneBlankLineAbove();

        // optional comment on the line above an if statement
        if (simpleCondition)
            simpleStatement();

        OneBlankLineBelow();
    }

    void Assignment(string drive)
    {
        OneBlankLineAbove();

        string prompt;
        if (simpleCondition)
            prompt = "simple assignment";
        else
            prompt = null;

        OneBlankLineBelow();
    }

    string Return()
    {
        OneBlankLineAbove();

        if (simpleCondition)
            return "simple return";
        else
            return null;

        OneBlankLineBelow();
    }
0
3
votes

Braces. Always. I'm kind of the fan of them, because it gives code some consistency. And also as @dsimcha wrote - less chance for errors on adding additional lines of code.

"Ugliness" of braces around single line of code are less harmful than additional work which is probable in those cases with debugging and/or adding code.

2
  • 1
    I've never seen anyone make the error you're speaking of. Nov 11, 2010 at 3:51
  • 1
    I've just made it yesterday on someone elses piece of code. :-) I just wonder how the upstream will look on, among other additions to the code, adding braces on all of his if's because he really seems to be from different side than me on this. :-) (calm down, I'm joking, edited just what I had to...) Nov 11, 2010 at 13:37
2
votes

Personally I go with brackets.

Why?

Well if anyone comes along and needs to add code into the if statement it's 100% clear where the scope is.

It keeps the format of if statements consistent no matter how many statements there are in the block.

However, if the project style is to go without, stick to that.

1
vote

I almost always use the brackets just to be on the safe side. However, sometimes if the contents of the block are really short I'll do leave them off and make it a one-liner like so:

if (x==5) Console.WriteLine("It's a five!");
7
  • Guess someone isn't a fan of brevity.
    – JohnFx
    Nov 3, 2010 at 15:30
  • 2
    Brevity for sake of readability? Absolutely not. It's code, not a golf contest.
    – Josh K
    Nov 3, 2010 at 15:39
  • 3
    I think readability is a great reason for brevity, personally. In any case: White-space doesn't count in my code-golf rulebook.
    – JohnFx
    Nov 3, 2010 at 15:58
  • The one problem with this is it lends itself to abuse Nov 3, 2010 at 21:32
  • 2
    Then don't abuse it. I'm not saying use it as a coding standard. There just happen to be a lot of times when you have a really short conditional followed by a really short single statement and this works well. For example an if (assert) log.write("assert failed");
    – JohnFx
    Nov 3, 2010 at 21:42
1
vote

I prefer braces for consistency, but not wasting too much white space (so more readably formatted code is in my limited field of view). So I write this for short enough lines:

If (cond) { statement; }
1
  • Interesting, I don't really see code like this, but I kinda like it. Jul 27, 2012 at 17:53
0
votes

I usually use braces, but there are some cases where I don't.

object GetObject() {
    // calculate obj1
    if(obj1 != null)
        return obj1;

    // calculate obj2
    if(obj2 != null)
        return obj2;

    // calculate obj3
    if(obj3 != null)
        return obj3;

    return defaultObj;
}

To me, it would just be silly to add them there. If someone adds a statement after the return, we have bigger problems than scoping issues.

4
  • You could just as easily use return (obj != null) ? obj : "Error";
    – Josh K
    Nov 3, 2010 at 15:07
  • @Josh, see edit Nov 3, 2010 at 15:36
  • In that case I would use something like Object returnObj = defaultObj; /* Three else-if's to change it to obj1/2/3 */ return returnObj;.
    – Josh K
    Nov 3, 2010 at 15:39
  • @Josh, Read through stackoverflow.com/questions/36707/…. First comment on the first answer, "Although having multiple exit point can get out of hand, I definately think it's better than putting your entire function in an IF block." Nov 3, 2010 at 16:07
0
votes

If the IDE has code formatting available I do not use braces.

On the other hand, where code may be edited in other editors which does not support auto formatting it is dangerous not to put braces as mentioned in other posts. But even so I prefer not to use braces, and it has not been problem for me.

Not the answer you're looking for? Browse other questions tagged or ask your own question.