322

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.

Tamara Wijsman
  • 8,259
  • 14
  • 58
  • 94
  • Excellent question. Can we get som esources as to where the different styles originated? – Moshe Sep 21 '10 at 03:59
  • 4
    The only reason this would matter would be if your IDE/editor doesn't support matching curly bracket recognition. – leeand00 Sep 26 '10 at 23:51
  • 7
    @leeand00: some of us still *print out* complex / unfamiliar code in order to study / annotate it. A good pretty-printer mitigates most of the problems though. – Shog9 Sep 27 '10 at 00:20
  • 3
    @leeand00: oh yes. Doesn't matter how big your monitor is, it can't beat crawling over a conference-room floor covered in taped-together printouts with a Sharpie. – Shog9 Sep 29 '10 at 19:15
  • 1
    Egyptian Brackets! http://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined/2801919#2801919 – jkerian Oct 04 '10 at 21:33
  • 1
    Honestly, aren't there **tools** for this sort of thing? – Christian Mann Nov 06 '10 at 07:56
  • Whenever I get code from someone else that has the brackets barfed onto the ends of the if statement and tacked onto the last line of the block, the first thing I do is change it so that I can see what's happening. I get lazy sometimes when it is just one line and leave off the brackets altogether but I'm not proud of that fact. –  Apr 06 '11 at 14:14
  • 2
    sad the question is closed. After some time of indent based syntax usage I switched to (maybe weird) another braces structure. Like your first but closing brace in the last line of block. (after code line) – cnd Mar 16 '12 at 10:05
  • 3
    Irony: "Please be constructive!" and "closed as not constructive" – Calmarius Jan 17 '13 at 10:10
  • Anyway I prefer the second method. I have OCD, the lack of symmetry annoys me. ;P – Calmarius Jan 17 '13 at 11:23
  • I heard that the second style was invented by low-profile coders who were paid per LoC... That could explain why it's the predominant style at Microsoft ;) – Mints97 Mar 29 '15 at 08:52
  • I prefer the second and third methods for readability, though I'm not sure what the convention is when the condition breaks a line and is indented. Do you indent the parenthesis as well? – Phil D. Oct 29 '15 at 23:36
  • Answering just the title question: no. Curly braces are social animals, and don't like being left alone. If you have only one on a line, make sure you give it some friends: "int main () {{} ..." – Jules Feb 05 '16 at 18:54
  • This really shouldn't have an accepted answer seeing as it is mostly up to user preference. – Stevoisiak Oct 13 '17 at 14:30
  • 1
    This is mostly just a preference. I don't have a strong opinion on it either way, other than to say people who put curly braces on the same line should be rounded up. – Steve3p0 Aug 13 '18 at 00:42
  • the older i get the less whitespace i need – Kirby Dec 19 '18 at 17:31
  • Coming from a visual studio background and learning Java now, I like the braces on their own line. I used these settings for IntelliJ https://superuser.com/a/1403486/75997 – Chris Smith Feb 20 '19 at 06:06
  • https://en.wikipedia.org/wiki/Indentation_style contains names for the various styles, as well as more information, which I found useful to know. – Somatic Custard Mar 28 '19 at 21:23
  • I prefer braces on their own line for readability. I know people don't like the white-space, but to me being able to pick out beginning and end of brackets is more important than the extra lines that are gained from making it more compact. Also to be consistent I never assume implicit brackets. – Daniel Cumings Jun 04 '19 at 17:20
  • I like the 3rd option (no braces on the separate line). However difficulties come when we want to cut and paste the whole line of code to somewhere else. Than instead of pressing fast keyboard shortcut selecting the whole line, we need to spend time on researching every bracket at the end of that line. – Liker777 Jan 10 '22 at 04:12
  • FWIW, I like my closing brace to align under the command or keyword it is closing without anything in between. Follow the closing brace up, and the first keyword or command it meets is the thing it is closing. – KWallace May 03 '22 at 16:07

36 Answers36

292

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.

Joseph Farah
  • 101
  • 4
rhettg
  • 1,087
  • 2
  • 7
  • 8
  • 138
    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 03:19
  • 9
    The thing is that braces are not useless -- they indicate a "block of code". And as long as you are having a block of code, it makes perfect sense to put braces around that block of code. Braces are there to make it absolutely clear where the block begins and where it ends... – Roland Tepp Sep 12 '10 at 06:26
  • 9
    @Roland: that reminds me of those folks who write out expressions with parentheses around *(every) (single) (sub-expression)*... – Shog9 Sep 12 '10 at 20:35
  • 4
    After forgetting to add braces a few times when revisiting the code and adding a line or two in the "else" and forgetting to add the braces, I started using method 2. – MetalMikester Oct 07 '10 at 18:49
  • 88
    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
  • 33
    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
  • 7
    @Ken Bloom I'm with you on this one, we have a convention here that one-line Ifs don't have brackets. Sometimes, it's a pain when I'm modifying those little bits a lot, in which case I just leave them in, and take them out later during code review. No one here has ever made the mistake of not blocking the code properly when adding more stuff later. – CodexArcanum Nov 01 '10 at 22:10
  • 2
    @CodexArcanum I agree, although I usually limit those one line ifs to operations that exit a function/loop/etc. Ex. if(true);\r\n return false; – Evan Plaice Nov 20 '10 at 00:53
  • 1
    @MrC I don't know where it originated, but one place you can read this advice is in Code Complete. – MarkJ Dec 03 '10 at 00:28
  • 2
    I found that ommitting braces in code you work on can be similar to placing gin traps in your front yard. Ecentually, you **will** get hurt. – sum1stolemyname Jan 17 '11 at 08:34
  • 44
    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 06:01
  • 19
    There's one advantage to style #3 that you're all missing: You get more code on your screen at once. – Loren Pechtel Sep 21 '11 at 23:52
  • 10
    @Loren : Heck, if the key is that you can get more code on your screen at once, let's just do away with newlines altogether. You'll get even more code on the screen that way. – Dunk Feb 28 '13 at 15:04
  • 4
    @LorenPechtel You can also use your monitor in vertical position, and use 8pt. – Calmarius Mar 28 '14 at 13:14
  • 4
    I don't buy this argument to add brackets for the next coder. It is like writing feature in your code just for the case they will be needed later. – Florian F Sep 02 '14 at 14:14
  • 9
    Disagree. Simple "If-return" and "If without else" statements can be written quite safely without braces. Requiring braces for all "Ifs" is a style low-quality programmers tend to get all excited about, that adds boilerplate without much real contribution to quality or reliability. – Thomas W Nov 26 '14 at 23:58
  • 6
    Same here, this seems like a modern myth. I have never ever seen a bug from using this syntax, and the first time would be quite amazing to experience. – Alex Dec 29 '14 at 07:51
  • 9
    @Alex: done, Apple SSL bug: http://embeddedgurus.com/barr-code/2014/03/apples-gotofail-ssl-security-bug-was-easily-preventable/ , although arguably there were other ways to avoid such: https://blog.codecentric.de/en/2014/02/curly-braces/ – Gauthier Jan 13 '15 at 09:44
  • @Gauthier Cool! Never seen one of those before, although the use of goto and the suspicion about an intentional attack takes away a little bit of the awe. And the fact that the extra line wouldn't make sense any way. But still, cool. – Alex Jan 15 '15 at 16:17
  • This also depends on conventions. If you always put the curly brace on a new line, it will be obvious when it is missing, and actually, it will allow for clear multiline blocks and compact single line blocks. – GolezTrol Jan 17 '15 at 22:20
  • I personally hate curly braces don't have their own lines. It makes code more difficult to read, loops more difficult to detect in scope, and all for what, saving the coder one indentation and one line? We're far beyond the point of printing out entire applications on paper (for the most part) and one line isn't such a resource hog when we're working with terabytes... – kayleeFrye_onDeck Mar 30 '15 at 21:18
  • 5
    For those in the "never seen a bug because of no curly brace" faction. Now you have: https://github.com/mono/xwt/commit/d89fe856c8c0736746eff52c0464a93195d42461 – Residuum Apr 23 '15 at 08:55
  • 1
    And another argument against omitting braces: What if what looks like a function call is in fact a macro and expands to multiple function calls? – Residuum Apr 23 '15 at 08:57
  • 2
    @Alex I've seen the bug. I've written the bug and it was my own laziness on bracers that cause it. Triple threat! – Gusdor Oct 29 '15 at 15:25
  • 2
    Could the argument be made that this issue contributed to the Apple SSL bug? https://nakedsecurity.sophos.com/2014/02/24/anatomy-of-a-goto-fail-apples-ssl-bug-explained-plus-an-unofficial-patch/ – Ryan E Feb 24 '16 at 19:13
  • 3
    @Residuum I think that is another example why I DON'T like the K&R style (Go lang's forced style). It is so easy to forget to add a curly brace at the end of the line, and much easier not to notice it is missing. Our curly brace style is on the same indent level which makes it much harder to overlook a missing brace, since you would either have an empty line or butt up against the `if..` statement. In the end, this is a matter of preference and proven best practice for your industry. No matter which style you choose, mistakes will happen, it's just a matter of minimizing those risks. – Jeremy Sep 22 '16 at 15:23
  • 2
    @Shog9 re: "writing code for people who won't read it is about as pointless as you can get": Apple's goto fail bug. 'nuff said. – Craig Tullis Dec 01 '17 at 18:02
  • 1
    Blaming that bug on a lack of braces is kinda silly, @Craig. There are many ways the code *could* have been structured to make such an error less likely (for example, putting the goto on the end of the line with the test would've made it much easier to copy-paste without introducing errors *and* kept it compact). Restructuring the logic to not rely on a whopping pile of jumps for control would've been even better. OTOH, even *with* braces a careless paste or merge could've easily left erroneous logic that compiled, but now in a way that couldn't have been caught with static analysis. – Shog9 Dec 01 '17 at 20:05
  • 1
    I’m not arguing that I love the design of that code. But I and others have seen it multiple times. Leave the braces off and you’re just intentionally planting a time bomb. Somebody WILL add another line of code without adding the necessary braces sooner or later, driving incorrect runtime behavior. It’s a bug just waiting to happen. The only argument against it is aesthetic, and that just isn’t good enough. – Craig Tullis Dec 01 '17 at 21:04
  • Yup. One word: #gotofail. – kkm inactive - support strike Dec 13 '17 at 18:11
  • I seriously dislike most of the arguments about this topic. Whether omitting braces or not, it would be in a normal form under some rewriting rules, which should be done automatically easily, like tab v. space. The more significant point is how does the adoption of the style effect the whole things artificially and unnecessarily. For instance: why function definition in ISO C (and lambdas in C++) need mandated braces around even it is a "compound-statement"? I bet few people would realize that is the sin from K&R age, sigh... Distraction on keystrokes seems another crime. – FrankHB Mar 03 '18 at 11:11
  • Write your code for other people – because future you may sometime be that "other people". – Micah Walter Mar 14 '18 at 19:10
  • I devised this rule from experience: the second programmer for my own code was oftentimes myself, and I forgot to place the curly brackets enough times so that I made it a personal rule. I am glad to find out I am not the only one. – lvella Jun 19 '19 at 12:27
  • This is the single most frequent error I've made until I finally decided to never use it again. I'll even annoyingly change other people's code to use braces. I consider it a language-feature bug. – Joe Coder Aug 28 '20 at 00:56
  • I like this because it makes git diffs cleaner. – Aelian Jun 16 '23 at 14:09
237

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
  • 9
Jay Bazuzi
  • 1,604
  • 3
  • 13
  • 19
  • 39
    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 04:42
  • Is the last in each sample a right paren on purpose? –  Sep 27 '10 at 12:16
  • 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
  • 52
    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
  • 28
    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. – Armand Dec 01 '10 at 18:07
  • 37
    Breaking out the parameters to multiple lines like that is maddening. – Fosco Nov 10 '11 at 17:59
  • 6
    I prefer to move the closing paren on to the newline along with the brace. – Merlin -they-them- Oct 31 '14 at 11:47
  • @YevgeniyBrikman: one point with extra empty line is that you're not forced to put it there. With the bracket on previous line, you can choose to put the extra line or not. You don't have that flexibility if the opening bracket is on its own line. – Gauthier Jan 13 '15 at 09:38
  • Most standards I've seen make an exception of "opening bracket on the same line" for just this case: function opening brackets are on their own line. One rationale for this (which sounds very far fetched to me) is that it allows regexp searching for start of functions. – Gauthier Jan 13 '15 at 09:39
  • 11
    The "function parameter" argument is a red herring. Obviously the arguments should be double intended. No problem whatsoever to distinguish it from the following code. – David Ongaro Mar 22 '15 at 21:24
  • K&R with added blank lines!? I've seen it all now. The refusal to admit the palpable superiority of ANSI style is real. – Chris Hatton Aug 03 '15 at 14:10
  • 2
    My golden rule is that it has to be easily [readable](http://pastebin.com/nUjSm1Wa). If it's even *slightly* difficult to skim, it needs revision. – Braden Best Oct 06 '15 at 07:19
  • I came here because i had this exact problem with a long if statement. I recently switched just so i could have more lines on my screen at once as i didnt see any real disadvantage. Turns out this one is and i'll be switching back. – Tom Dec 08 '15 at 11:53
  • I have edited this answer to accomodate for the *real* alternatives used by K&R-fanatics, instead of just resorting to silliness by only allowing equal indentation and an extra blank line as a solution. – klaar Feb 05 '16 at 08:52
  • In my case, what I try for is to wrap a line such that the next begins with punctuation. I personally have found that visual cue very helpful over the years. So in the very first example, "parameterOne" is on the same line as "MyFunction" and the "parameterTwo" line is the same, except it begins with a comma & space. Assuming the "localOne" and "localTwo" part was meant to be a single, wrapped declaration, I'd indent and use a leading comma for "localTwo" also. – Granger Sep 21 '16 at 14:29
  • K&R style when discussing methods/functions is one thing, but the more important [because they tend to exist more often] is the style of if, for, while. In this case, they are surrounded by code. Currently I'm in the process of defining coding standards for C#. I was always a fan of K&R and I try it in here as well, because I think that indentation is good enough to visualise where the if/for/while starts. What's more important to me is to have a line break BEFORE those statements, to separate them from the rest of the code. – Krystian Oct 13 '16 at 07:29
  • 1
    Regular parenthesis should follow similar rules as curly braces when reasonable. So, if I have a multiple-line content inside the parenthesis, I put the closing parenthesis in a separate line. Applicable for function calls with many arguments, as well as long parameter lists at function declarations. – CygnusX1 Jul 17 '17 at 08:21
  • Ugh, the empty line after the brace is a straight-up abomination. What has been found in formal studies on the subject is that comprehension improves when the code following the conditional is in an obvious block. This actually means indenting the closing curly brace if you're putting the opening brace at the end of the line instead of on its own line. – Craig Tullis Dec 01 '17 at 18:04
  • While I'm at it, this syntax on its own line sucks: } else { – Craig Tullis Dec 01 '17 at 18:05
  • The Google Code style for C++, adopted by quite a few projects in the wild, requires braces on the same line, and allows for both choice of options 1/ and 2/. Line after a declaration paren at EOL indents double (4), after comma at the paren of the line above. Starting code indent in 2. – kkm inactive - support strike Dec 13 '17 at 18:17
  • 2
    You could also have the closing parenthesis on a different line than parameters, just as you do for the opening parenthesis. That way, the new line would consist of `) {`, but of course this wouldn't work as an argument against having the opening brace on the same line, if that's your only goal. – Aleksi Sjöberg Jan 08 '18 at 04:30
  • @Fosco As is usually the case with these sorts of things, sometimes you don't really have much of a choice. If the parameters/conditions are numerous and your horizontal scrollbar starts to look more like a tiny square, breaking out across multiple lines is great. – Jacob Stamm Feb 17 '21 at 18:47
  • This is exactly the approach I take. I'm a "braces right" guy, but when my if() conditions are going to span more than one line, I really do not like it when the opening brace is in the middle-ish, and there's code farther to the right than the right brace in the line above it. In those cases, and only in those cases, I drop the opening brace to a new line. ;-) – KWallace May 03 '22 at 16:05
  • I find the best way to format parameter lists is to consistently indent the parameter brackets, with the closing bracket being on the next line, un-indented. This way, the opening brace can be on the same line as it, and you still get the separation. It's also much more readable in general if you always have the closing bracket unintended on the next line whenever you have a line break after the opening bracket. – Steve Jul 25 '22 at 01:59
  • I think this is obviously the right answer. When you have multiline ifs,funcs whatever, you do not know where the block starts if the brackets are at the end of the line. However, the guys putting the opening brackets at the end have won this war, no doubt about it, hence I believe we have to go with that. This is also true for new languages that had the freedom to stop this discussion once and for all - all Rust code opens brackets at the end. Simply stopping the discussion, as Stackexchanges does by simply closing it, does not help. – Patrick Fromberg Aug 10 '22 at 08:19
125

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
  • 1
  • 3
  • 10
  • 8
    On the other hand, the brace on the new line is an ANSI STANDARD, K&R is not. But the beauty about standards is, that there are so many different ones (see also http://uncyclopedia.wikia.com/wiki/AAAAAAAAA! on uncyclopedia). – Quandary Mar 31 '16 at 09:53
  • "there are fewer lines" I have Terabytes of Space and lots of Pixels. Why should i care about use more lines? – 12431234123412341234123 Sep 21 '16 at 06:27
  • 1
    @12431234123412341234123: I think he means because some people print the code out for code-review. And each not absolutely necessary newline is paper wasted, or a km² of forrest wasted at scale. However, if you don't print it out (i certainly don't) then ANSI is a lot better than K&R. Also, anybody who intends to print should probably use an automated code formatter - so this should be a question of tooling, not one of coding style. – Quandary Oct 11 '18 at 16:00
  • 1
    I agree that you should stay consistent, I'm been using curly braces on new lines for years, but I have to mix in the other way in my code, such as when calling functions, anonymous functions, object literals etc. Any expression-based languages / anonymous code make brackets on the same line much easier – David Callanan Dec 06 '19 at 22:24
124

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,180
  • 6
  • 64
  • 87
82

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,763
  • 10
  • 56
  • 103
  • 1
    Why make it look horrible by saying WASTING AN ENTIRE LINE??? Better say, Are they worth a single character '\n' ......n I say, Yes sir, they are. – loxxy Sep 11 '10 at 09:38
  • 15
    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 09:54
  • 11
    When I was beginning coding I liked each brace on its own line, now I prefer the first method – NimChimpsky Sep 21 '10 at 09:01
  • There's a reason it's called the ONE TRUE Brace Style. – Frank Shearar Oct 31 '10 at 10:28
  • 65
    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 01 '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. – Benbob Nov 03 '10 at 22:48
  • 10
    LOL @ "wasting an ENTIRE line". OMG! Not that!! =P – Nick Spreitzer Dec 12 '10 at 19:47
  • +1 @Nick @John R. Strohm I agree about whitespace in code. Afterall visual design rates whitespace highly, and code is another form of visual communication, so whitespace has value. – therobyouknow Jan 17 '11 at 13:24
  • 3
    I'm sure this is a coincidence, but I've noticed that, in **my** experience, the proponents of the second method tend to fall into one the two categories. New/relatively new to programming, or don't care about code clarity as much. Again, I don't doubt this is just a coincidence, but it's something I've observed. Yes, I favor method 1 and I used to favor method 2 (long, long ago). – Julio Apr 04 '11 at 03:18
  • 3
    @Julio I've been coding for 5 years and still prefer the 2nd method, and precisely because I care about code clarity. Having a block of code between the braces makes what's happening a LOT clearer. – Click Upvote Apr 18 '11 at 15:19
  • 10
    @Julio In college I favored method 1 strongly, and couldn't stand to read method 2. After going to work at a company that uses C#, where the standard is method 2, I've come to like that just as well. I can now read or use either; neither one bothers me. People who have a strongly averse reaction to one or another are generally overreacting to something that they are unfamiliar with. – KChaloux Jan 17 '13 at 15:54
  • 1
    @Julio I use Allman, and I've been programming for decades, AND I'm terribly picky about code clarity. – Almo Sep 30 '14 at 20:35
  • 2
    Because the opening brace for a block of code DOES add to the clarity, it is immediately visible where the start of the block of code is. – CashCow Oct 07 '14 at 13:52
  • 1
    @JohnR.Strohm That book is 43 years old. Although its argument still may be valid is regards of comprehension and the amount of code you can see, one might think that our resources of vertical space is on a whole different level today. Maybe even so that there is other more relevant factors now, like for example clear separation of blocks. – Alex Dec 29 '14 at 09:10
  • 3
    @Alex, one might think that. One would be highly mistaken. 40+ years ago, using video display terminals and text editors for programming was VERY RARE. The vast majority of programmers used printed listings, at roughly 66 lines per page. EVEN TODAY, tubes that support 66 lines per screen, with a readable font, are relatively uncommon, meaning that Weinberg's data is still highly relevant today. – John R. Strohm Dec 29 '14 at 11:08
  • 1
    @JohnR.Strohm Good counter-argument, but if this is based on static printouts... What about the IDEs navigability and outlining management of today? 66 lines of static code maybe is significantly different to 66 lines of interactive code in regards to comprehension. – Alex Dec 29 '14 at 12:05
  • 1
    @Alex, comprehension is generally limited to what the programmer can see WITHOUT turning a page, or scrolling, or punching a button. Fancy "navigation" features still boil down to turning pages, meaning the programmer has to remember what he left behind, reducing comprehension. An IDE that can collapse and expand blocks might help, but I've only heard of one such (Rational R1000, for Ada) and I've never used it. – John R. Strohm Feb 18 '15 at 14:19
  • 1
    @JohnR.Strohm I think IDEs with the ability to collapse blocks of code like methods and classes are standard these days. At least in PHP and C#, I know one semi-popular PHP IDE that can/could not do "code-folding", and it got a lot of bashing for that. This is one of the major features I had in mind, together with very simple one-click navigation to dependencies of classes, implementations of abstracts and interfaces and such. At least in Visual Studio with ReSharper. I would feel very handicapped without the later, code-folding is mostly just neat to have. – Alex Feb 18 '15 at 15:21
  • 2
    @Keyo By that logic we should all just zoom out until the text is as small as we can tolerate. – Pharap Dec 23 '15 at 04:50
  • Ever since widescreens and toolbar "ribbons" caught on, I've found myself short on vertical screen space - even with giant 2560x1600 displays. I appreciate when developers opt for the style that conserves my precious vertical pixels. – rkagerer Oct 27 '16 at 11:02
  • 1
    Wasting an entire line? Don't you have as much space as you want? Literally a million lines if you want? – Tyler S. Loeper May 28 '18 at 18:27
60

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,924
  • 12
  • 47
  • 54
  • 17
    This is true until your program exceeds the height of your screen. ;) – weberc2 Apr 04 '13 at 18:09
  • 20
    @weberc2 I think that when your program exceeds the height of the screen, two lines less won't change a lot. – Alexandre Khoury Jun 29 '13 at 10:41
  • 22
    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 06 '14 at 13:34
  • 3
    I could never fathom why I preferred this method but it's for exactly this. – Declan McKenna Jul 30 '15 at 17:00
  • @weberc2 You have another -bigger- problem if you are writing a function that exceeds the height of your screen – qwerty Dec 18 '15 at 21:45
  • @accfews I said 'program', not 'function'. – weberc2 Dec 18 '15 at 21:53
  • 4
    @Mageek This is belated, but it's not 2 lines, it's 2 lines for every scope. That's O(N), not O(1). I don't actually feel that strongly about it; it's more important that you pick a style that makes long parameter lists readable. – weberc2 Dec 18 '15 at 21:56
  • @weberc2 While it may be for each scope difference, you don't need all scope changes in your mind when trying to figure out what that if/then statement does, you just need that 1 or 2 scopes, as well as the 1 or 2 conditionals. So in that case it is more along the lines of O(1) as you're only looking at one set. – Joo Beck May 18 '18 at 16:40
  • 1
    @weberc2, Scroll down? Isn't writing a program or even function that is larger than the screen quite common in large companies? Out of the millions of lines of code in my company, I'm pretty sure at least 30% are functions much larger than the screen. – Tyler S. Loeper May 28 '18 at 18:29
45

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,427
  • 35
  • 50
  • 8
    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
  • 16
    @Robert, In C you have to do *both* whitespace and braces. In Python you should do only whitespace. Which is better? – P Shved Sep 16 '10 at 17:34
  • 5
    @Pavel, in C' you don't have to do whitepace. – Ken Bloom Oct 22 '10 at 14:26
  • 8
    @KenBloom C programs without whitespace are impossible to read. So you have to do them anyway. – P Shved Oct 23 '10 at 11:21
  • 2
    @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 05 '10 at 18:50
  • 1
    I don't pair braces visually. I pair the last statement in one level of indentation with the closing brace. I write my C like I write my Python; I just use braces as well. I'm trying to fix a project written in Python, and I don't like the style at all. – Christian Mann Nov 06 '10 at 07:54
  • 8
    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 06 '11 at 14:52
  • 1
    If the above example is supposed to be supporting a more cleaner and easier to understand way of coding then you lose. What a mess. – Dunk Feb 28 '13 at 15:02
  • 1
    @Dunk, I read it fine. And it really pays out when you get more than a page's worth of code. You don't waste time scrolling up and down a page of code that is 30% larger than necessary simply because you (stupidly) decided a brace and indentation conveys more meaning than indentation alone... – weberc2 Apr 03 '13 at 20:21
  • 1
    @weber:Your opinion is just fine "IF" the only reason you indent is for stuff like if-then-else code blocks. However, there are many reasons for indenting code and many of them have nothing to do with delineating code-blocks. Thus, you have to look and take time to see WHY the code was indented using your method. May or may not take much time, but it does take time, it does take thought away from understanding the code, thereby making it less readable. Also, if you are having to scroll up and down very often in a single method/function then it is your code that is the problem not the braces. – Dunk Apr 04 '13 at 17:17
  • @Dunk: It also works for enums, namespaces, function definitions (multi-or-single line), multi-line function calls (e.g., 1 line per param), and every other reasonable use for indentation in code. I agree that it takes time to see *why* it was indented, but it takes me less time than scrolling all over creation to see other parts of my code. Good style is not without costs, but the costs thereof are outweighed by the benefits. – weberc2 Apr 04 '13 at 18:04
  • @Dunk: Otherwise just use Ada/Pascal syntax. Then you can see **exactly** why your code is indented irrespective of whether you're at the beginning or end of your block. And you can forget about your brace keys altogether! :) :p – weberc2 Apr 04 '13 at 18:07
  • 1
    @weberc2 Good point, but minor observation: I think you mean Ada/Modula/Fortran, not Ada/Pascal. Pascal uses `begin` and `end` for delimiters which is just as stupid as the curly brace languages. – Ray Toal Mar 06 '14 at 05:54
  • @RayToal Ada and Modula use `begin/end` as well as Pascal, which was exactly the point of weberc2 IMO. – Joffrey Jun 30 '14 at 15:39
  • Not true at all. Ada and Modula, like Ruby, use a plain `end`, and no `begin`. Maybe you are thinking of the `begin` that starts a procedure or function, but this is completely different than using blocks to start a structured statement like and `if` or `while` which was the point of the question. Maying I was being pedantic, but Pascal is absolutely subject to the same annoying "should I put my `begin` on the same line as the `if` or on the next line?" question. Ada and Modula **are not**. Huge, huge difference here IMHO. – Ray Toal Jun 30 '14 at 18:21
  • @PavelShved The benefit of curly braces is that it can be minified to take up less space as the white space isn't needed to compile. So back when space was far more of a commodity than it is now, that was a huge deal. And on systems where space is still limited, it can still be a huge deal to not have to keep whitespace because the language needs it. – Joo Beck May 18 '18 at 16:43
  • Braces are very important and not just trash. When you place it wrong, your code gets broken, in the worst case, the wrong code will still compile. – 12431234123412341234123 Oct 11 '18 at 18:18
44

Use Python and sidestep the argument completely.

Mark Ransom
  • 763
  • 5
  • 12
  • 26
    +1 `SyntaxError: not a chance` – Seth Nov 03 '10 at 00:56
  • 8
    This is simply not an option for the vast, vast majority of projects. Plus, indentation-for-grouping has it's share of problems. – Bryan Oakley Jul 18 '11 at 14:02
  • @Bryan, I realize that this isn't very practical. I just thought it was a point of view that needed to be out there, stronger than just a comment. And I've never run into the problems caused by indentation that you imply, probably because I don't mix tabs and spaces. – Mark Ransom Jul 18 '11 at 15:46
  • Use Go and sidestep the argument completely (plus static typing, speed, and a compiler!) :) – weberc2 Apr 03 '13 at 20:23
  • 4
    Then press the space bar one too many times and watch the compiler/interpreter laugh at you. That won't happen in most braced languages. – Pharap Feb 02 '15 at 05:00
  • Yeah use an something like coffeescript where extra unnecessary syntax isn't prevalent. – Nick Sotiros Feb 26 '16 at 17:06
  • @Pharap: OR we can use *proper* tools like an IDE that takes care of the indentation for us. Also: use tabs, not spaces, for indentation - those will stand out if they are unintended (lol get it, unintended indentation). – klaar May 03 '16 at 11:31
  • @klaar IDEs aren't always available or suitable. For example some programs that use python for scripting have a built in REPL for handling commands. To use an IDE you would have to set the IDE up to recognise the program's libraries (if they are externally exposed and not self-contained within the program) and read from/output to the program's script directory, and then you'd have to remember to save in the IDE before loading the script in the program. It's doable but it's time consuming. If you do have a decent IDE though, it shouldn't matter if you're using tabs or spaces for indenting. – Pharap May 04 '16 at 17:41
  • @Seth: No SyntaxError is hardly a good thing. To take your argument to the extreme: code in machine code, and then any sequence of bits is syntactically valid, no brace, no space, no syntax error ever. Also a feature of some BrainFuck-ey esoteric languages. I want my compiler catch the error at compile time, not fight with it's (often remote) consequences at runtime. A hello world is fine in Python, a million-line code base is a disaster. Besides, the whole #gotofail and HeartBleed happened only due to incorrect indentation. – kkm inactive - support strike Dec 13 '17 at 18:26
  • The syntax error itself sounds like a joke. Is there any formal grammar can handle the condition _syntactically_ without artificial preprocessing phases not defined in the language spec, despite that unexpected indentation does actually involve the _semantics_ of the language a lot? – FrankHB Mar 03 '18 at 11:22
  • @FrankHB it is a built-in joke, try in python `from __future__ import braces` – hans Jan 10 '19 at 11:28
36

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
  • 1
  • 4
  • 10
    Totally agree. It's presentation and not data. – Petruza Nov 09 '12 at 14:57
  • 1
    The issue is that if you let everyone set their own, things get messy very quickly as commits are done. – Andy Jun 04 '16 at 01:22
  • 2
    @Andy: That's exactly the point, the IDE will change how they look, but only in the IDE! The actual source will not be touched. For version control, you can add hooks that translate whatever the setting for curly braces was to a common situation, so that everyone checks code out the same way. – klaar Aug 01 '16 at 07:44
  • 3
    @klaar Every modern IDE i've used will change tabs to spaces and move braces to their own line or the end of the "opening" line; I'm not sure why you think the source isn't touched in these cases, and that is the reason for my comment. It IS typically changed by the IDEs depending on the developers settings, which means during a commit I'll see lots of changes which are just noise as the braces got moved to thier own line, thus hiding the ACTUAL change someone did. – Andy Aug 01 '16 at 22:26
  • @Andy: Isn't there the possibility to use hooks that convert those discrepancies regarding whitespace and braces to a uniform standard uppon commit, to circumvent the noise problem you described? Either way, a proper versioning system *should* transcend petty things like whitespace or other nonsensical things. – klaar Aug 02 '16 at 07:17
  • @klaar Assuming your VCS has such a thing as post-commit hooks; not all of them do. And post-commit sounds like something done AFTER the commit is now in the VCS, so likely too late to do anything anyway. Then there's other formatting, things like what R# calls line chomping, and now we're talking about a whole lot of formatting done where the developer doesn't have a chance to review it, and which may matter depending on the language. Or I can just dictate everyone use the same settings, and enforce those mandates with things like a shared R# settings file, which can itself be versioned. – Andy Aug 02 '16 at 21:19
  • Fair enough, it's presentation. Presentation is what led to the Apple `goto fail` bug, incidentally. I will contend that presentation matters. – Craig Tullis Dec 01 '17 at 18:08
25

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
  • 5
  • 11
  • 14
    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 02 '10 at 14:53
  • 7
    The "; {" looks like a kind of winking grumpy face or maybe a person with a moustache. – glenatron Nov 02 '10 at 23:28
  • 1
    +1 Great example in answer: very subtle mistake, easily overlooked. Thought provoking too on layout showing this up. – therobyouknow Jan 17 '11 at 13:27
  • 11
    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
  • @Dunk The only flaw in your argument (which I vigorously agree with) is that so many people are using interpreted languages these days (JavaScript, PHP, et al) that a lot of "programmers" wouldn't know a compiler from a double latte. – Craig Tullis Dec 01 '17 at 18:11
20

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
  • 198,589
  • 55
  • 464
  • 673
  • 1
    It can be written in a lot of languages like that, because a block-statement is a statement. Adding! :-) – Tamara Wijsman Sep 11 '10 at 00:34
  • 4
    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
  • 3
    @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
  • @Uwe: That's Cwalina's book and it's terribly named as it is much more than that. The FDG on MSDN has nothing to say about that. Also I wonder, why would the *Framework* *Design* Guidelines say anything about *C#* *coding* practice? – R. Martinho Fernandes Sep 15 '10 at 03:15
  • 4
    You should, in fact, put curly braces on the same line in Javascript. You can cause errors if curly braces are on their own line. For example, see http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/ – Joseph Hansen May 06 '15 at 21:51
20

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
  • 2
  • 16
  • 1
    I have seen this one around where I work. It's interesting. – Almo Jul 20 '12 at 15:16
  • 2
    I also like this style better, as it allows me to put comment above the `else` line when needed, and/or put a blank line between the if-block and the else-block to make things look less crammed. Bracket style #2 does nothing other than distancing the actions from the conditions. With that said, my favorite is definitely python's no bracket style :) – sayap Oct 28 '12 at 03:26
  • 4
    If maximizing the number of code lines on the screen is important then just do away with newlines altogether. You'll be able to get a lot of lines on one screen. I prefer to not have anything cause me to pause and think while reading, ie. my definition of more readable. With the braces my mind ignores them. Without the braces my mind has to pause and align the control blocks. Not a long pause, but a pause none-the-less. – Dunk Feb 28 '13 at 15:21
  • 1
    Yes, if and else belong together, BUT so do { and } and as } is on a separate line, { should be on a separate line, too. "I can only fit a certain amount of source code on my screen" And that's exactly why saying the 3) would be "disqualifying itself" is no option at all. After a decade of working with 3) I have not forgotten adding brackets when adding a new line of code, ever, nor do I know anyone who ever had. If I have to adjust code to people, who can't read properly, where does it end? Stopping using certain language features, because some of the codes readers may not understand them? – Kaiserludi May 05 '14 at 18:25
  • @Dunk If you feel cramped with so few lines, take a few pages to breath everywhere allowed. Yes, this is equally absurd. – Deduplicator Jun 02 '22 at 18:25
16

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.
  • 14,567
  • 4
  • 44
  • 65
  • 2
    They are both as easy to debug, mainly since it's a short block of code. The indentation is consistent making it easy to visualize the actual code blocks. – Htbaa Apr 06 '11 at 14:44
  • @Htbaa: indeed :) So why bother ? – Matthieu M. Apr 06 '11 at 15:22
  • @MatthieuM. The first block makes more sense to me, because the newlines (in the second block) between the function signature, the for-statement and the if-statement have me believe they are unrelated, but clearly they aren't. Blank lines are to separate unrelated bits of code; code that's close to other lines of code means that they are in fact related. This is all 'imo' of course, but I wondered what your point was. EDIT: also any proper IDE will notice any brace missing and give you a smattering of errors upon interpreting your code. – klaar May 03 '16 at 11:48
  • I would like to point out that these two code sections are completely different. You would have compiler errors at different points in the code. The first would have a compiler error on "else" and the last curly. The second would only have a compiler error on the last curly. – Mark Walsh May 05 '20 at 18:22
11

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,878
  • 11
  • 125
  • 168
  • ... The second option also facilitates both of your points (with indentation alone serving the purpose of the brace/indentation combo). :) – weberc2 Apr 03 '13 at 20:24
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

  • 9
    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
  • I know of no one who uses the GNU style. 1TBS all the way. – Jé Queue Nov 05 '10 at 18:00
  • You can't do any worse than two indentation levels per block, except for lisp style, of course, that goes without saying. – ergosys Jan 28 '12 at 05:57
  • 4
    +1 for the link on brace styles. It shows that whatever your style, many great people disagree with you. – Florian F Sep 02 '14 at 14:28
  • @RobertHarvey There is no extra work, if it is, you don't use the right tool to write code or dint configure it right. The benefit is much more readable code, you see every error in the bracket very fast and you can easy read only the code from while ignore subblocks. – 12431234123412341234123 Sep 21 '16 at 07:13
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.

  • 1
    This is by far the best argument for K&R style I have seen, the rest are laughable with today's IDE systems with code folding support. This does only apply to C style languages which support `;` block ends. This is also why I despise this block ending system which IMHO is outdated and the Go language proves it. I have seen this issue many times although not in this scenario. It usually happens where they intend to add something to the statement and forget to. – Jeremy Sep 22 '16 at 16:19
9

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

Bryan Harrington
  • 2,502
  • 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
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
  • to be used like that, `postAnswer()` and `doSomething()` should return value for ternary operator, which is often not the case: they can very well return void (no value). and also (at least in c#) result of `?:` should be assigned to some variable – ASh Aug 17 '18 at 12:01
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.

Tim O'Neil
  • 277
  • 2
  • 3
  • 2
    Old timers like me use three keystrokes to select the block no matter where the damn braces are. – ergosys Jan 28 '12 at 06:10
5

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
  • 10
  • 4
    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! –  Sep 27 '10 at 12:24
  • 2
    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
  • I agree with Almo. It is not a case of "is it really hard". It is a case of "it is definately harder", even if not hard. So why make things harder? In the "toy" examples people give of course there is little difference. In my experience, When I inherit nasty code from someone else and they used method 1, quite frequently it becomes necessary to go ahead and turn it into method 2 just to be able to follow the logic. Because of the fact that it becomes frequently necessary; it automatically answers the question of which method is better and easier to understand. – Dunk Feb 28 '13 at 15:12
  • 1
    @Dunk: I cannot fathom code that would be noticeably improved by swapping such irrelevant details around. – jkerian Feb 28 '13 at 15:28
  • @jkerian-Apparently you haven't inherited much code from others who have long left either the project or company. I can't fathom not running into that situation by anyone with some years of experience. But then again, everybody's work situation is different. Also, if you have to do "formal" code reviews, formatting makes quite a difference. Being able to read the code naturally is very important. Sure I can pause and think to match up braces, but that slows the process down. One way does not require pausing, the others do. That's why I don't see why any other choice could be recommended. – Dunk Mar 06 '13 at 21:05
  • 1
    @Dunk: Every one of your presumptions about me in that comment is hilariously wrong. I still cannot imagine being slowed down by such nonsense. Indentation is important for clarity and speed, brace-style is irrelevant. Actually... I suspect it's exactly because of the variety of coding standards I switch between daily that makes me not even notice brace style. (helpfully, my editor flags me for project-specific coding standards violations) – jkerian Mar 06 '13 at 21:13
  • @jkerian-Well you are just awesome. Nothing slows you down. Not the case for me (who also has had to work with many different styles which is the reason for my strong opinion). I've held the it doesn't matter opinion before, but when I started paying attention...guess what....IT DOES MATTER. – Dunk Mar 06 '13 at 21:21
4

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,675
  • 3
  • 15
  • 26
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
  • 2
  • 12
  • 14
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,170
  • 1
  • 11
  • 21
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
  • 573
  • 4
  • 12
2

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,377
  • 22
  • 89
  • 138
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.

Digital Dude
  • 393
  • 2
  • 8
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();
Chankey Pathak
  • 3,249
  • 28
  • 32
  • 2
    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
  • @FinnNk : Exactly ! – Chankey Pathak Sep 12 '10 at 15:18
  • 3
    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
  • I wanted to say that his 3rd method is wrong. – Chankey Pathak Sep 16 '10 at 16:47
  • 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 02:13
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
  • 5
  • 15
  • 5
    +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. – Jé Queue Nov 05 '10 at 18:05
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,793
  • 31
  • 51
  • 12
    ...as do most programmers who would choke on this. – Jé Queue Nov 05 '10 at 18:05
  • 4
    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
  • lol this is awesome! :) better than first style! – nawfal Jan 14 '13 at 08:50
  • Apparently it even has a name. [The Horstman Syyle](http://weblogs.java.net/blog/cayhorstmann/archive/2010/06/28/horstmann-brace-style) is mentioned in [wikipedia](http://en.wikipedia.org/wiki/Indent_style#Horstmann_style). I've worked with a codebase like this, it's really not bad to use. – AShelly Jan 14 '13 at 14:29
-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
  • 12
  • 21
  • My exception on this one is that `else` and `elseif` do go on a newline so they aren't prefixed with a closing brace. – Htbaa Apr 06 '11 at 14:43
-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
  • 1
  • 4
  • 9
-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.

DanLeaningphp
  • 480
  • 4
  • 10
  • That is pretty confusing if you ask me. – Toby Nov 02 '10 at 20:49
  • 2
    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 05 '10 at 18:57
  • this is like completely inconsistent :) – L-Four Mar 15 '13 at 10:26