328

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.

36 Answers36

297

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.

rhettg
  • 1,087
239

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.

Edit: Two alternatives to the 'extra blank line' solution when using K&R:

1/ Indent the function arguments differently from the function body

2/ Put the first argument on the same line as the function name and align further arguments on new lines to that first argument

Examples:

1/

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

2/

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

/Edit

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.

klaar
  • 121
Jay Bazuzi
  • 1,604
128

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. (environment,paper wastage)

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) i would say it is okay to use different styles, it's easier to 'switch context' at a high level.

dbza
  • 277
128

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.

Stephen C
  • 25,388
  • 6
  • 66
  • 89
83

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.

EpsilonVector
  • 10,683
  • 10
  • 58
  • 103
59

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.

JD Isaacks
  • 8,926
47

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();
}
P Shved
  • 7,477
  • 36
  • 51
44

Use Python and sidestep the argument completely.

37

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.

Jonathan
  • 101
26

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.

bmb
  • 141
24

I prefer a slight variant of 1)

if (you.hasAnswer()) {
    you.postAnswer();
} // note the break here
else {
    you.doSomething();
}

Why?

  • I think always putting braces on their own line decreases readability. I can only fit a certain amount of source code on my screen. Bracket style 2) makes heavy algorithms with a lot of nested loops and conditionals painfully long.

  • However, I want else to start on a new line because if and else belong together, visually. If there's a bracket in front of the else, it's much more difficult to spot what belongs to what.

    1. disqualifies itself. We all know what bad things can happen if you leave out the brackets and forget about it.
Jack G
  • 242
21

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#.

Robert Harvey
  • 200,592
17

Simple answer: what is easier to debug ?

// Case 1:
void dummyFunction() {
  for (i = 0; i != 10; ++i) {
    if (i <= 10)
      std::cout << "i is: " << i << "\n";
      std::cout << 10 - i << " steps remaining\n";

      // Some hard work here
      // which is really hard
      // and does take some screen estate
    }
    else
      std::cout << "We'll never get there";
  }
} // COMPILER ERROR HERE


// Case 2:
void dummyFunction()
{
  for (i = 0; i != 10; ++i)

    if (i <= 10)
    {
      std::cout << "i is: " << i << "\n";
      std::cout << 10 - i << " steps remaining\n";

      // Some hard work here
      // which is really hard
      // and does take some screen estate
    }
    else
      std::cout << "We'll never get there\n";
  }
} // COMPILER ERROR HERE

In which case did you diagnose the issue first ?

I don't care much for personal preferences (there are many other styles, including whitesmith and al.) and I don't care much... as long as it doesn't hamper my ability to read the code and debug it.

As to the "waste space" argument, I don't buy it: I tend to add blank lines between logical groups anyway to make the program clearer...

Matthieu M.
  • 15,214
12

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).

ChrisF
  • 38,948
  • 11
  • 127
  • 168
10

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.


[Update] I have seen the light, and now worship Allman

Mawg
  • 4,298
9

Not that anyone will notice, but this is why braces belong on the same line as the conditional (except for very long conditionals, but that's an edge case):

In C, this is a valid construct:

while(true);
{
    char c;
    getchar(); //Wait for input
}

Quick! What does this code do? If you answered "infinite loop asking for input", you are wrong! It doesn't even get to the input. It gets caught at while(true). Notice that semicolon at the end. This pattern is actually more common that it seems like it should be; C requires you to declare your variables at the beginning of a block, which is why a new one was started.

A line of code is a thought. Braces are a part of the thought containing the conditional or loop. Therefore, they belong on the same line.

9

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

Nayrb
  • 2,514
  • 1
  • 19
  • 22
6

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.

Ullallulloo
  • 139
  • 6
6

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.

jkerian
  • 651
5

It depends on the platform/language/conventions

In Java:

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

In C#

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

In C:

void someMethod() 
{ 
     if (you_hasAnswer()) {
         you.postAnswer();
     } else {
       you_doSomething();
     }
}

I hate when Java guys use their style in C# code and vice versa.

OscarRyz
  • 1,665
  • 3
  • 15
  • 26
5

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.

FeatureCreep
  • 1,334
  • 1
  • 12
  • 14
5

I'm surprised this hasn't been raised yet. I prefer the second approach because it allows you to select the block more easily.

When the braces begin and end on the same column and on their own line, You can select from the margin or with the cursor on column 0. This generally amounts to a more generous area with mouse selection or fewer keystrokes with keyboard selection.

I originally worked with braces on the same line as the conditional, but when I switched I found it accelerated the rate at which I worked. It's not night and day of course, but its something that will slow you down slightly working with braces next to your conditionals.

3

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.

Joanis
  • 1,364
3

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!

gablin
  • 17,525
2

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();
}
TRiG
  • 1,172
2

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.

Phil Cohen
  • 646
  • 5
  • 7
2

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);
AndrejaKo
  • 583
  • 4
  • 12
0

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.

0

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();
0

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.

Ming-Tang
  • 856
0

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.

AShelly
  • 5,773
  • 32
  • 51
-1

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 '('

Toby
  • 1,921
-1

I find the first option more readable. Never do the third as it can lead to bugs.

As with arguments over underscored_variable_names and camelCase though, the actual choice does not matter much.

Whatever the team or programming language convention is, go along with the stream and follow that convention.

If you vary from the convention it will make reading your code slightly harder, as your brain notices the difference instead of skimming along easily.

brian_d
  • 391
-2

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.

-2

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)

-3

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.