73

I've spent most of the last several years working mainly with C# and SQL. Every programmer I've worked with over that time was in the habit of placing the opening brace of a function or control flow statement on a new line. So ...

public void MyFunction(string myArgument)
{
     //do stuff
}

if(myBoolean == true)
{
    //do something
}
else
{
    //do something else
}

I have always been struck by how space wasteful this is, especially in if/else statements. And I know alternatives exist in later versions of C#, like:

if(myBoolean == true)
    //do something on one line of code

But hardly anyone used them. Everyone did the curly-brace-on-newline thing.

Then I got back into doing JavaScript after a long absence. In my memory, JavaScript developers used to do the exact same curly-brace-newline thing but with all the fancy new libraries and stuff, most developers put the opening brace after the declaration:

function MyJavaScriptFunction() {
    //do something
}

You can see the sense in this, because since using closures and function pointers has become popular in JavaScript, it saves a lot of space and makes things more readable. So I wondered why it wasn't seen as the done thing in C#. In fact, if you try the above construct in Visual Studio 2013, it actually reformats it for you, putting the opening brace on a new line!

Now, I just saw this question on Code Review SE: https://codereview.stackexchange.com/questions/48035/questions-responses-let-me-tell-you-about-you In which I learned that in Java, a language I'm not overly familiar with, it's considered de-rigour to open your curly braces right after the declaration, in modern JavaScript fashion.

I had always understood that C# was originally modelled after Java, and kept to a lot of the same basal coding standards. But in this instance, it seems not. So I presume there must be a good reason: what is the reason? Why do C# developers (and Visual Studio) enforce opening curly brackets on a new line?

Bob Tway
  • 3,606
  • 3
  • 21
  • 26
  • 39
    Convention is simply that. – Oded Apr 25 '14 at 13:12
  • 1
    @Oded yes ... but why? Why is it different in C# from other syntactically similar languages? – Bob Tway Apr 25 '14 at 13:12
  • 26
    Visual Studio enforces nothing, the code style is configurable. *Something* needs to be the default. Which default is "better" is bikeshedding of the highest order. – Phoshi Apr 25 '14 at 13:13
  • 1
    Why not? Why is the JS style the way it is? Or the K&R? Or... or... or... – Oded Apr 25 '14 at 13:16
  • 2
    You may have misunderstood my question. I'm not asking for opinion on which is better. I'm looking for historical precedents as to why the de-facto standards are different. This is purely a matter of personal curiosity rather than problem solving. If you think I've phrased it badly, will gladly edit. – Bob Tway Apr 25 '14 at 13:16
  • 3
    Don't fret over bracing style. I used to hate the C# style of bracing, back when I was learning Java in college. I then got a job in C#, got used to it, and it no longer bothers me, at all. The only reason I didn't like it was because I was unfamiliar with it. This is one of those things that is just too much of a nitpick to give yourself heartburn over. – KChaloux Apr 25 '14 at 13:20
  • @KChaloux Thanks, but I'm not fretting. As I've tried to make clear, I'm just curious as to whether there's a historical reason for the differing styles. It seems a straightforward and objective question to me, which does not depend on personal opinion. Slightly surprised by the negativity it seems to be generating. – Bob Tway Apr 25 '14 at 13:23
  • 2
    @Phoshi: Ask 100 arbitrary C# developers how many of them have change that particular setting. I bet my whatever, it is only a small fraction. – JensG Apr 25 '14 at 13:26
  • 1
    @JensG: Yes, because it's not important in the slightest. There doesn't need to be a big reason or grand story behind why one community took one path and another took another in a meaningless decision, it can simply *be*. – Phoshi Apr 25 '14 at 13:28
  • @Phosi Communities don't generally make deliberate and conscious decisions as a body. So while it's plausible they diverged for entirely random reasons, other examples suggest there's usually a reason, even if it's a trivial one. – Bob Tway Apr 25 '14 at 13:31
  • 31
    The brace at the end of the line is the ancient K&R C standard. Kernighan and Ritchie invented the C language when computer displays only had 25 lines (23 if you add header and status lines). That isn't really the case any more, right? **What is important is consistency throughout a project.** There *are* also scientific studies showing that the brace on its own line (indented to the same level as the code, in fact) improves code **comprehension** despite what people think they think of the aesthetics. – Craig Tullis Apr 25 '14 at 13:55
  • 13
    C# has *always* supported evaluating a single line of code after a conditional, by the way. In fact, that's the *only* thing it does, even now. Putting code in braces after a branching expression just makes that instruction a goto (the compiler creates scope using jmp instructions). C++, Java, C# and JavaScript are all more or less based on C, with the same underlying parsing rules, for the most part. So in that sense, C# is not "based on Java." – Craig Tullis Apr 25 '14 at 13:59
  • @Craig Thank you. That's just the sort of answer I was hoping for. If you add it as an actual answer, I'll certainly upvote and possibly accept it. – Bob Tway Apr 25 '14 at 14:02
  • @Oded Given this question now has a favourite, an upvote and a viable answer, can it be taken off hold please? – Bob Tway Apr 25 '14 at 14:02
  • 2
    Well, thanks Matt. I'd go ahead and add it as an answer, but the hold is crimping my style. :-) This *is* a bit of a religious/flame-war issue. But there are studies making it pretty clear that arranging code in blocks improves comprehension. The *compiler* couldn't care less. But this is also related to the reason why I never put a line of code after a branch without braces--it's just too easy to later add another line of code without adding the braces and create a bug. Still, I'll admit that JavaScript closure syntax looks a little silly with braces on their own lines...aesthetically. :-) – Craig Tullis Apr 25 '14 at 14:17
  • 20
    As a side note, `if(myBoolean == true)` makes little sense to me. While we're at it, while not `if ((myBoolean == true) == true)`?? Just `if (myBoolean)` and that's enough. Sorry, a pet peeve of mine. – Konrad Morawski Apr 25 '14 at 14:42
  • 1
    @KonradMorawski: that's funny. I agree, much better to see `if(myBoolean){}`. No need for a belt *and* suspenders. In fact, since someone here has probably guessed that I think highly of many of Steve McConnell's conclusions, I like to see somewhat self-commenting code like `bool allDocumentsAreReady = (/*long list of conditions*/); if( allDocumentsAreReady ){ /* do something */ }`. FWIW. – Craig Tullis Apr 25 '14 at 14:47
  • @Craig yes it looks better. Some people prefer `condition == false` though and this is where I start having doubts :) `!` is more brief, but it's easier to miss in case of a condition like `if (!String.IsNullOrEmpty(settings.UserName))` – Konrad Morawski Apr 25 '14 at 14:53
  • @KonradMorawski, there's another argument in favor of the self-commenting test: `bool allDocumentsAreReady = (/*long list of conditions*/); if( ! allDocumentsAreReady ){ /* do something */ }` – Craig Tullis Apr 25 '14 at 15:05
  • 6
    I read somewhere (which of course I can't find now) that K&R only adopted the "opening bracket on the same line" approach to save space in the **printed** book. Having it on a separate line would have added many pages to their book and hence increased the cost of the book. – ChrisF Apr 26 '14 at 14:59
  • For me it kind've boils down to... b/c it's the default. Javascripts default places the opening bracket on the same line, so that's what I go with. For whatever reason JS functions using the brace on a newline method just seem odd and out of place to me, but in C# code it seems perfectly logical – CSharper Apr 29 '14 at 20:20
  • 3
    Here in Russia, we have a legend that Microsoft hires lots of programmers of the kind who are used to be paid by LoC (lines of code) number. They, obviously, were the ones who invented and popularized this coding convention. – Mints97 Feb 27 '15 at 19:45
  • I started programming in VBA and got used to having the conditional on a single line. Now whenever I install VS and start programming in C#, the first thing I do is change the above-mentioned setting. Admittedly, the fact that in Javascript there can be a difference in meaning if the braces are on a different line, cemented my preference for all brace languages. – Zev Spitz Mar 06 '16 at 23:25
  • @CSharper In Javascript there is a case where having the braces on another line affects the meaning of the code: `var fn = function() {return {a:1};};` will return an object, vs `var fn = function() {\n return\n {\na:1\n};\n };` which will return `undefined` because of automatic semicolon insertion. – Zev Spitz Mar 06 '16 at 23:30
  • 3
    @ZevSpitz You should have added a health warning to your comment - there are people who could be tempted to jump out of the window when reminded of semicolon insertion... :-) – SusanW Sep 26 '16 at 16:12
  • 3
    Well, there is actually a "reason" for Javascript to place the brace on the same line. Thanks to JS magics, the statement `return {` is not the same as the `return` and the `{` in different lines, because `return` without anything on the same line becomes `return;`... and the rest is ignored. This is only relevant when working with literal objects and not with functions, but for consistency it's better to stick to the single rule "brace on the same line". – bgusach Oct 07 '16 at 11:30
  • 1
    "Ugly" is highly subjective. What's ugly to you may be beautiful to others. – starmandeluxe Apr 24 '17 at 00:52
  • @starmandeluxe Quite right. Have edited it out. – Bob Tway Apr 24 '17 at 08:05
  • There is always a "historical reason" for everything (except radioactive decay). That is basically the definition of existence. "*Time is nature's way of preventing everything from happening at once.*" In Buddhism this is called Dependent Origination: everything happens for a reason, or actually: an infinite number of reasons. It is rarely useful to figure out why things happened, just come up with a better way and do it. Of course, "Those who do not learn from history are doomed to repeat it." So, maybe it is a good idea to ask why after all? *We now return you to your regular programming*. –  May 26 '17 at 14:00
  • Has anyone else ever wondered if a pre-filter for java and other brace-block languages that converted indents to the corresponding brace might be interesting? I have a hard time reading Python at first, with it's use of indents-rule-all, but it might make a very interesting variant on the java language (simply using indents), and could easily be managed by build scripts and addons to make the IDE complicit. Hmmm..... – tgm1024--Monica was mistreated Nov 23 '17 at 03:06
  • 1
    I realise this was closed over 5 years ago, but the crucial bit of info missing here that I think Matt was after is that a major reason opening curly brackets were put on separate lines was because of _conditional compilation_. People would use preprocessor directives to do lovely things like change method signatures _before_ the compiler got its hands on them, i.e. you might have two method signatures surrounded by `#if foo`, `#else`, and `#endif` lines. Having a curly bracket at the end of each method signature line would mean they don't match up with the single closing curly bracket. (1/2) – Amos M. Carpenter Jun 05 '19 at 07:06
  • 1
    (2/2) So as much as many people defend it and say it improves readability (I don't agree, I think you can get used to either way), it's a remnant of days gone by that has no practical use these days. – Amos M. Carpenter Jun 05 '19 at 07:08
  • 1
    @AmosM.Carpenter Yes, this is exactly the kind of detail I was interested in, thank you - couldn't care less about the stylistic flame war. Nowadays this question would be a better fit on retrocomputing I guess, but that didn't exist back then. – Bob Tway Jun 05 '19 at 08:06
  • 1
    No worries - I can't answer since the question's been closed, but figured I'd add the comment since no one else seems to have mentioned this fact. :-) – Amos M. Carpenter Jun 05 '19 at 08:08
  • because it’s superior – Dirk Boer Oct 17 '21 at 10:55

5 Answers5

84

The brace at the end of the line is the ancient K&R C standard, from Brian Kernighan and Dennis Ritchie's book The C Programming Language, which they published in 1978 after co-inventing the UNIX operating system and the C programming language (C was mostly designed by Ritchie, based on B, which another Bell employee Ken Thompson had adapted from the older BCPL programming language), at AT&T.

There used to be flame wars about "the one true brace style."

So Ritchie created the C language, and Kernighan wrote the first tutorial, when computer displays only showed a few lines of text. In fact, UNICS (later UNIX) development started on a DEC PDP-7, which used a typewriter, printer and paper tape for a user interface. UNIX and C were finished on the PDP-11, with 24-line text terminals. So vertical space was indeed at a premium. We all have slightly better displays and higher resolution printers today, right? I mean, I don't know about you, but I have three 24" 1080p displays in front of me right now. :-)

Also, so much of that little book The C Programming Language is code samples that putting the braces at the ends of the lines instead of on their own lines allegedly saved an appreciable amount of money on printing.

What is truly important is consistency throughout a project, or at least within a given source code file.

There are also scientific studies showing that the brace on its own line (indented to the same level as the code, in fact) improves code comprehension despite what people think they think of the aesthetics. It makes it very clear to the reader, visually and instinctively, which code runs in which context.

if( true )
    {
    // do some stuff
    }

C# has always supported evaluating a single command after a branching expression, by the way. In fact, that's the only thing it does, even now. Putting code in braces after a branching expression just makes that one command a goto (the compiler creates scope using jmp instructions). C++, Java, C# and JavaScript are all more or less based on C, with the same underlying parsing rules, for the most part. So in that sense, C# is not "based on Java."

Summing up, this is a bit of a religious/flame-war issue. But there are studies making it pretty clear that arranging code in blocks improves human comprehension. The compiler couldn't care less. But this is also related to the reason why I never put a line of code after a branch without braces--it's just too easy for me or another programmer to slap another line of code in there later and slip on the fact that it will not execute in the same context with the line right before or after it.

EDIT: Just go look at the Apple goto fail bug for a perfect example of this exact issue, which had very serious real world consequences.

if( true )
    doSomething();

becomes...

if( true )
    doSomething();
    doSomethingElse();

In this case, doSomethingElse() executes every time, regardless of the outcome of the test, but because it is indented to the same level as the doSomething() statement, it's easy to miss. This isn't really arguable; studies back this up. This is a big source of bugs introduced into source code during maintenance.

Still, I'll admit that JavaScript closure syntax looks a little silly with braces on their own lines...aesthetically. :-)

Craig Tullis
  • 1,935
  • 12
  • 10
  • 16
    The part about blocks in conditionals is slightly misleading. In C, the conditional always has a single statement, but a block (aka compound statement) [is a kind of statement](http://www.lysator.liu.se/c/ANSI-C-grammar-y.html#statement). C# follows this precedent. Anyway, conditional evaluation *always* implies some kind of conditional goto or branching instruction, due to the linear nature of all common instruction sets. A conditional without a block is not qualitatively different from a conditional with a block (except with regards to scoping). – amon Apr 25 '14 at 14:44
  • @amon: Thanks -- is there a clearer description you'd prefer to see? I was trying to convey the message that C# supporting a single command after a branch sans braces isn't something new, and that in fact it basically *always* does that--executes a single instruction (jmp) into that code block (or over it). – Craig Tullis Apr 25 '14 at 14:55
  • One quibble. Unix was never implemented on the DEC-10, only on the PDP-11 (and from there it was ported all over the place). – John R. Strohm Apr 25 '14 at 15:56
  • 1
    @JohnR.Strohm Wasn't the first UNIX implemented using assembler on the PDP-7? I seem to recall part of the impetus behind creating C was to implement UNIX in a "portable" language so that it *could* be ported easily to other machines. No argument here re: C and UNIX being developed on the 16-bit PDP-11, not the 36-bit PDP-10. Wasn't there a UNIX on the KL or KA-10 machines, though? Ah, well, I'll go edit my post. Thanks! :-) – Craig Tullis Apr 25 '14 at 16:15
  • 1
    @Craig, You're right. UNIX started on an unused PDP-7. As far as I know, and was able to check quickly, there was never a PDP-10 (PDP-6, KA10, KI10, KL10, or KS10) implementation of it. The only 36-bit UNIX I found mentioned anywhere was a Univac 1100, that ran as a guest OS under Exec. (And I find myself trying to avoid becoming violently ill at the mere mention of a Univac 110anything...) – John R. Strohm Apr 25 '14 at 17:18
  • 1
    @JohnR.Strohm, given what those machines cost back in the day, the fact that a PDP-7 was sitting around unused (taking up half a room and enough power to run 2 whole houses), *might* just be saying something about the PDP-7? (humor) Please accept my apologies for leading you down the Univac 110* path. :-) – Craig Tullis Apr 25 '14 at 17:23
  • 1
    I felt like I should confirm my power use guesstimate. It looks like the PDP-7 actually used about as much juice as an electric water heater, so definitely less than "2 whole houses." At the moment, there is a copy of the PDP-7 operating manual from 1965 [here](http://bitsavers.trailing-edge.com/pdf/dec/pdp7/F-75_PDP-7userHbk_Jun65.pdf), complete with octal to decimal conversion tables. And of course, it used as much juice as an electric water heater, presuming the water heater never shuts off. So maybe the "2 whole houses" estimate isn't actually so far off, after all. – Craig Tullis Apr 25 '14 at 17:46
  • 1
    @Craig If you could, would you mind adding links to full/abstract versions of the brace studies you mentioned? All I have ever seen with regards to brace styles are holy wars, and a quick search turned up nothing more informative than a listing of different styles :( – Dan Lyons Apr 25 '14 at 18:08
  • @DanLyons I'll have to go dig out my old copy of Code Complete by Steve McConnell this evening. But he listed some of these kinds of sources in that book. – Craig Tullis Apr 25 '14 at 19:31
  • 4
    @Craig, remember, this was at Bell Labs, back when Bell Labs was chartered to "do interesting stuff" that was not necessarily required to be practical for anything. Put smart people in a building, tell them to do some interesting research, move them out of what they do isn't "interesting", and, funny thing, INTERESTING stuff (like transistors and Unix) tends to pop out. DARPA had sort of the same focus, back in the beginning, and they funded a LOT of good work, in the name of basic research. – John R. Strohm Apr 25 '14 at 20:21
  • 2
    @Craig, EVERY programmer's manual from DEC included octal-decimal conversion tables *AND* a powers-of-2 table. It was part of their standard documentation "look and feel". (I have an old PDP-8 manual, I had a set of PDP-11 manuals, and I had a couple of DEC-10 manuals. They ALL had 'em.) (And I just can't bring myself to toss that PDP-8 manual.) – John R. Strohm Apr 25 '14 at 20:23
  • 1
    I'm surprised no-one has brought up Apple's `goto fail` bug yet... – Mark K Cowan Jun 21 '14 at 11:13
  • 1
    @MarkKCowan exactly, *precisely* the type of code design issue I was referencing when I mentioned always using braces. Fantastic example with serious real-world consequences. As far as I'm concerned, this whole issue is just inarguable. It doesn't make you a heroic or clever programmer to avoid using the braces. Leaving the braces out is tantamount to planting time bombs. Sometime down the road, 10 minutes from now or 2 years from now, the lack of braces will lead directly to the introduction of a serious bug. – Craig Tullis Jun 22 '14 at 05:46
  • 3
    @Craig: In the old Pascal/Delphi days, I usually avoided it for single-line blocks, as Pascal uses `begin` and `end` in place of braces, which makes such errors really hard to miss, and it also stricter regarding semicolon placement - but having spend 4 days last year debugging a problem in embedded C which ended up being due to someone's lack of brace placement..... I think there should be a compiler option which makes braces mandatory for control statements! – Mark K Cowan Jun 22 '14 at 11:16
  • @MarkKCowan, your comment about languages that use begin/end makes sense to me--I've also taken the same approach in the past with SQL, for instance. But yeah, with C-derived languages, I've also wished there was a compiler option to require the braces. I suppose you could write your own preprocessor that would do that, and slip a call to it into the head of your build chain. :-) – Craig Tullis Jul 03 '14 at 21:25
  • 2
    @Craig: Regarding the newlining in this question - having the open-brace on the same line as the control statement makes it really hard to "accidentally" detach the braced block from the statement e.g. by deleting the control statement or inserting a statement between it and the open brace line. I do wonder why the C# default is to newline the braces given it wastes a line and opens doors to new kinds of misread-syntax-related bugs... – Mark K Cowan Jul 03 '14 at 22:05
  • @MarkKCowan, why on earth would you insert a new statement between the control statement and the opening brace if it's on its own line? Seems a tiny bit silly, to me... :-) – Craig Tullis Jul 04 '14 at 21:32
  • @Craig: Generally you wouldn't, but then someone else might... also, when working quickly in VIM, a mis-press of the shift-key can cause that... – Mark K Cowan Jul 05 '14 at 07:24
  • 1
    those terminals had 24 lines, not 25. 24 lines by 80 columns was standard (matching the punched card), and then DEC came out with the VT100 with a 132 column mode to match the width of line printers. – kevin cline Aug 03 '14 at 18:18
  • Yep, my bad. Fixed. :) – Craig Tullis Aug 04 '14 at 16:15
  • 28
    Please provide references for "... scientific studies showing that the brace on its own line ... ". Without at least two references (otherwise it would be *study*, not *studies*), it's just shooting randomly into the air. – ErikE Jul 17 '15 at 19:01
  • 8
    @Craig, could you provide some clues how to find those research studies you mentioned? – Grzegorz Adam Kowalski Mar 09 '16 at 09:27
  • 11
    I second other commenters. Please provide references for "scientific studies" you mentioned. Absence of verifiable sources makes that particular argument lack credibility. – Luis Artola Aug 15 '17 at 00:25
  • 2
    The `goto fail` bug would have been caught by a whitespace linter, or by editors which allow you to reindent a block or an entire file automatically. I have such linters wired up at work so i can't even submit a commit if it fails linting. And in the latter case if i re-whitespace the entire file (which I do fairly frequently since the cost in terms of keystrokes to me is less than highlighting a block and reformatting only the block) i would have caught the error in as a diff in code that i hadn't touched. – lamont May 18 '18 at 23:59
  • 1
    It wouldn't have even needed to be caught if the original programmer had just used braces. It's so easy to use the braces, yet there is so much resistance... – Craig Tullis May 19 '18 at 07:40
  • 3
    The "Apple goto bug" isn't an argument to always use braces (it is actually about bad indentation). There are many ways to write bugs, blaming braces is just absurd (not to mention bloating the code vertically, which affects readability). – NateS Dec 03 '18 at 10:46
  • (Rolling eyes). Fine, argue. – Craig Tullis Dec 03 '18 at 16:54
  • @NateS my opinion is obviously that the braces IMPROVE readability. I see the extra vertical space as a distinct benefit for readability. If you have so much code in a procedure that the braces cause comprehension issues, then you have other problems. If there is just one short statement after the test, I will sometimes put the braces and the statement all on one line. Bottom line, yes, the Apple goto fail bug is an argument in favor of always using the braces. – Craig Tullis Dec 08 '18 at 20:46
  • @NateS relying on indentation for program flow is insanity. Yes, Python, I’m talking about you... – Craig Tullis Dec 08 '18 at 20:48
  • 1
    @Craig The code can be formatted well to avoid the "goto" bug without using braces. Your claim that braces are somehow involved is baseless. Poorly formatted code is the problem. – NateS Dec 09 '18 at 19:08
  • Relying on the formatting is an anti-pattern. Also, depending on who is writing the code, if you end up with long lines for tests, then you use word wrap to read without horizontal scrolling (another anti-pattern), your careful formatting is right out the window. No thanks, I’ll take the explicit control of the braces over the implied intent of the formatting. Someday you’ll encounter enough real-world problems along these lines that it will change your mind. – Craig Tullis Dec 09 '18 at 19:36
  • Besides which, the entire basis of the goto fail bug is that the fact that the line after the test was indented “properly“ led to a visual misinterpretation that the next indented line of code, added later, would execute with the first, only upon a true outcome. The point is that the “good” formatting leads to visual illusions that lead to bugs. Like I’ve said before, I think it’s unfortunate that there’s no option in the compilers to enforce use of the braces. – Craig Tullis Dec 09 '18 at 19:44
  • 2
    The `goto fail` bug doesn't seem like a great counter-example, because it's trivially avoidable by restricting "inline if bodies" to only ever being inline. I.e. `if (condition()) doSomething();` (one one line, and never one two lines). That's particularly common in guard conditions, something like `if (i == 0) return 0;` – Alexander Jun 22 '21 at 01:44
  • 2
    With modern versions of Xcode, it is actually very hard to enter the “goto fail” bug in your code as it is. If you typed it, or copied and pasted the first statement, it would automatically be aligned correctly. You’d have to manually insert spaces before the last line. – gnasher729 Jun 22 '21 at 06:50
  • So much resistance to simply putting the braces in…. ;-) – Craig Tullis Jun 25 '21 at 22:29
  • @Alexander or… just always use braces and completely eliminate the possibility in addition to making your code style completely consistent. – Craig Tullis Jun 25 '21 at 22:30
  • @Craig Yep, that's what my language of choice (Swift) does, at a language level (not just linting). It's a little wordy for early returns, like `if i == 0 { return 0 }`. But given that the parentheses on the condition are optional (convention is to omit them), I see why having the `{ }` might be necessary for unambiguously parse the condition from the body. – Alexander Jun 25 '21 at 22:35
  • @CraigTullis While I do prefer always using braces (except maybe rarely in one-liners where I'd put the condition and the statement on one line), repeatedly commenting "or you could just use braces" every time someone offers an alternative solution to avoiding the bug is not productive to the discussion at all. We heard it the first time, if you don't have anything new to add then perhaps just don't say anything at all. It seems like you can't stand not having the last word even *seven years later*. – alexia Dec 04 '21 at 09:58
  • @nyuszika7h I was just up late in the night, literally last night, fixing code containing cut and paste unnecessary and redundant logic and procedures that could not possibly complete successfully, removing hundreds of lines of code and fixing broken flow of execution resulting in bugs. I don’t honestly have a lot of patience for the argument that typing the braces is too much extra work. So yes, I’m going to repeat it and from my perspective it is excruciatingly useful: just use the damn braces. Make your intent crystal clear. Make it look like you actually *designed* the code. :) – Craig Tullis Dec 04 '21 at 16:04
  • The first edition of "The C Programming Language" had braces-right. But in the second edition they switched to newline braces. – KWallace May 03 '22 at 16:23
  • @KirbyL.Wallace Yeah, the braces on the same line saved lines, which save printing costs, and by the time the second edition rolled around and the fixed it (haha), it was too late. The habit had escaped the lab into the wild, and we are where we are. I personally and completely apologetically still prefer the Whitesmith indentation style (braces on their own lines, indented). – Craig Tullis May 04 '22 at 01:18
  • @CraigTullis, Actually, I was wrong. There's a third option some people call the "K&R Method". Wanting to verify that what I said was correct, I went and looked at my 2nd Edition, and sure enough, K&R used a MIXED approach. Braces on newlines for function and method declarations, but same line braces for statements and expressions within the them. That's just kinda weird, in my opinion. This guy pointed it out to me: https://jeremybytes.blogspot.com/2013/04/where-do-curly-braces-belong.html – KWallace May 04 '22 at 15:11
  • Right, what I was saying (in my original post, if I recall) is that putting the braces at the end of the line literally reduced the length of the book since it eliminated so many lines. I find the braces easily lost at the ends of the lines, and the code looks jumbled up. It's faster and cleaner to scan down a page while scrolling, rather than having to read long lines and even scroll sideways as has now become common with chained lambda expressions going out to column 387, which is just insanity. That code is simply unreadable. It's just as bad as out-of-control regular expressions. – Craig Tullis May 05 '22 at 04:55
42

The reason C# developers do it is because it is the default setting of the Visual Studio auto-formatter. While this setting can be changed, most people don’t, and thus all developers in a team have to go with the majority.

As for why this is the default in Visual Studio, I don’t know.

Timwi
  • 4,411
  • 29
  • 37
  • 18
    It's the default in Visual Studio because it was the generally-accepted coding style at Microsoft going way, way back, and in fact on at least some teams at Microsoft the style was not only braces on their own lines, but braces on their own lines and indented. So that is an option in Visual Studio, as well (I personally prefer it). – Craig Tullis Apr 25 '14 at 14:58
  • 35
  • 7
    @PreferenceBean Hmm. Personally I dislike the K&R style, because the brackets are just lost in noise at the ends of the lines and the text looks clumpy to me, which isn't just an aesthetic preference, but has an actual impact on readability/comprehension. I like vertical whitespace. It was a little different on 12" monitors with 24 lines of text back in the old days when vertical space was precious. – Craig Tullis Feb 14 '16 at 23:28
  • 16
    @Craig: That's no excuse for indenting the braces :P – Lightness Races in Orbit Feb 15 '16 at 00:20
  • @PreferenceBean The braces are indented for an entirely different reason. ;-) – Craig Tullis Feb 15 '16 at 04:50
  • 4
    @Craig To make Microsoft employees miserable? – Mateen Ulhaq Feb 29 '16 at 20:10
  • @MateenUlhaq Oh, I don't know, it never made *me* feel miserable there. – Craig Tullis Feb 29 '16 at 23:37
  • 2
    @Craig To me, the style of putting the opening brace on the same line and indenting the closing brace makes the code look like an outline: important line with subsidiary lines underneath it. This is *such* a familiar metaphor with anyone who knows how to read, that I would think it would be perfectly obvious. The code doesn't look any more 'clumpy' this way than text in a book does. Maybe we should change how books and outlines are written to make them less likely to be misread? –  May 26 '17 at 14:09
  • 2
    That's not a subjective analysis AT ALL. :) the brace at the end of the line can be lost in the noise, ESPECIALLY if it is at the end of a long or complex line of code. The brace on its own line is completely unambiguous. That's not at all subjective, either. :) – Craig Tullis May 26 '17 at 16:10
  • @nocomprende I just read this again and I'm not sure it came across as jovially as I meant. I can actually *kind of* see the appeal of what you're describing. – Craig Tullis Aug 04 '17 at 06:35
  • @Craig no, I thought it was funny, no worries. I would not stick a closing brace on the end of a line. In SQL I even put the semicolon on a line by itself. But the opening brace can't get any closer to what it belongs next to than on the same line, so the situation is not symmetrical. A little thought should reveal this, and so I am dumbstruck why everyone didn't come to the same conclusion? I guess they are just following the herd instead of thinking for themselves (irony). –  Aug 04 '17 at 12:07
26

As I hypothesized in this answer here - https://softwareengineering.stackexchange.com/a/159081/29029 - I suppose the decision to go with Allman's bracing could be a sign of Pascal heritage, given that Hejlsberg created Delphi before he designed C#. Same as Pascal case for method names.

Personally I believe in following the adage "in Rome do as Romans do". I use Allman's in C#, but K&R in Java. I am so used to it that switching the convention either way is jarring to me.

I believe that some convention diversity is actually beneficial for a "multilingual" developer as it helps to remember which language they're coding in at the moment and makes it easy to differentiate various habits. It's a mental equivalent of muscle memory, so to speak.

Konrad Morawski
  • 9,721
  • 4
  • 37
  • 58
  • 7
    +1 for the "multilanguage developer" line, actually. I seriously prefer braces on their own lines and indented. However, in work on, for example, ASP.NET (MVC) projects, I find that I like C# with the "right" style, and JavaScript with "JavaScript" style. That's a little tongue-in-cheek, but honestly part of it is that JavaScript's closure syntax is more attractive with the brace at the end of the line. So I'm as much a slave to aesthetics as anyone else... – Craig Tullis Apr 25 '14 at 15:10
  • PascalCase for method names was a standard at Microsoft a *long* time before Anders Hejlsberg left Borland to be a distinguished software engineer at Microsoft. – Craig Tullis Jun 30 '17 at 17:36
  • 2
    Interestingly, I use Allman for all brace-block languages. However, I am becoming increasingly interested in what a pre-processing conversion of indents to curly-brace blocks might look like in Java. The "java" code might be extremely clean looking, once I wrapped my pattern recognition mind around it. I think Python might actually have it right: There's really no _**great**_ reason for braces in a language. – tgm1024--Monica was mistreated Nov 23 '17 at 03:12
  • 1
    Using whitespace to control program flow is insanity. Python is popular these days, but this aspect of Python has been a little crazy since it first appeared. – Craig Tullis Dec 09 '18 at 19:48
  • 2
    @Craig Python fan here, trying to get something done in javascript. Looking at your other answer, and your edit about the `goto fail`, using the indent to control program flow is what humans naturally want to do, so what you see is what executes. If it's indented wrong it plain doesn't work. Having to decode what those braces mean, whether they actually reflect the indentation, is additional work over and above understanding the program. Indentation is redundant to braces, so why do programmers use it if the braces are useful? Deep nesting is unintelligible in any language. Jus' sayin'. – Neil_UK Dec 13 '18 at 06:15
  • 1
    You’re relying on human-invisible characters to control program flow. Tabs and spaces aren’t treated the same. It’s nuts. ;-) More to the point, though is that C-style languages are not Python and never will be, making it dangerous to approach them as if they are. Nor is there universal agreement on the issue, anyway. I completely agree with you re: deep nesting being a problem in any language—no argument here at all. The goto fail bug was not, however, a case of deep nesting. Your arguments are, in summary, making a strong case *for* including the braces every time. – Craig Tullis Dec 13 '18 at 08:02
  • 1
    I find, personally, that the braces make the behavior explicit and thus reduce cognitive load. – Craig Tullis Dec 13 '18 at 08:04
  • @CraigTullis Whitespace isn't human visible? Try reading a paragraph without any, I'm sure you will *see* the difference. – Turksarama Oct 18 '21 at 06:14
  • Try reading code that has intermingled tabs and spaces, but is whitespace-dependent. – Craig Tullis Oct 18 '21 at 16:17
  • @CraigTullis Python certainly doesn't let you do that, Haskell _does_, but if you actually use tabs the community will eviscerate you (I think the compiler should just not allow mixing within one file, like Python does). F# does not allow use of tabs at all. So really, that's not a real problem. – Turksarama Oct 18 '21 at 22:47
  • @Turksarama Of course Python lets you do that. I've seen it. It works with both tabs and spaces for indentation, and in a file that ends up mixing both it just fails. And the problem is that you can't visually see which lines have tabs and which have spaces, so it really sucks to debug. In a language with braces, the compiler couldn't care less. F# has exactly nothing at all to do with Python. – Craig Tullis Oct 19 '21 at 03:11
18

The convention that you associate with Java is the K&R style, or the "One true brace style," and originally comes from C. This page indent-style from the venerable Jargon File shows how old the distinction is.

I've always thought that the Allman style and its variants are a reflection of how the authors think about code, elevating the block delimiters to the level of keywords similar to how some languages use "begin" and "end" around blocks of code.

John Bickers
  • 773
  • 3
  • 7
  • I'm under the impression that these days OTBS (one true brace style) also implies never leaving out the braces after control statements, even for single lines of code. See the Apple goto fail bug. – Craig Tullis Sep 17 '17 at 16:42
-2

I assume it all started because the work is paid by number of code lines. (Now it is too late for fix). This is the most reasonable explanation to me.

Code is read by coders. I disagree that extra new lines will improve the code comprehension or make it more readable. Especially the cases with "else", "catch", "finally":

}
else
{

Code is not one line, no one is reading single line. The code is functions and function body is readable when it fits in one screen. Extra new lines are not helping. Opposite - it makes the code more un-readable.

The new line separate paragraphs in the books and the articles. The paragraphs are split by the story. That makes it more readable! (Not a simplified rules without meaning like - new line after 'if' and before 'then').

I like the comment from @Neil_UK:

...indent to control program flow is what humans naturally want to do...

...those braces ... actually reflect the indentation...

mmm
  • 11
  • 2