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.
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.
Update 2020: Another Exception: Go
Go uses a C-style syntax with braces for blocks. The language enforces style #1: opening brace on the same line. It also enforces that braces are required for "if" blocks and similar structures, even if there is only one line inside the block.
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!
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!
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// Compare:
Deleteif (something.happened()) { // <- curly brace on same line
// Deal with it
}
// with:
if (something.happened())
{ // <- curly brace on different line
// Deal with it
}
/*
I don't need to waste an ENTIRE LINE for just a
SINGLE CHARACTER. The `if` statement already tells
me "A block of code starts here".
I don't need an extra "redundant" line.
But, opinions are opinions. You shouldn't get mad
at people
doing () {
this
}
instead
of ()
{
this
}
I ceartanly don't get mad at anyone. Except at people like
you, who don't understand that opinions aren't for chopping
someone off the knees.
*/
The `if` statement already tells me "A block of code starts here".
DeleteReally? Something I've seen multiple times. You are scrolling your code. you find this:
if(long compare statement. Specially used with "self commented" code)
doSomethingHere();
} <<< at first sight is this for the if?
As a programmer with a leg amputation, and with a taste of using the backets on the same opening block code, I don't take this funny at all...
DeleteI'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.
ReplyDeleteThe conventions are language specific and sometimes indicate an anachronism.
ReplyDeleteJava 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.
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.
Deletehttps://en.wikipedia.org/wiki/Indent_style#Allman_style
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.
DeleteIf 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!
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.
ReplyDeleteSame-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.
ReplyDeleteThe "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.
It's very good
ReplyDeleteSo 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.
ReplyDelete> "Having lined up blocks makes it easier to read and faster to maintain."
DeleteSubjective. I find that NOT doing that helps fit more code on the screen without having to shrink the size of the font which to me and many others, is easier to read. Simply indenting the contents of the code block negates the argument of readability as indenting immediately implies that it is the child of the outdented line above it.
This works for my like a charm, is my personal preference:
ReplyDeleteIF statement:
If(condition)
{
doSomeStuff();
}else{
doOtherStuff();
}
for methods or functions i use:
public myMethod()
{
//logic here...
}
function myFunc()
{
//logic here...
}
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)
ReplyDeleteWhich version of Visual Studio does that? I've been using VS for many years with many versions and I haven't noticed that restriction. I do the { on the next line for code block recognition purposes and having seen the other way of doing it I don't buy the "I can see more code" excuse for it.
DeleteI just tested it with VS 2008 (an oldie but goodie) and it built fine. When I get to work tomorrow (a 10 foot commute these days) I'll see what VS 2019 says. I'm betting it doesn't bat an eye.
I think the braces is used for connecting the preceding and the following.
ReplyDelete"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 {
...
}
i also prefer it on the same line. but looking at getting into new languages so doing some reading. to me the stuff inside the curly braces belongs to a previous statement. you dont go around wrapping code in { ... } just for the same of using curlies.
ReplyDelete[conditional/instruction]{
i belong to the conditional/instruction
}
vs
[conditional/instruction]
{
i belong to the curly bracket
}
we dont write code like
var test = 1
{
var test2 = 2
}
so why would we want to move the curly to its own "header"? the currly is directly related to the part before it. the curly just wraps the logic for the first part
Another reason for putting it on a different line is comments for "else if" and "else"
ReplyDelete// Comment about something
if(something)
{
print(something)
}
// comment about something else
else if(somethingElse)
{
print(somethingElse
}
// comment about else
else
{
print(else)
}
If you have braces on the the same line, you can't really do that without violating some tabbing conventions within braces:
// Comment about something
if(something) {
print(something)
// Comment about something else?
} else if(somethingElse) {
print(somethingElse)
// Comment about else?
} else {
print(else)
}
In your case, I prefer to see:
ReplyDeleteif (something) { // Comment about something
____print(something)
} else if (somethingElse) { // Comment about something else?
____print(somethingElse)
} else { // Comment about else?
____print(else)
}
It contains a lot less visual noise. Regardless, it's an edge case, your code should be written for readability so that you don't need comments to understand it.
One issue you aren't really addressing is the effect on readability when there are large function declarations. For example, my work currently uses the same line braces rule (as well as 88-char line breaks), and we have places that functions with long lists of function parameters. So it can end up reading something like this, and finding where the body of the function begins can be a real chore.
ReplyDeletestd::vector Engine::LogLikelihoods(
const UnrootedTreeCollection &tree_collection,
const EigenMatrixXdRef phylo_model_params, const bool rescaling) const {
return FatBeagleParallelize(
FatBeagle::StaticUnrootedLogLikelihood, fat_beagles_, tree_collection,
phylo_model_params, rescaling);
}
To me, I'm not a fan of the opening curly brace on the same line -- as it can be fine, but when you have a lot of nested if/then/else statements, it's hard to read. Also, I don't like things Crammed in there. We aren't running on 640x480 resolution anymore are we? :)
ReplyDeleteFor your initial example, I'd like to throw my own version which is different than K&R, as it's (gasp) "mixed" .... since we're dealing with something So small in code.
public void RefreshCatalog()
{
if (IsCacheValid) { ResetFilterToDefaults(); }
else { RepopulateCatalogFromService(); }
}