views:

1978

answers:

22

Of all the conventions out there for positioning braces in C++, C#, Java, etc., I don't think I've ever seen anyone try to propose something like this:

public void SomeMethod(int someInput, string someOtherInput) {
    if (someInput > 5) {
        var addedNumber = someInput + 5;
        var subtractedNumber = someInput - 5; }
    else {
        var addedNumber = someInput + 10;
        var subtractedNumber = someInput; } }

public void SomeOtherMethod(int someInput, string someOtherInput) {
    ... }

But why not? I'm sure it would take some getting used to, but I personally don't have any difficulty following what's going on here. I believe indentation is the dominant factor in being able to see how code is organized into blocks and sub-blocks. Braces are just visual noise to me. They are these ugly things that take up lines where I don't want them. Maybe I just feel that way because I was weened on basic (and later VB), but I just don't like braces taking up lines. If I want a gap between blocks, I can always add an empty line, but I don't like being forced to have gaps simply because the convention says the closing brace needs to be on its own line.

I made this a community wiki because I realize this is not a question with a defined answer. I'm just curious what people think. I know that no one does this currently (at least, not that I've seen), and I know that the auto-formatter in my IDE doesn't support it, but are there are any other solid reasons not to format code this way, assuming you are working with a modern IDE that color codes and auto-indents? Are there scenarios where it will become a readability nightmare? Better yet, are you aware of any research on this?

Update

Thanks to jim's point, I'm willing to concede that the closing bracket for a method block should be left-aligned. It clearly denotes that the method is complete, and eliminates the double brace (} }) at the end. Also, I always put gaps between methods, so the extra line caused by the brace doesn't bother me as much.

So, here's the updated code snippet:

public void SomeMethod(int someInput, string someOtherInput) {
    if (someInput > 5) {
        var addedNumber = someInput + 5;
        var subtractedNumber = someInput - 5; }
    else {
        var addedNumber = someInput + 10;
        var subtractedNumber = someInput; }
}

public void SomeOtherMethod(int someInput, string someOtherInput) {
    ...
}
+7  A: 

The convention you propose is common in languages like Lisp.

scribu
+6  A: 

This is just a matter of taste. The only thing is important - to use the same style across whole solution.

Yauheni Sivukha
+1  A: 

Dan,

Apart from the closing brace on the method, this looks fine to me as well.

I would prefer the method to have a definate visual 'end-point. the closing brace does just that.

jim
Jim, that's a good point. I always put gaps between methods anyway, so that wouldn't really bother me.
DanM
Personally, I would apply that same argument to all blocks.
glowcoder
+72  A: 

Personally that causes me to hesitate and start counting braces to see if they are all there and removes "at a glance" visual clues on the structure.

Mark Schultheiss
Reminds me of Lisp with all the braces next to each other.
Kimmo Puputti
+1  A: 

I suppose the real reason this is not common is that without the closing braces at the start of a line, it would be really hard to tell what "indent level" you were on at any particular line.

chaiguy
A: 

If you do as you're suggesting, you might as well just do Python-style blocks (indentation-defined), since the braces aren't really doing anything except adding noise.

Brendan Long
+1  A: 

For me personally it's important that each operation, whenever possible, takes a separate line. Not if (i < 0) {i = 1} or int i = 0; double x = 1;, for example. That's why I don't like }}} noise at the end: if-else construction (all parts of it) should be visually separate from assignments and other stuff.

Not to mention, I like to copy-paste full lines of code and 'i = 0;}}}' would be a problem in this case :)

But that's just my personal preference and I think your convention is generally valid.

Nikita Rybak
+2  A: 

I think it's very interesting that the braces are visual noise to you, particularly because you come from a VB background. To me, the noise in VB is much higher. I'd much rather see braces than End Sub, End Function, End If, Next, etc.

I do see your point however. I've felt it's better to move to another language that's more Lisp like if the C style or Basic style is too noisy, such as Python, Ruby, etc. Though you might not like Clojure's very extensive use of parenthesis. :)

Jeff Schumacher
+15  A: 

A reason not to is that you can't always move to the end of a line, press enter, and start typing a new line of code. You have to park the cursor to the left of the proper brace first.

Daniel Newby
Not something I've thought of before, but a good point. I can readily see a programmer not accostomed to this convention carelessly doing what you describe, or inserting a blank line under the last line of a block in some other way, and then getting seemingly-mysterious bugs.
Jay
+40  A: 

I think this makes it harder to grab a "chunk" of code. For instance if you have multiple levels of if statements and decide to refactor some of it into a function it's a little harder to grab just the right number of end brackets. Where as having the end brackets on separate lines makes that task easier. Just a small issue really, but as far as readability it's true that the indentation is really what's important.

juharr
+1. Great point, and great answer. Thanks.
DanM
+4  A: 

While it is indeed possible to figure out the structure of the code from your example, the main issue is not the possibility to make out the structure of the code, but rather the immediate readability of the code. For the readability of the code vertical blank spacing is as important than horizontal one.

In your example, the condition in the if is "glued" to the code inside the true branch. The header of the function (parameter list) is "glued" to the implementation as well. This is poor readability already. It is very difficult to extract the beginning and the end of the logically continuous section of the code in your original example. And if the condition becomes multi-line, the code will get even harder to read than it is already.

In order to make the code readable, the elements of different nature have to be separated by a blank line

public void SomeMethod(int someInput, string someOtherInput) 
{ /* Comment here */
    if (someInput > 5) 
    { /* Comment here */
        var addedNumber = someInput + 5;
        var subtractedNumber = someInput - 5; 
    }
    else 
    { /* Comment here */
        var addedNumber = someInput + 10;
        var subtractedNumber = someInput; 
    } 
}

Additionally, the extra blank line provides a natural space for writing a comment (if one is necessary).

AndreyT
python code is pretty readable even though the lines in "if" constructs, etc., are usually adjacent.
Amnon
Sorry, but personally I hate this style. I think that by placing the opening brace on a new line totally detaches the code block from the header (method header, or if statement or whatever) and I feel that this makes it more difficult to read. Especially if there are no comments placed where you have indicated then it just seems like there is a lot of white space. At my work we have had many dicussions about code style and everyone has their own preferences, and this is just mine, so no offence intended. I guess the key is just to be consistent.
DaveJohnston
+1 I think this formatting style ties in well with small methods, classes (Single responsibility Principle) - however if the methods\classes are not small then it looses it's effectiveness
David Relihan
+2  A: 

I find it considerably more readable and clearlier arranged when the method signature is not followed by an opening bracket.

It's still only a matter of taste whether to write the opening bracket in a seperate line or not - anyway, I have never seen anyone not setting the closing bracket in a seperate one.

Marius Schulz
+2  A: 

Braces exist purely as a lexical element to aid the compiler. In most cases as above they are used to create a statement block that is uniform to all statement blocks. Thus their main purpose is to provide you with as much control over how your blocks are formatted as possible. Given this I would recommend using them however you like and that the form you present is fairly easy to read.

However would note that while for simple statements I really like how all the closing braces end on the same line. However, In the example below consider how this looks with a large number of nested statements.

public void SomeMethod(int someInput, string someOtherInput) {
    if (someInput > 5) {
        var addedNumber = someInput + 5;
        var subtractedNumber = someInput - 5; }
    else {
        if(1==1) {
            if(1==1) {
                if(1==1) {
                    if(1==1) {
                       var addedNumber = someInput + 10;
                       var subtractedNumber = someInput;  } } } } } }

As opposed the standard method where closing braces just line up vertically. As you can see below you can just see where each block ends. Where as with your method you end up counting closing braces.

public void SomeMethod(int someInput, string someOtherInput) 
{
    if (someInput > 5) 
    {
        var addedNumber = someInput + 5;
        var subtractedNumber = someInput - 5; 
    }
    else 
    {
        if(1==1)
        {
            if(1==1)
            {
                if(1==1)
                {
                    if(1==1)
                    {
                       var addedNumber = someInput + 10;
                       var subtractedNumber = someInput; 
                    }
                }
            }
        }
    } 
}

A main thing to consider when doing changes to the common formatting of things is that other developers will see your code and having a common format for the code is very helpful.

Jonathan Park
Of course, if you only have one statement, you can leave out the braces altogether in Java. And I'm pretty sure that 1=1 isn't legal at all.
Vuntic
Furthermore, if later you need to add a new line of code after one of the inner blocks, it is simple to do so correctly in the latter style while doing so in the former style requires counting braces.
TheUndeadFish
+1. Good point, Jonathan. I made a small edit to your first example, though.
DanM
@Vuntic: Fixed the 1=1.
Jonathan Park
+1  A: 

I have to say that this is an issue that I encountered many times in the various projects I worked on. We have developers from various backgrounds - C, C++, Java, C#, Cobol and even developers that started their way writing Shell scripts.

Some take the conventions they were taught at their university. Some take the conventions of their team and some define their own.

When I first started I was used to the Egyptian brackets but since I joined a team working on C# - we immediately adopted the Microsoft convention:

public void myMethod()
{
  ...
}

After migrating myself to Java, I am still using the old ways since I find it the most readable. To me - any other format breaks the indentation and is not very readable. In my current project - there is almost a unanimous agreement that this is the best practice.

The way I see it (and I'm sure people will correct me if I'm wrong): People who write code like you suggested - have no problem reading code the way I write it. But people who write code the way I write it - have difficulty reading code the way you write it. --> This is my feeling, I'll be happy to get comments about it.

RonK
RonK, you may be right, but it also might just be that the way I wrote it is completely unfamiliar (even to me :)).
DanM
+1  A: 

After this line this line

        var subtractedNumber = someInput; } }

in your example it is not obvious that the next line should be out-dented twice to lign up correctly. Looks like a recipe for an unmaintainable and confusing mess.

Jonathan Park's answer includes an example where the out-dent would need to be 6 levels, and you can only tell that by counting the }'s. It is extraordinarily error prone without direct IDE support; and who's going to write formatter to cater to a very minority taste? You should not have to think about indenting, it should be intuitive.

Clifford
+1  A: 

For some reason, I just can't read that code. Which is very strange, as I program in python very often. So the idea of indentation deciding my if/else blocks is something that I'm familiar with (and I like it better than using braces personally), but I'm suddenly uncomfortable with it when you add braces.

I guess it's because with Python, what I see is what happens. While with C++, C#, and Java, the indentation can lie because the compiler uses the braces. So I just don't trust the indentation when I'm coding in those languages and I can't properly read the braces because they don't match the indentation level.

On the other hand, I'm fine with doing trailing end-paren's in Lisp variants... now I'm just confused.

So the only real answer I can give is because convention says to do it another way. When you enter another programming language, you enter another culture and you change your coding style. In Lisp, what you did up there is fine. In Python, there's only one way to end blocks. In C and similar languages, you use curly braces and spaces to specify indentation.

Jonathan Sternberg
Every programmed in Lisp without a parenthesis-aware editor? I have. It was very, very painful. On the other hand, I've written large amounts of C and C++ code without using automatic brace matching much, because it isn't as necessary.
David Thornley
I actually have. For larger functions, even with parenthesis-aware editors, it becomes impossible to read it. The syntax is really nice for writing code, but it's really hard for reading code.
Jonathan Sternberg
+1  A: 

One example where this is confusing:

Case 1:

if (someInput > 5) {
    var addedNumber = someInput + 5;
    var subtractedNumber = someInput - 5; }

Case 2:

if (someInput > 5) {
    var addedNumber = someInput + 5; }
    var subtractedNumber = someInput - 5; 

Both snippets look very similar although they do different things. It is easy not to see that in case 2 the second line is incorrectly indented. The compiler will not tell you this and you are required to run a code formatter to get this obvious.

By putting the braces on separate lines it is much easier to spot what is going on here and to actually see that there is a formatting error:

Case 2 with braces on separate lines:

if (someInput > 5) 
{
    var addedNumber = someInput + 5; 
}
    var subtractedNumber = someInput - 5; 

Beside that point: Stick to the way of indenting that is the most common in your programming language as you will usually write code that needs to be understood by others.

0xA3
1. I'm confused. Case 2 doesn't have any braces at all, and in Case 1, the braces are correct for the indenting you've shown. If you auto-format this code, the second `var` in case 2 will be aligned with the `if`. 2. Regarding your last paragraph, I agree that we should follow standards/conventions, but that doesn't mean that standards/conventions shouldn't be allowed to evolve if newer and better ways of doing things are discovered (Hungarian notation, anyone?). (And I'm not saying the inline-brace idea is a better way of doing things...it's just a curiosity for now.)
DanM
@DanM: Regarding 1: Exactly that was my point. The code snippets both look similar but do different things. Relying on an IDE feature such as code-formatting is not a good idea because it always requires that you use an IDE and that the current compilation unit is syntactically correct which is not guaranteed to be the case then the auto-formatting command is applied. Regarding 2: I tried to make clear with my sample why I think the proposed formatting is actually not a good idea.
0xA3
1. Okay, I'm with you that the two segments look similar but do different things, but clearly, Case 2 is a formatting *error*. And this error can cause nearly as much confusion whether you normally place braces on separate lines or not. As I said in my original question, indenting is a *much* more powerful visual cue than braces. 2. After reading all the responses, you are probably right that there are good reasons to put closing braces on a separate line, but I still believe conventions can and should change over time if better ideas come around.
DanM
@DanM: See my updated example to clarify my point.
0xA3
Much clearer, now, thanks. And +1 for putting up with me giving you a hard time :)
DanM
A: 

Since the compiler won't error in this scenario (like python), you have the potential for intent and syntax to become out of sync. This makes the code hard to read and maintain, and error prone.

It's like naming a function that adds something a(). You can do it for shorthand, but it'll cause more problems later than it solves now.

seren23
A: 

See Sutter and Alexandrescu's "Rule 0: Don't sweat the small stuff", which applies to a variety of languages, despite its inclusion in their book "C++ Coding Standards." Brace placement is one of the examples.

Rule 0 appeared as an excerpt in Dr. Dobbs: http://www.drdobbs.com/184401863

Andy Thomas-Cramer
Sutter and Alexandrescu don't know me at all. I *live* to sweat the small stuff :)
DanM
+1  A: 

My preference is "the opposite" - takes up more lines, but I think this way is more readable (not "hiding" the start-bracket way out on the right (maybe even wrapped))

And no useless semicolons!

public void SomeMethod(int someInput, string someOtherInput) 
    {
    if (someInput > 5) 
        {
        var addedNumber = someInput + 5
        var subtractedNumber = someInput - 5
        }
    else 
        {
        var addedNumber = someInput + 10
        var subtractedNumber = someInput
        } 
    }
T4NK3R
Useless semicolons? How in the hell would you make a compressed javascript?
BrunoLM
I wouldn't : )- I rely on cashing instead...
T4NK3R
This method is the most logical; the braces are lined up with the thing they surround. Unfortunately, I haven't found any workplace that uses this method. Most of them keep the braces one level left of this, which I've gotten used to. (As for having opening braces at the end of the line, I haven't worked in a single C# shop that does that. I wouldn't want to work in such a place; if braces have meaning, then it's foolish to put them in a place where they're easily missed.)
Kyralessa
A: 

I recommend programming with a team. If you're already doing so, try it longer. It took me years to get over petty differences in programming styles, but it's a fact of life with C/C++. Programming in a team environment is as much about communicating with other people as it is about communicating with the machine, and even people speaking the same language have different dialects, different kinds of expressions they prefer over others, etc. Learn them and get used to dealing with them even if you don't like them as much: you're not supposed to - no one ever formats code exactly the same way unless the language requires it (ex: Python).

Apologies for getting preachy but this kind of formatting style is really a trivial thing. If you like it, you can feel free to use it but you should get used to other, more common styles if you plan to read other people's code. Don't go reformatting other people's code if you work in a team unless you want to make people really upset, even if you are sure your style is superior.

BTW, I had a co-worker who used this style. It is basically like a combination of Pico style and K&R style. I didn't mind that so much but what drove me crazy was that she used 2-space indentations. Personally I wish everyone just used Allman style like me; everything lines up that way which is why I like it, but to each his own.

A: 

As a Lisp programmer by choice who had to do Java programming for work once, I have tried this. You can write programs this way, and it does save a lot of lines. Unfortunately, there were 2 things working against me:

  1. Java's syntax is much more complex. In Lisp, a line always ends with ))) or so -- the only thing left to do is make sure you have the right number of close-parens (which editors are great at). In Java and C#, lines often end with some mess like )};}));, so you can't just hit ) until the opening paren highlights. In Lisp I don't really think about the parse tree, because it's trivial, while in Java/C# I actually have to think about the structure of the entire block just to finish it. I suppose the editor could help here, but:

  2. Editors don't support it. (Yes, this is largely just a consequence of #1.) In Emacs, anyway, it's really easy to do operations on sexps, and every editor with any amount of Lisp support can do such things, because it's generally really easy to implement. You can move, select, compile, etc., sexps, and there's pretty much one way to indent and the editors are great at that, too. OTOH, selecting an expression in Java/C# is a lot harder -- I'm not sure what that would even mean, in a lot of cases.

I think it's great to try things like this, but it's also great to recognize when they don't work so you can drop them. For better or worse, a coding standard has to take into account language syntax, and Java was designed (intentionally or not) for C-like indentation/bracing.

(P.S., and no, I used Python for a while, and it drives me crazy. Go find the nearest Python code and tell me what "select this sexp" means. Its syntax is even more editor-hostile than Java/C#'s. They're very complex but at least you could in theory write something to move strangely-indented blocks around. In Python most of the time I have to resort to moving by word/char/line.)

Ken