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.

This question exists because it has historical significance, but it is not considered a good, on-topic question for this site, so please do not use it as evidence that you can ask similar questions here. This question and its answers are frozen and cannot be changed. More info: help center.

Many good questions generate some degree of opinion based on expert experience, but answers to this question will tend to be almost entirely based on opinions, rather than facts, references, or specific expertise.
If this question can be reworded to fit the rules in the help center, please edit the question.

2

But you have your opening brace in the wrong position. That much is certain.
–
Christian MannNov 6 '10 at 7:38

2

Since you didn't specify a language... What about statement if condition;?
–
Dave SherohmanSep 9 '11 at 11:44

17 Answers
17

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.

Good point about putting everything on one line.
–
Neil AitkenNov 3 '10 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.
–
dsimchaNov 3 '10 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 ANov 3 '10 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.
–
MurphNov 3 '10 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.
–
Konrad RudolphNov 4 '10 at 16:56

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.

@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.
–
Konrad RudolphNov 3 '10 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.
–
bedwyrNov 3 '10 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.
–
Konrad RudolphNov 3 '10 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.)
–
MurphNov 3 '10 at 21:02

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.
–
eswaldNov 3 '10 at 17:33

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.

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?
–
yegor256Jan 30 '13 at 14:33

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.
–
Konrad RudolphNov 3 '10 at 16:42

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.

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.

I've never seen anyone make the error you're speaking of.
–
kirk.burlesonNov 11 '10 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...)
–
Vedran KrivokućaNov 11 '10 at 13:37

I think readability is a great reason for brevity, personally. In any case: White-space doesn't count in my code-golf rulebook.
–
JohnFxNov 3 '10 at 15:58

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");
–
JohnFxNov 3 '10 at 21:42

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.