Coding Style: Braces

Pages: 123
I know this topic has been debated over and over and it's largely a personal preference... but I just thought of something on the topic that I've never thought of before, and felt like sharing.

Duoas linked this in another thread:

http://www.joelonsoftware.com/articles/Wrong.html

I've seen this before... but I skimmed it again until I saw this part:


Even more subtle:

1
2
    if (i != 0)
        foo(i);


In this case the code is 100% correct; it conforms to most coding conventions and there’s nothing wrong with it, but the fact that the single-statement body of the ifstatement is not enclosed in braces may be bugging you, because you might be thinking in the back of your head, gosh, somebody might insert another line of code there

1
2
3
    if (i != 0)
        bar(i);
        foo(i);


… and forget to add the braces,



Do people actually DO that? By which I mean... add additional lines to clearly single-line if statements without adding braces? Apart from having to be practically blind... you also would have to manually tab over because the IDE wouldn't tab properly (or rather... it would tab properly which would be an indication that you're messing up).

I have always hated the "always use braces even for single-line if statements" rule. I've worked in places where it was a rule and it always irritated me. It adds a lot of unnecessary clutter, especially in code that has a lot of such conditionals.

I can't think of a single time in my life where I've made the mistake of adding a new line to an if block and thinking there were braces when there weren't. Even when I was a noob I never made that mistake. So why are people so worried about it?


Well I think I know why. I suspect it's because of this stupid brace style:

1
2
3
if( something ){
    thisIsStupid();
}


It's not immediately obvious that the brace exists because it's on the same line as the conditional. Someone used to that style might get confused:

1
2
3
4
5
if( foo )          // <- this 
    biff();

if( bar ){         // <- looks similar to this
    blam();


On the other hand... if you are a sane person and put the brace on a newline, it much more clear:

1
2
3
4
5
6
if( foo )     // <- now this looks totally different
    biff();

if( bar )     // <- from this
{            
    blam();


I have used the latter style for pretty much my entire life (except for a time when I was a noob and tried to cram everything on as few lines as possible because I was dumb)... which I really feel is a big part of the reason why I never made the mistake mentioned in Duoas' linked article.



EDIT:

To elaborate further... the article is talking about coding style to make wrong code look wrong... but then shows this as an example of why you should do that:

1
2
3
    if (i != 0)
        bar(i);
        foo(i);


When that code already does clearly look wrong. This is a glaring indentation error in my brain and it's almost impossible for me to miss the mistake.
Last edited on
It doesn't look wrong to Python programmers.

I always make the opening and closing braces on their own lines because I like the way they visually line up vertically on the screen.
Last edited on
Good point.

Then again neither does this:

1
2
3
if something:
        foo()  # spaces
	bar()  # tab 


Python is stupid.
Do people actually DO that? By which I mean... add additional lines to clearly single-line if statements without adding braces? Apart from having to be practically blind... you also would have to manually tab over because the IDE wouldn't tab properly (or rather... it would tab properly which would be an indication that you're messing up).


I always preferred no braces, but I changed to using braces after reading a long list of comments about the goto fail bug of 2012, where not using braces was heavily criticized and blamed for the bug. Whatever the case, if this bug was not intentionally added, it was a major boneheaded mistake to miss in a review or test. Nevertheless, it is an example by a professional working on some of the most security critical code out there.

I cannot see how this style could be error prone. Stupid looking to some? Yes. Stupid? Arguably the smartest of all the styles if you evaluate rationally.
1
2
3
if( something ){
    thisIsStupid();
}
Last edited on
i agree with Disch. Anyone even remotely familiar with C++ should see the glaring error.

That said, there is an apparently large cohort of programmers out there who make that exact error all the time. Coding standards, then, have to be written to the lowest common denominator, which I imagine is often enough an observed issue in development teams either past or present.

I personally consider it a beginner's issue, and see it in posts here on the forum regularly enough.

I also despise the trailing brace styles, but alas, that came from K&R.
What really gets me is when a closing brace is packed at the end of the last statement in a block.
1
2
3
if(something) {
    noticeTheSpace()
}


I've never made the mistake Disch described in his OP
@NoXzema:

That article dodges the point:

That article wrote:

"You cannot safely mix tabs and spaces in Python."

That's right, and you don't want that. To be exact, you cannot safely mix tabs and spaces in C either: While it doesn't make a difference to the compiler, it can make a big difference to humans looking at the code.


Comparing the danger of mixing tab/spaces in Python to the danger of it in C is laughable.

My last programming job had a large Python codebase both in the code and in the system-level tests. In the 2 years I was there, I can recall several times (at least 5) where incorrect mixing of tabs/spaces led to bugs that not only made it passed review, but also passed testing.

Usually it was a bug in the test itself, causing the test not to run because it wasn't part of the class. IE, something like this:

1
2
3
4
5
6
7
8
#eveything uses spaces
class TestClass:

        def test_foo(self):
                foobar()

	def test_bar(self):  # someone added this with tabs
		foobarbaz()


There's no way to visually see this error unless you enable tab/space viewing in your editor (which is hideous)... or you have tabs in your editor set to a different value than the number of spaces in code.

Again... this happened multiple times... where people thought this test was running but it actually wasn't. And thus broken code was added to the repo.





Python lovers like to gloss over this... but it really is a serious problem with the language, and if you ask me, a horrendous design flub on the part of the language designers.
Last edited on
made it [past] review, but also passed testing.


I am ambivalent about Python's indentation=block. Personally, I kind of like it. The problem comes with all the idiots who use tabs.

Yep. I said it. Just don't use tabs in source code. Get yourself an intelligent editor that can indent/'tab' properly with spaces. And threaten people who use tabs when programming in Python with termination for being idiotic. (And make sure to install a filter on the Python 'build' environment/VCS that outright rejects any code with HTs in it.)

My too-many cents.
@Duoas:

I actually wrote "past" first out of habit, and I frequently confuse past/passed... However I went back and changed it to passed because is seemed grammatically accurate.

Looking into it, you are correct. The form of the word there should be "past". Whoops. Freaking English.


The problem comes with all the idiots who use tabs.


I agree. Unfortunately it's the default for most common editors. Notepad++ was typical at the job in question, and not everybody went in and change the settings to replace tabs with spaces.
closed account (EwCjE3v7)
I always use no braces for one line and have not rarely forgot the braces if im adding another line
LOL, I'm just a Grammar Nazi.
(I wasn't trying to give you a hard time, just a little push with something that gets a lot of people.)

On an unrelated note (not directed at you), a fun video I really enjoyed when it came out: http://www.youtube.com/watch?v=8Gv0H-vPoDc
It was such a vindication for me! (And now I don't feel bad when people try to give me a hard time about wording things correctly.)



I hate having to use small words and short thoughts with people all the time so they don't go "wut?" at me.


[edit] LOL! The next place I went after posting this was xkcd.
http://xkcd.com/1429
:O)
Last edited on
I think beginners should be taught to use braces because it creates discipline. It is one of the first times a programmer will have a choice about code style and the lesson should not be to take the shortcut.

I personally would just write the whole thing on one line:
if ( something ) doThis();

If someone comes along and wants to add a line, this is clearly wrong:
if ( something ) doThis(); doThat();

And while that person is adding the line breaks, he/she will know to add braces.

I also think about the future of the code. What if something that starts out as:
if ( something ) doThis();

Might evolve into:
1
2
3
4
5
6
if ( something )
  doThis();
else if ( somethine_else )
  doThat();
else
  doOther();


Then I realize that two things needed to happen in the else if, things get ugly:
1
2
3
4
5
6
7
8
9
if ( something )
  doThis();
else if ( somethine_else )
{
  doThat();
  andThis();
}
else
  doOther();


I should have just used braces from the start:
1
2
3
4
if ( something )
{
  doThis();
}
Last edited on
Can we avoid the tab/space flamebait? I actually prefer tabs over spaces, and saying to "threaten people who use tabs when programming" isn't exactly open-minded. EDIT: Oh, I didn't realize you were talking about Python in specific. Nevermind.
Last edited on
Issues like that is why all commited code should now be run through auto-identer. Only complaints are from people who likes to do this:
1
2
3
4
5
6
7
       if(  SomeVar1 = const2 ) {
    dosomething1()
} else if ( SomeVar10 = const1 ) {
    dosomething2();
} else if (   Variab1 = const3 ) {
    dosomething3()
}
Last edited on
Bi-directional auto-indent shouldn't be too terribly difficult, especially not with Git. Git already manages bi-directional line-ending changes for you, surely you can code a plugin to commit code with one indentation style but keep the files on disk as another.
There are times when auto-indentation and one-line brace usage are a bad idea, which is why I'm not a fan of either of them.
Yes, if you're going to omit the brackets then leave the statement on the same line as the conditional. If somebody screws that up, they deserve to be fired. Out of a cannon. Into the Sun.

P.S. If you use tabs instead of spaces you're worse than Obamanazis taking away all of our freedom guns and forcing communist health care onto the population.
ResidentBiscuit wrote:
If you use tabs instead of spaces you're worse than Obamanazis taking away all of our freedom guns and forcing communist health care onto the population.
That's some pretty closed-minded thinking there. Instead of arguing just throw me a couple links pertaining to tabs vs spaces in C++ and I'll be out of your way.
Last edited on
If i use no braces it is exclusively because everything fits on one line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if(one thing) OneThing();
else          AnotherThing();

// otherwise it doesn't fit on one line:

if(one thing)
{
    Some(really, long, line, that, might, not, fit, onto, a, single, line,
         so, it, is, cropped, onto, another, line, anyway);
}
else 
{
    AnotherThing(); // this on one line, with no braces, just doesn't look right anymore
}


LB wrote:
That's some pretty closed-minded thinking there. Instead of arguing just throw me a couple links pertaining to tabs vs spaces in C++ and I'll be out of your way.

Just go on github, go to any project that uses tabs, look through the source and you'll see the 1000s of formatting errors because github doesn't use tab = 4 spaces. Best be on your way.
Last edited on
Pages: 123