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!

6 comments:

  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!!

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

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

    ReplyDelete
    Replies
    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.

      https://en.wikipedia.org/wiki/Indent_style#Allman_style

      Delete
    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!

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

    ReplyDelete