Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Should curly braces be on their own line or not? What do you think about it?

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

or should it be

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

or even

if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();

Please be constructive! Explain why, share experiences, back it up with facts and references.

share|improve this question

closed as not constructive by Jeff Atwood Sep 26 '11 at 3:19

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

57  
I find the "== true" more distracting than the choice of brace placement. –  Dan Dyer Sep 10 '10 at 22:36
6  
@Dan: I think that always explicating the conditional expression greatly helps in clearness. –  Lorenzo Sep 10 '10 at 23:12
19  
@Lorenzo: I don't need to see you explicating. –  Robert Harvey Sep 10 '10 at 23:13
5  
Tremendous. I was wondering when someone would ask this! –  Paddyslacker Sep 11 '10 at 5:02
7  
So tempted to down vote everyone posting on this one just because it's tempting to call EVERYONE wrong. But then that's going to be a lot of rep I'd be giving up. –  MIA Sep 21 '10 at 3:54

37 Answers 37

up vote 22 down vote accepted

When I was a student I used to put curly braces on the same line, so that there are fewer lines, and the code gets printed on fewer pages. Looking at a single bracket character printed as the only thing in a line is annoying , think of your carbon footprint :)

But when coding large applications, allowing some lines with only braces in them are affordable, considering the 'grouping' feeling it gives.

Whichever style you choose, be consistent so that it does not become an overhead for your own brain to process multiple styles in related pieces of code. In different scenarios (like above) it is OK to use different styles, it's not that much of an effort to 'switch context' in a high level.

share|improve this answer
1  
TOTALLY AGREE re: consistency within a project. But when I was a student, there would be guys who I knew were in my classes working on exactly the same assignments, whose code listings would print on 3 or 4 pages when mine would print on less than 1 page, totally despite anything related to the brace style. Hmm. No wonder they liked the old K&R style, if they couldn't write more efficient code than that. What does brace style have to do with carbon footprint? Let's not conflate silly issues with other silly issues... ;-) –  Craig Apr 25 at 14:04

It depends.

If I am coding in Javascript or jQuery, I use the first form:

jQuery(function($) { 
    if ($ instanceOf jQuery) { 
        alert("$ is the jQuery object!"); 
    } 
}); 

But if I am coding in C#, I use the second form, because that is the canonical way to do it in C#.

public int CalculateAge(DateTime birthDate, DateTime now) 
{ 
    int age = now.Year - birthDate.Year; 
    if (now.Month < birthDate.Month 
        || (now.Month == birthDate.Month && now.Day < birthDate.Day)) 
        age--; 
    return age; 
} 

Note that your example can be written

if (you.hasAnswer())
    you.postAnswer();
else
    you.doSomething();

in C#.

share|improve this answer
1  
It can be written in a lot of languages like that, because a block-statement is a statement. Adding! :-) –  Tom Wijsman Sep 11 '10 at 0:34
1  
According to the "Framework Design Guidelines" the "canonical way" is to place the opening brace on the same line (i.e. the first form). Just sayin' ... –  Uwe Honekamp Sep 11 '10 at 14:48
1  
@Uwe: Perhaps. But Microsoft adopted the "aligned braces" approach for all of its MSDN C# examples, and it's baked into Visual Studio, so... –  Robert Harvey Sep 11 '10 at 15:05

I like the first method. It seems neater IMO, and it's more compact, which I like.

EDIT: Ah, a third. I like that one the best when possible, as it's even smaller/neater.

share|improve this answer

Ah, the One True Brace Style.

It has everything neded for a Holy Way - even a prophet (Richard "my way or the highway" Stallman).

The guy was so wrong about so many things, but GNU is spot-on when it comes to braces.

share|improve this answer
8  
I don't see the point of the GNU style, other than it models lisp code. Seems like a lot of work for little benefit. –  Robert Harvey Sep 11 '10 at 17:10
1  
+1 for the link on brace styles. It shows that whatever your style, many great people disagree with you. –  Florian F Sep 2 at 14:28

You could write it:

you.hasAnswer() ? you.postAnswer() : you.doSomething();

To answer the question; I used to prefer curly braces on their own line, but, to avoid having to think about bugs from automatic semicolon insertion in browsers i started using Egyptian style for javascript. And when coding java in eclipse I had no interest in fighting (or configuring) the default brace style, so I went with Egyptian in that case too. Now I'm fine with both.

share|improve this answer

The benefit of the first method is that it is more vertically compact, so you can fit more code on your screen, and that is why I prefer it. The only argument I heard in favor of the second method is that it makes it easier to pair opening and closing brackets, but most IDE's have a keyboard shortcut for that, and it's actually a false statement- instead of pairing an opening bracket to a closing bracket you can pair a closing bracket to the "start of block" expression (if, else, for, while) on the same indentation level, so it's just as easy to determine where the start of the block is.

I see no reason to waste an entire line just for a bracket when the preceding for/while/if construct already visually indicates the start of a block.

That said, I do believe that the closing bracket should be in its own line because we need something to indicate the end of a block and its indentation structure in a visible way.

share|improve this answer
8  
No... I'm saying why reduce the amount of code that can fit on your screen by doing something that doesn't add to the code's clarity? –  EpsilonVector Sep 11 '10 at 9:54
5  
When I was beginning coding I liked each brace on its own line, now I prefer the first method –  NimChimpsky Sep 21 '10 at 9:01
28  
There is a huge body of research, going all the way back to the early Steam Age (Weinberg, "Psychology of Computer Programming"), that shows that programmer comprehension falls off DRAMATICALLY when the amount of code that must be viewed is more than can be seen at one time (i.e., one screenful, one printer page). This phenomenon argues STRONGLY for viewing vertical space as a valuable resource, not to be wasted gratuitously, and thus the first method is preferred. –  John R. Strohm Nov 1 '10 at 21:34
2  
It reads like a sentence. If bool do this and this and that. Having a blank line is like putting a huge gap in that sentence, it doesn't read the same. –  Keyo Nov 3 '10 at 22:48
3  
LOL @ "wasting an ENTIRE line". OMG! Not that!! =P –  Nick Dec 12 '10 at 19:47

For a long time I argued that they were of equal worth, or so very close to equal that the possible gain by making the right choice was far, far, below the cost of arguing about it.

Being consistent is important, though. So I said let's flip a coin and get on to writing code.

I've seen programmers resist change like this before. Get over it! I've switched many times in my career. I even use different styles in my C# than in my PowerShell.

A few years ago I was working on a team (~20 developers) that decided to ask for input, and then make a decision, and then enforce that across all the code base. We'd have 1 week to decide.

Lots of groans & eye-rolling. Lots of "I like my way, because it's better" but no substance.

As we were studying the finer points of the question, someone asked how to deal with this issue in brace-on-the-same-line style:

void MyFunction(
    int parameterOne,
    int parameterTwo) {
    int localOne,
    int localTwo
}

Note that it's not immediately obvious where the parameter list ends, and the body begins. Compare to:

void MyFunction(
    int parameterOne,
    int parameterTwo) 
{
    int localOne,
    int localTwo
}

We did some reading on how folks around the world had dealt with this problem, and found the pattern of adding a blank line after the open brace:

void MyFunction(
    int parameterOne,
    int parameterTwo) {

    int localOne,
    int localTwo
}

If you're going to make a visual break, you may as well do it with a brace. Then your visual breaks become consistent, too.

I still argue that consistency is more important than other considerations, but if we don't have an established precedent, then brace-on-next-line is the way to go.

share|improve this answer
17  
FYI, I may sound like a reasonable person, but I'm actually a nut. For simple, single-line blocks, I will use neither braces nor newlines, making 'if (foo) bar()' all one line. I strive to make my code simple enough that it's not a problem. –  Jay Bazuzi Sep 11 '10 at 4:42
1  
That first example where the start of the function is visually welded onto the params list, is exactly how all the code is in this huge project I've been hired to work on. Ugh! It really costs time having to stare and think vs. just seeing the visual break. –  DarenW Oct 21 '10 at 16:48
18  
Came here to post exactly this. Tons of people that keep the opening brace on the same line follow it up with a blank line (especially at the start of classes and methods) because otherwise, it's hard to separate the class/method header from the body. Well, if you're going to use an extra line anyway, you may as well put the brace there and get the added benefit of indentation being easier to see. –  Yevgeniy Brikman Oct 29 '10 at 20:14
17  
I've not seen the blank line - I'm more familiar with double-indent of the parameters for MyFunction() when they stray onto another line. –  Alison Dec 1 '10 at 18:07
12  
Breaking out the parameters to multiple lines like that is maddening. –  Fosco Nov 10 '11 at 17:59

All I can say is that if you're a fan of method #3, you are going to be persecuted by every IDE code-formatter on earth.

share|improve this answer

I prefer the first method. Braces are totally not worth separate line.

The thing is that braces are not important. They're just syntactical trash, which is absolutely unnecessary to understanding of what code is for, of it's purpose and the way it's implemented. They're just a tribute to old-style C-like languages where visual grouping of operators was impossible due to low screen space available.

There are languages (Python, Haskell, Ruby) which are OK without braces at all. This only confirms that braces are trash, and should not deserve a line for them whenever possible:

if (you.hasAnswer()){
    you.postAnswer();
}else{
    you.doSomething();
}
share|improve this answer
1  
I don't know about Haskell or Ruby, but Python is whitespace sensitive, which is why it doesn't require braces or other delimiters to denote blocks. The braces are not just syntactical noise; they serve an actual purpose. –  Robert Harvey Sep 16 '10 at 16:11
9  
@Robert, In C you have to do both whitespace and braces. In Python you should do only whitespace. Which is better? –  Pavel Shved Sep 16 '10 at 17:34
2  
@KenBloom C programs without whitespace are impossible to read. So you have to do them anyway. –  Pavel Shved Oct 23 '10 at 11:21
1  
@Pavel: I find that this method makes it more difficult to pair braces visually, ie to spot if one is missing or not, and thus hamper my ability to debug code (see my answer). I don't consider them to be "trash" since they do affect the meaning, but I do prefer the Python syntax for its lack of clutter though. –  Matthieu M. Nov 5 '10 at 18:50
3  
Regardless of if braces are a good idea or not, the mere existence of languages that don't use them doesn't seem like an argument for or against them. It only suggests that it is possible to have a language without them, not that it is a good or poor language design. –  Jason Apr 6 '11 at 14:52

I did read somewhere that the authors of some book wanted their code formatted like this:

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

But space constraints from their publisher meant that they had to use this:

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

Now I don't know whether that's true (as I can't find it any more), but the latter style is very prevalent in books.

On a personal level I prefer the brackets on a separate line as:

a) they indicate a new scope
b) it's easier to spot when you've got a mismatch (though this is less of an issue in an IDE that highlights errors for you).

share|improve this answer

I personally like the second way.

However, the way I'm going to demonstrate is in my opinion best because it results in greatest job security! A fellow student from my university asked me for help with his homework and this is how his code looked like. Whole program looked like one single block. The interesting thing is that 95% of the bugs in the program he made came from mismatched braces. The other 5% were obvious once the braces were matched.

while(1){
i=0;
printf("Enter coded text:\n");
while((s=getchar())!='\n'){
         if(i%1==0){
            start=(char*)realloc(input,(i+1)*sizeof(char));
if(start==NULL){
printf("Memory allocation failed!");
exit(1);}
input=start;}
      input[i++]=s;}
start=(char*)realloc(input,(i+1)*sizeof(char));
if(start==NULL){
printf("Memory allocation failed!!!");
exit(1);}
input=start;
input[i]='\0';
                puts(input);
share|improve this answer
5  
Bad, bad, I mean terrible, terrible example. The problem is not the braces! It's the crazy indentation! –  R. Martinho Fernandes Sep 15 '10 at 3:20
2  
not necessarily... do proper indentation on the above and then randomly switch brace-styles, you'll find that it's understandable. –  jkerian Sep 26 '10 at 23:27

You should never do the 3rd method.

Skimping on braces might save you a few keystrokes the first time, but the next coder who comes along, adds something to your else clause without noticing the block is missing braces is going to be in for a lot of pain.

Write your code for other people.

share|improve this answer
43  
I wish I knew where that little bit of wisdom originated. Because writing your code for people who won't bother to read it is about as pointless as you can get... –  Shog9 Sep 12 '10 at 3:19
10  
Write your code for other people. +1 –  Moshe Sep 21 '10 at 3:58
20  
The second programmer can add his own braces when he adds something. He's not stupid, and in a coding convention that encourages omitting braces for simple stuff like this, he'll know to look. –  Ken Bloom Oct 22 '10 at 14:25
7  
Optional braces are not optional. There are few worse design decisions that were made in C and carried over to its descendants. That it lives on in a language as recent as C# makes me rage. –  Adam Crossland Oct 29 '10 at 15:58
6  
It doesn't matter how smart you are or how ingrained the coding standard around single line omitted curlies is: if you're looking to solve a problem or bug, you will likely miss that the curlies were omitted. And for a grand total of 2 seconds of work, is it really so bad to be explicit? –  Jordan Feb 15 '11 at 6:01

It all depends on you as long as you are not working on a project where some coding constraints or some standards have been set by the project manager that all the programmers who are working on that project have to follow while coding.

I personally would prefer the 1st method.

Also I didn't get what you wanna show by the 3rd method?

Isn't that a wrong way? For example consider a situation as..

if (you.hasAnswer())
  you.postAnswer();
else
  you.doSomething();

Now what if someone wants to add some more statements in the if block?

In that case if you use the 3rd method the compiler will throw the syntax error.

if (you.hasAnswer())
   you.postAnswer1();
   you.postAnswer2();
else
   you.doSomething();
share|improve this answer
1  
Even worse would be if someone came along and did:if (you.hasAnswer()) you.postAnswer(); else you.doSomething(); you.doSomethingElse(); - it's a recipe for subtle bugs that the eye can easily slip over and the compiler won't help out either –  FinnNk Sep 12 '10 at 13:02
2  
If someone wants to add another statement, they can put in the braces themselves. Any programmer worth his salt really should be able to figure that out. –  Robert Harvey Sep 16 '10 at 16:18
3  
@Robert Harvey, I've seen very experienced coders miss adding the braces when modifing existing code. I think the problem is that indentation is a much stronger clue to meaning than braces (especially since there are multiple brace styles,) so it's quite easy to overlook the missing brace if the indentation looks like what you expect. –  AShelly Sep 28 '10 at 2:13

When I was first learning programming at 12, I put the braces on the next line because the Microsoft coding tutorials are like that. I also indented with 4-space TABS that time.

After a few years, I learned Java and JavaScript, and saw more braces-on-same-line code, so I changed. I also began to indent with 2-spaces SPACES.

share|improve this answer
2  
+1, -1. Why would you NOT indent with tabs as any editor can adjust the tab length to your arbitrary length? Otherwise, you lead a lot of us who like true indents at 8 to curse your code. –  Xepoch Nov 5 '10 at 18:05

Second example, I'm very big on readability. I can't stand looking at if blocks any other way =(

share|improve this answer

I use the first method simply because it is more compact and allows more code on the screen. I myself have never had a problem with pairing up braces (I always write them out, together with the if statement before adding the condition, and most environments allow you to jump to the matching brace).

If you did need to pair up braces visually, then I would prefer the second method. However that allows less code at one time which requires you to scroll more. And that, for me at least, has a greater impact on reading code than having neatly aligned braces. I hate scrolling. Then again, if you need to scroll across a single if statement, it is most likely too large and needs refactoring.

But; the most important thing of all is consistency. Use one or the other - never both!

share|improve this answer

Nearly all the responses here are saying some variation on "Whatever you do, stick with either one or two".

So I thought about it for a moment, and had to admit that I just don't see it as that important. Can anyone honestly tell me that the following is hard to follow?

int foo(int a, Bar b) {
    int c = 0;
    while(a != c)
    {
        if(b.value[a] == c) {
            c = CONST_A;
        }
        c++;
    }
    return c;
}

I'm not sure about anyone else... but I have absolutely zero problems mentally switching back and forth between styles. It did take me a few moments to figure out what the code did, but that's the result of me just randomly typing C-like syntax. :)

In my not-so-humble opinion, opening braces are almost completely irrelevant to code readability. There are a few corner cases listed above where one style or the other makes a difference, but for the most part, judicious use of blank lines cleans that up.

FWIW, our coding styles at work use a slightly more structured form 1 and a modified form 3. (C++)

            // blank line is required here
if (x) {
            //This blank line is required
   y = z;
}
            // blank line is required here too, unless this line is only another '}'

if (x) y = z; //allowed

if (x)
    y = z;  // forbidden

I'm curious if those who strongly prefer form 2 would find this version of form 1 better, just because the blank line gives a stronger visual seperation.

share|improve this answer
3  
As your example shows, indentation is so much important than braces for readable code. In fact, some languages make indentation the only way to nest statements! –  Roger Pate Sep 27 '10 at 12:24
1  
Ok, I honestly find you inconsistent example hard to read. Not REALLY hard, but harder than if it were consistent. –  Almo Jul 20 '12 at 15:14

The cardinal rules are:

  1. Follow the project's existing coding standard.
  2. If there is no coding standard and you are editing an existing code-base owned by someone else - be consistent with the style of the existing code, no matter how much you like / dislike it.
  3. If you are working on a green-field project - discuss with other team members, and come to a consensus on a formal or informal coding standard.
  4. If you are working on a green-field project as the sole developer - make up your own mind, and then be ruthlessly consistent.

Even if you have no external constraints on you, it is (IMO) best to look for an existing (widely used) coding standard or style guideline, and try and follow that. If you roll your own style, there's a good chance that you will come to regret it in a few years.

Finally, a style that is implemented / implementable using existing style checkers and code formatters is better than one that needs to be "enforced" manually.

share|improve this answer
3  
This answer deserves more votes. –  AShelly Nov 1 '10 at 23:04

There is a 4th option that keeps the braces aligned, but does not waste space:

if (you.hasAnswer())
{    you.postAnswer();
     i.readAnswer();
}
else
{   you.doSomething();
}

The only problem is that most IDE's autoformatters choke on this.

share|improve this answer
4  
...as do most programmers who would choke on this. –  Xepoch Nov 5 '10 at 18:05
2  
That seems horrendous. Think of the extra effort you have to go through if you want to insert a line at the top, or remove the top line. You can't just delete the line and move on, you must remember to re-insert the curly brace. –  Bryan Oakley Jul 18 '11 at 14:06

My personal preference is for the first method, probably because that's the way I first learned PHP.

For single-line if statements, I'll use

if (you.hasAnswer()) you.postAnswer();

If it's not you.postAnswer(); but something a lot longer, such as you.postAnswer(this.AnswerId, this.AnswerText, this.AnswerType); I'll probably revert to the first type:

if (you.hasAnswer) {
    you.postAnswer(this.AnswerId, this.AnswerText, this.AnswerType);
}

I will never use a line-break, and I'll never use this method if there's also an else statement.

if (you.hasAnswer()) you.postAnswer();
else you.doSomething()

is a theoretical possibility, but not one I'd ever use. This would have to be turned into

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}
share|improve this answer

I prefer the first because it is harder for me to see the mistake in this example.

if (value > maximum);
{
    dosomething();
}

than it is in this example

if (value > maximum); {
    dosomething();
}

The ; { just looks more wrong to me than a line ending with ; so I'm more likely to notice it.

share|improve this answer
4  
You make a good argument, but personally, this has only ever happened to me once in my 5 years programming. I couldn't figure out why it wasn't executing, posted it on SO and someone quickly pointed out the semi-colon to me. However, every time it is condensed to use that 1 less line, I find it harder to read. –  JD Isaacks Nov 2 '10 at 14:53
3  
The "; {" looks like a kind of winking grumpy face or maybe a person with a moustache. –  glenatron Nov 2 '10 at 23:28
1  
Of course any decent IDE will flag the empty control statement and any decent compiler will issue a warning. –  Dunk Feb 28 '13 at 15:16

Use Python and sidestep the argument completely.

share|improve this answer
2  
+1 SyntaxError: not a chance –  Seth Nov 3 '10 at 0:56

I've always gone for a middle ground:

if ( i<= 10){
    printf("hello");
    i++;
}
else
    printf("goodbye");

I find it the easiest way to recognize code blocks at a glance while not taking up too much space or making the {} stick out.

share|improve this answer
1  
really? to me the left curly brace after an if block seems visually redundant. I know that there is a block of code following the if and don't see it necessary to assign a separate line to the curly brace. The right brace at the end of the block is a little more useful as what follows won't always break the white space as you would like it to ( for instance if you have a loop within a loop). This is the best form I've found for making the conditional visually clear to me without wasting extra space. –  DanLeaningphp Nov 5 '10 at 18:57

They should not; first method for me.

When I look at the second one, because of the unused lines (those only having braces on it, other than the very last closing brace), it feels like it breaks the continuity of the code. I can't read it as fast because I need to take special attention to empty lines which usually mean a separation in code purpose or something like this, but in no case "this line belongs to a curly brace" (which only repeats the meaning of indentation).

Anyway, just like when you write text... adding an indentation at the beginning of a paragraph is superfluous if there is a blank line before it (double sign of paragraph change), there is no need to waste lines for braces when we are properly indenting.

Plus, as already stated, it allows to fit more code in the screen, which otherwise is a little bit counterproductive.

share|improve this answer

The main reason to use the 2nd method is that it keeps the if and the else on the same tab, which greatly improves readability.

share|improve this answer

I prefer

if (you.hasAnswer())
{
    you.postAnswer();
}
else
{
    you.doSomething();
}

over

if (you.hasAnswer()) {
    you.postAnswer();
} else {
    you.doSomething();
}

because the line you.postAnswer(); is much easier to read and find at first glance. In the second way, it gets blended in with the line above it (you.hasAnswer()) making my eyes have to focus more to read it.

share|improve this answer
1  
@weberc2 I think that when your program exceeds the height of the screen, two lines less won't change a lot. –  Mageek Jun 29 '13 at 10:41
1  
10 years ago, I would have agreed about screen space. Today, I use a 1920*1200 screen. It fit a LOT of code, more than my brain can process at once. The first method allows me to pull back and see the different scope opening/closing without having to read it. –  LightStriker Apr 6 at 13:34

The position of curly braces should be

meta data

configurable in the IDE by the programmer. That way, those pesky braces in all code, regardless of author, look the same.

share|improve this answer
1  
Totally agree. It's presentation and not data. –  Petruza Nov 9 '12 at 14:57

I use;

if ($test) {
    //something
} else {
    //something else
}

Because this is the way the phpcs (PHP Codesniffer) likes you to do things when running under it's default setting (which is the Zend standard).

The only other thing to note is the space between 'if' and '('

share|improve this answer

I use the first style usually just to get more code into one screen view. I never use the last it is just to easy to forget to add the {} if you add a second line of code.

Also these have a 'common' names the first one with the {} on the same line is K&R style and the second one with the {} on the next line is Allman or BDS style. (wikipedia indent style)

share|improve this answer

I would prefer 2nd and 3rd method.

1st Method are usually from veteran programmers who learn the old stuff and get used to it. I find it very hard to read the codes last time. Luckily VS2010, make it more easily to read but what happen if you open up other editors? There will be problems.

2nd Method are more clearly define and its more easy on your eyes. You will not have much difficulties looking for the ending braces compared to the first one.

3rd Method will save more space and its clearly define its only reading one line of statement. I disagree with people about programmer taking over and making mistake. It was a careless mistake if they overlooked on this.

share|improve this answer

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