Thursday, April 25, 2013

Where Do Curly Braces Belong?

A question came up in one of my sessions this past weekend (Clean Code: Homicidal Maniacs Read Code, Too):

Do you put opening curly braces on the same line or a separate line?

(Let the religious war begin...)  So, I gave the answer, "It usually doesn't matter as long as you are consistent."  There is an exception for one particular language (which I'll mention below).

The Options
So, let's start by looking at the problem.  With any "curly brace" language, we need to decide whether we put the opening curly brace on the same line as the method or conditional, or if we put the curly brace on a separate line.  "Curly brace" languages are basically anything that uses C-style syntax, such as C, C++, Java, C#, and JavaScript (there are others as well).

Option one is to put the curly braces on the same line.  Here's a sample:

Option two is to put the curly braces on a separate line.  Here's a sample:

Each of these styles has its pros and cons.  So, let's take a look at the advantages, and I'll let you know my personal preference.

Camp One: Opening Curly Braces on the Same Line
The biggest advantage to having the opening curly brace on the same line is to save vertical space.  Vertical density is an important topic when talking about easy-to-read code, so this is definitely something that we should consider.

By having the curly brace on the same line, we reduce the (already short) code sample above by 3 lines.  This means that we have more space on the screen to see additional code.

This is also welcome in books and blogs that include code samples since more code can fit in less vertical space.

Camp Two: Opening Curly Braces on a Separate Line
The biggest advantage to having the opening curly brace on a separate line is that the curly braces will always line up visually (assuming that we are also using good horizontal spacing in our code).  This makes it easy to visually spot the beginning of the code block -- we just need to find the end brace and then scan up until we see an opening brace in the same column.

Camp Three: K&R
Now, there is a third camp that I should mention just because you may run across it.  This is the K&R method (from the book The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie - Amazon link).  I recently ran across a curly brace discussion, and they decided that no matter what, K&R is wrong.

I'll have to admit that I didn't know what the K&R method was.  When I'm reading books, I generally don't pay attention to curly brace layout.  As mentioned above, books often use the "same line" version to save space.  So, I went back and took a look through my K&R and was a bit surprised at what I saw.

Here's a sample (based on the same code block from above):

For methods, the opening curly brace is on a separate line.  But for other blocks (such as the "if" statement), the curly brace is on the same line.

I think that we can all agree that consistency should be high up on the list So, we'll take K&R off the list of possible choices.

Pick One & Be Consistent
Ultimately, which style we choose doesn't really matter.  What's important is that we pick one and stay consistent.  Clean Code by Robert C. Martin (Amazon Link + Jeremy's Review) contains a ton of excellent advice.  With regard to this topic, there is a section that talks about the importance of vertical spacing and horizontal spacing.  Most of the conversation focuses on appropriate blank lines (to break up the code visually) as well as consistent indents (to make code blocks visually apparent).

As with everything else in the development world, we need to find the balance.  That's why I don't spend time in my session to talk about this particular topic.  People on both sides are extremely passionate about how they do it "the one true way".  But really, there are more important things that we should be discussing.

One Exception: JavaScript
There is one exception to the "it doesn't matter" rule: JavaScript.  JavaScript has a quirk in the language called semicolon insertion.  This means that if the JavaScript parser thinks that you forgot to put a semicolon at the end of a line, it will put one in for you.  This can cause problems.

For more information on this, just do some searches for "JavaScript semicolon insertion", and you'll find tons of results.  This is also mentioned in JavaScript: The Good Parts by Douglas Crockford (Amazon Link + Jeremy's Review).  Of course, he puts this into a section called "The Awful Parts."

So, for JavaScript, we should put our opening curly braces on the same line.  Otherwise, we may get unexpected behavior from our code.

Personal Choice
Okay, so you've read through all of this, and I still haven't told you my preference.  I like to have the curly braces on a separate line.  There are 2 reasons for this.

First, I like that the curly braces line up.  This helps me see where the blocks are.  (The same was true when I programmed Delphi (Object Pascal) -- I like to have "Begin" and "End" statements line up.)

Second, I'm a lazy programmer.  I constantly let Visual Studio reformat my code for me (Ctrl+K, Ctrl+R).  The defaults for Visual Studio are to put the opening curly brace on a separate line (unless both curly braces are on the same line -- but that's an entirely different discussion).  As a side note, if you get the "Productivity Power Tools" for VS2012, there is an option to have it reformat your code automatically when you save a file; I don't have this turned on.

You can change the way that Visual Studio formats your code; there's a whole slew of options available.  This is why I put this into the "lazy programmer" category.  For the most part, I run with the Visual Studio defaults (unless there is something that really bugs me).  I have a history of moving around to a variety of machines, so I usually have as little customization as possible so that they will all behave the same.  (I know, there are ways to export profile settings now, but I'm still stuck in my old ways.)

Wrap Up
I always find it interesting to have these types of discussions with other developers.  I like to see who takes it seriously and who sees it as an arbitrary choice.  There's also plenty of other people in between.

Pick your battles.  In a team environment, we need to make sure that we all work in a consistent manner.  Ultimately, where the curly braces go is pretty unimportant compared to other things -- like unit testing strategies.

So, keep your curly braces consistent.  And make sure you're using "the one true way." <smirk/>

Happy Coding!


  1. Curly braces must be placed on lines by themselves. Code is MUCH easier to read this way. I do not understand why programmers insist on placing braces on lines with code. These programmers must be chopped off at the knees!!

  2. I'm definitely a curly-brace-on-it's-own-line person. But if I'm modifying someone else's code who isn't a curly-brace-on-it's-own-line person, I'll do it their way. I'd much rather see consistency than do it my own way all the time.

  3. The conventions are language specific and sometimes indicate an anachronism.

    Java programmers should always have the open brace (not curly brace, that is redundant) on the same line as the beginning of the flow control.

    C/C++ programmers should always have it after. Microsoft prefers this method for C#.

    Java adopted this method as a convention at the same time it was coming up for debate in C++. It was kind of because of this that C++ programmers decided to keep it after.

    The before and after method make the open and close braces more akin to Begin and End in pascal and gives it more natural "white space" to make it easier to read.

    The open brace in the same line method means you have to create an "artificial" line for whitespace to block out your code to make it readable.

    1. A few other notes the on the same line people call this the TBS style (one true brace style) and the the "after" is known as Allman or BSD style.

    2. Wow, you have completely missed the reason for putting the curly brace at the end of the line. It has nothing to do with saving vertical space or making the code easier to read. It is all about AVOIDING MISTAKES.

      If the curly brace is on its own line, then somebody in a hurry can click way past the end of the line, hit return, and insert some code they're desperate to insert. This will compile. But it won't do what they want.

      If the curly brace is at the end of the if/for/while/whatever line, and somebody in a hurry clicks way past the end of the line, hits return, and starts typing, it does what they intended -- i.e. inserts some code into that condition/loop/whatever.

      You should always assume the person maintaining the code in the future is a sleep-deprived, caffiene-short, axe-wielding maniac who doesn't have time to stop and think very deeply about what they're doing. They WILL get their hands on your code. All you can do is make it as hard as possible for them to screw up. Ergo, braces at the end of the line!

  4. Generally speaking, usually only one keyword (in blue type) appears per line. The curly bracket may not be a keyword, but it is a meaningful token and as such is as important as a keyword. (In some languages, its equivalent is a keyword such as begin/end.) Thus for consistency, curly brackets should be on a line of their own.

  5. Same-line-as-control-blocks-opening-brace is, as Joe Strout mentioned, solely to prevent coding mistakes by people in the future (usually one self). The fact that it saves vertical space is irrelevant. All sane books and coding standards preach that each individual control block should be no more than a few lines long anyway.

    The "Opening-brace-on-its-own-line-after-function-declaration" was the only sensible way to do things originally, since parameter types were declared outside the parameter list in the early versions of C. For extra fun, you could leave types out and they would default to int. It looked like this:

    int main(argc, argv)
    char *argv[];
    printf("Hello world\n");

    Nowadays, C (and C++) have function attributes that can go after the parameter list. Keeping the opening brace on a separate line makes it easier to review such changes when looking at patches, or checking historical changes in a version control system. To the best of my knowledge, that's the only argument of any substance when it comes to brace placement for function declarations, and as such is the only thing that carries weight in the debate. For those unfamiliar with such syntax, it looks like this:

    static void fatal(char *fmt, ...)
    __attribute__((format(printf, 1, 2))

    So the only brace placement style that has any *actual* arguments in its favour besides personal preference is the one you immediately discarded. Granted, you seem to mostly be fiddling with C#, which lacks function/method attributes, but if we're talking consistency and the choices are between choosing a brace placement style that sucks for half the C family (and has no downsides for the other half), then it becomes pretty obvious which style we should go with.

  6. So your reason for putting a curly brace on the same line is to protect your code base from careless / maniacal programmers? You have bigger problems to deal with! Put the curly brace on a new line. Having lined up blocks makes it easier to read and faster to maintain.

  7. This works for my like a charm, is my personal preference:

    IF statement:


    for methods or functions i use:

    public myMethod()
    //logic here...

    function myFunc()
    //logic here...

  8. If I'm programming in Java, I put the curly brace on the same line (honestly, I prefer that, because it's more elegant, I prefer lines to either have actual statements on them or nothing at all). If I'm programming in C# however, I respect the convention and go with a curly brace on the next line (to be fair, Visual Studio doesn't like it at all if I DARE put the curly brace at the same line, so)

  9. I think the braces is used for connecting the preceding and the following.
    "One line one statement do one thing" is the most perfect programming way, the braces
    just enclosure sub-statements as an element of the statement. For example,

    // do something with conditions
    if (condition1) { ... } else if (condition2) { ... } else { ... }

    For well reading, put the start brace `{` on the same line means the statement is not finished, put the end brace `}` at the begin of a newline means the line is not a new line, it's a continuation of the previous line.

    if (condition1) {
    } else if (condition2) {
    } else {