Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


Poll: if () with single inner statement. What do you do? What do you do?


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
47 replies to this topic

Poll: Single-state if's (89 member(s) have cast votes)

if () has a single statement. Do you still use braces?

  1. Extra work? No way! (12 votes [13.48%])

    Percentage of vote: 13.48%

  2. Sometimes… (26 votes [29.21%])

    Percentage of vote: 29.21%

  3. Always! (51 votes [57.30%])

    Percentage of vote: 57.30%

Vote Guests cannot vote

#1 L. Spiro   Crossbones+   -  Reputation: 14014

Like
2Likes
Like

Posted 13 November 2011 - 11:32 PM

I am running around someone else's code right now.
This person never adds braces if they are not necessary.

if ( dog > you )
	run();
else
	pet();

As I scan the code I find this tripping me up often. In debugging the code I was trying to find out what code does what and I changed this:
if ( doit )
	okay();
for ( ; ; )
{
	blah();
}
to this:
if ( doit )
	//okay();
for ( ; ; )
{
	blah();
}

And hilarity did not ensue.


I always use braces no matter what. I have even had people leaning over my shoulder back in school days saying, "You don't need a brace there you know."
"Yes, I know."
"Then why do you put it there?"
"Why not?"

Back then, to me it was the same as being lazy for the sake of being lazy. But these days I have actual reasons.
However, I would like to hear from everyone else instead. Someone will probably post all of my reasons anyway.


So, what is your policy and why?
Do you always add the braces, never add the braces, or sometimes add the braces?


L. Spiro


It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

Sponsor:

#2 wqking   Members   -  Reputation: 756

Like
-1Likes
Like

Posted 13 November 2011 - 11:37 PM

Always!

Extra work but clean code, and no error-prone

http://www.cpgf.org/
cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.
v1.5.5 was released. Now supports tween and timeline for ease animation.


#3 Cornstalks   Crossbones+   -  Reputation: 6991

Like
0Likes
Like

Posted 13 November 2011 - 11:41 PM

I always do. I shudder when one doesn't. The reasons range from consistency to stopping that evil bug we've all experienced. The only time I don't shudder is when the if and its statement are on the same line, like

if (someBool) x += 2;

Or

if (someBool) x += 2; else x -= 4;

I never do it like that, but if someone isn't going to use braces I'd prefer they did it that way.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#4 ApochPiQ   Moderators   -  Reputation: 16073

Like
2Likes
Like

Posted 13 November 2011 - 11:45 PM

Part of coding discipline in a braces-optional language is to learn to inject them as needed when working with code written by someone who stylistically doesn't always use them.

#5 Hodgman   Moderators   -  Reputation: 31100

Like
2Likes
Like

Posted 13 November 2011 - 11:51 PM

I understand all of the arguments for inserting these "unnecessary" braces, and why it's a good idea to always put them in anyway... but code with extra braces just looks very 'messy' to my eye, likewise with code where every second line is blank "to space things out".

e.g. in your "dog > you" example, 4 lines of code suddenly becomes 8 lines of code when adhering to this style. I'd prefer the concise code and trust in my ability to understand the ramifications of changing those 4 lines. After all, you spend more time reading code than you do writing code.

I don't have a strict style on this. I just write it in whichever style seems most readable at the time. In some rare cases, it even turns out that Cornstalks' example of not even inserting new-lines is the most readable style (IMHO)! e.g. in this made-up example of making all components of a vec4 positive, I'd probably go with the first option, because it gets the purpose off of the screen and into my brain the quickest:[source lang=cpp]if( vec.x < 0 ) vec.x *= -1;if( vec.y < 0 ) vec.y *= -1;if( vec.z < 0 ) vec.z *= -1;if( vec.w < 0 ) vec.w *= -1;//vsif( vec.x < 0 ){ vec.x *= -1;}if( vec.y < 0 ){ vec.y *= -1;}if( vec.z < 0 ){ vec.z *= -1;}if( vec.w < 0 ){ vec.w *= -1;}// vsfor( int i = 0; i != 4; ++i ){ float value = vec[i]; if( value < 0 ) { vec[i] = -value; }}[/source]

#6 SimonForsman   Crossbones+   -  Reputation: 6175

Like
0Likes
Like

Posted 14 November 2011 - 01:11 AM

If its kept on a single line, i.e:

if (x<y) doSomething(); else doSomethingElse();
then i can skip the braces, but if its more like:
if (long and fairly complex expression that makes this line really really long)
    	someFunctionWithAWholeBunchOfParameters(x,y,z,y,window,monkey,etc);

Then i'd add braces just to make things clear and avoid future mistakes.
I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

#7 taz0010   Members   -  Reputation: 275

Like
1Likes
Like

Posted 14 November 2011 - 02:05 AM

I don't use { } unless I have to. Space is a valuable commodity and the last thing I want is for a function to scroll off the page because half of the lines are comprised of single braces. I rarely put code on the same line as the conditional though. I find that it makes the code a little harder to read, while omitting the braces and always - always indenting, provides more than enough clarity.

But I love binary IF as it's amazing for writing concise code. A somewhat contrived example, but;

if(a > b)
{
  x = c;
}
else
{
  x = d;
}

vs:

x = (a > b ? c : d);

8 lines vs 1...




#8 rip-off   Moderators   -  Reputation: 8518

Like
0Likes
Like

Posted 14 November 2011 - 03:40 AM

I'd always include braces, unless I was following a coding convention which required single statement conditional/loop blocks to be on the same line as the predicate. At work we put the braces on the same line as the predicate, which converses space but I find it makes the code a denser and harder to read. But as a result I'm quite used to switching between bracing styles, I'm sure I'd adapt quickly to omitting or adding braces for single lines of code.

If I was involved in drafting a coding convention, and the majority wanted single-line statements to be allowed, I'd still argue that braces should be included too. So using Hodgman's example:
if( vec.x < 0 ) { vec.x *= -1; }
if( vec.y < 0 ) { vec.y *= -1; }
if( vec.z < 0 ) { vec.z *= -1; } 
if( vec.w < 0 ) { vec.w *= -1; }

It is slightly annoying that it is impossible to be totally consistent with such a convention - it cannot be applied to function bodies for example, only if statements and loops.

As for why, I think it makes the code easier to edit. You don't have to think about adding/removing braces when adding or removing statements from blocks.

I do love the ternary conditional operator, while some people prefer the much more longhand full if/else block.

#9 NightCreature83   Crossbones+   -  Reputation: 2934

Like
0Likes
Like

Posted 14 November 2011 - 05:05 AM

I always add them and it is more due to the fact I have been bitten by my own code not having them. I find it is not the commenting out that gets me when there are no braces it is extending the if with more statements that gets me.

So since then I have been adding them as it keeps the blocks clearer and easier to extend. I curently work with a code base that has {} arround normal code in functions just so people can reuse variables.
Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#10 L. Spiro   Crossbones+   -  Reputation: 14014

Like
2Likes
Like

Posted 14 November 2011 - 05:19 AM

I also put the braces on the same lines as the if and friends, so spacing is not a problem.

if ( dog > you ) {
	run();
}
else {
	pet();
}
It did increase but only by 2 lines. I would take that trade-off any day over the risks that come with omitting the braces.

Also I am willing to put them on 1 line as long as the inside of the if is extremely short and simple. Usually these are returns.
if ( dog > you ) { run(); }
else { pet(); }
This is not a particularly good example though because the calls to run() and pet() do not align well. Usually it is more like:
if ( doBad ) { return false; }
if ( doGood ) { return false; }
if ( always ) { return false; }





Aside from that, I am finding it a bit hard to skim his code. I am used to seeing this:
myFunc( parm0, parm1, parm2, parm2,
	parm3, parm4 );
So when I see:
if(doItToItAllDayAllNightGetItDoneOrGoHomeCrying)
	okayIllDoItToItAllDayAllNight(parm0);
It does not jump out at me that it is an if statement. Looks like a function that just went on too long and he decided to break it up into 2 lines.
One reason is the lack of spaces.
if ( doItToItAllDayAllNightGetItDoneOrGoHomeCrying )
	okayIllDoItToItAllDayAllNight( parm0 );
This jumps out better, as in the previous example the parentheses are a bit hidden. Even this is hard to spot when you are mainly trained to scan for } or {.


As was mentioned by someone else, I tend to add braces on code I am exploring that does not have them, because these are the most dangerous ones. I didn’t write the code. I am not always focused on missing brackets when I insert or remove code, and it frequently happens that I change the scope of some statement on accident.
My coworker watched me make the change in my first example at the top and he also didn’t think about how the for loop’s scope was changed.
When I finally realized, I said, “Oh!”
He saw me adding the first brace and said, “あれ?”
Then I added the second and he said, “ああああぁぁ。そうだねぇ”


L. Spiro
It is amazing how often people try to be unique, and yet they are always trying to make others be like them. - L. Spiro 2011
I spent most of my life learning the courage it takes to go out and get what I want. Now that I have it, I am not sure exactly what it is that I want. - L. Spiro 2013
I went to my local Subway once to find some guy yelling at the staff. When someone finally came to take my order and asked, “May I help you?”, I replied, “Yeah, I’ll have one asshole to go.”
L. Spiro Engine: http://lspiroengine.com
L. Spiro Engine Forums: http://lspiroengine.com/forums

#11 Promethium   Members   -  Reputation: 580

Like
1Likes
Like

Posted 14 November 2011 - 06:05 AM

I always add braces. I have yet to hear even one compelling argument against adding braces. The "wasted whitespace" is a red herring IMO. Writing code is about reading code and overly dense code is harder to read and so it's easier to miss some crucial detail (such as for instance missing braces around the if statement you are modifying.) But even then:
if( something )
    x();
else
    y();
vs
if( something ) {
    x();
} else {
    y();
}
ONE extra line! I will sacrifice that one extra line any day if it stops me or someone else from introducing a stupid bug later.

#12 japro   Members   -  Reputation: 887

Like
0Likes
Like

Posted 14 November 2011 - 06:08 AM

I still use both variants. But the no-braces version only in really "trivial" cases like
[source lang="cpp"]int clamp(int x, int a, int b){ if(x<a) return a; else if(x>b) return b; else return x;}[/source]

Also I put "{" always on the next line and generally have pretty "sparse" looking code, since I find "dense" code very hard to read.

#13 NightCreature83   Crossbones+   -  Reputation: 2934

Like
0Likes
Like

Posted 14 November 2011 - 07:57 AM

I also put the braces on the same lines as the if and friends, so spacing is not a problem.

if ( dog > you ) {
    run();
}
else {
    pet();
}
It did increase but only by 2 lines. I would take that trade-off any day over the risks that come with omitting the braces.

Also I am willing to put them on 1 line as long as the inside of the if is extremely short and simple. Usually these are returns.
if ( dog > you ) { run(); }
else { pet(); }
This is not a particularly good example though because the calls to run() and pet() do not align well. Usually it is more like:
if ( doBad ) { return false; }
if ( doGood ) { return false; }
if ( always ) { return false; }





Aside from that, I am finding it a bit hard to skim his code. I am used to seeing this:
myFunc( parm0, parm1, parm2, parm2,
    parm3, parm4 );
So when I see:
if(doItToItAllDayAllNightGetItDoneOrGoHomeCrying)
    okayIllDoItToItAllDayAllNight(parm0);
It does not jump out at me that it is an if statement. Looks like a function that just went on too long and he decided to break it up into 2 lines.
One reason is the lack of spaces.
if ( doItToItAllDayAllNightGetItDoneOrGoHomeCrying )
    okayIllDoItToItAllDayAllNight( parm0 );
This jumps out better, as in the previous example the parentheses are a bit hidden. Even this is hard to spot when you are mainly trained to scan for } or {.


As was mentioned by someone else, I tend to add braces on code I am exploring that does not have them, because these are the most dangerous ones. I didn’t write the code. I am not always focused on missing brackets when I insert or remove code, and it frequently happens that I change the scope of some statement on accident.
My coworker watched me make the change in my first example at the top and he also didn’t think about how the for loop’s scope was changed.
When I finally realized, I said, “Oh!”
He saw me adding the first brace and said, “あれ?”
Then I added the second and he said, “ああああぁぁ。そうだねぇ”


L. Spiro

See that's why IMHO the braces should be on a new line as the spacing for function arguments doesn't matter any more, you can just parse for statement blocks. Also it means that brace open and brace close are on the same indentation. With large functions, those that run for more than a page of code (and every codebase has them), it is easier to see where a block is opened and closed.
Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, Mad Max

#14 Burnt_Fyr   Members   -  Reputation: 1245

Like
0Likes
Like

Posted 14 November 2011 - 08:06 AM

In the past if done all manner of things but now, I endeavor to use braces.


int function(int arg)
{
   /////////////;
   /////////////;
   /////////////;
}


I used to hate the braces on their own line, but as time went on I found I spent more time hunting down dangling braces with cryptic debug output to go off of (even worse is a missing ; at the end of a class declaration). There is always a chance that your single statement will multiply. If the code is stable, and modification is unlikely, I rarely look past the headers, so the extra white space doesn't affect me.

#15 Bregma   Crossbones+   -  Reputation: 5249

Like
0Likes
Like

Posted 14 November 2011 - 08:09 AM

I've spent decades maintaining other people's code as well as writing my own. I always use braces where there is an option because I have spent far far too much time debugging problems caused by missing braces. Not using braces will get you hated.

That said, I do follow established published coding conventions for projects where they exist, and sometimes those conventions were established by ideologues who insist their opinion trumps practicality and product quality at all costs, so I leave the braces out in those circumstances (and relegate the project to the 'do not recommend -- crap code' pile).

Control statements are promiscuous, you should always use the appropriate prophylaxis if you want to play with them.
Stephen M. Webb
Professional Free Software Developer

#16 Telastyn   Crossbones+   -  Reputation: 3726

Like
0Likes
Like

Posted 14 November 2011 - 08:21 AM

Always. I also use braces on same line as conditional (as Promethium shows, where standards permit) to help spacing.

#17 d128562   Members   -  Reputation: 108

Like
0Likes
Like

Posted 14 November 2011 - 10:58 AM

Always! I'm a kinda braces-parenthesis-space-tabs nazi. I also hate compact code style...

#18 swiftcoder   Senior Moderators   -  Reputation: 10241

Like
0Likes
Like

Posted 14 November 2011 - 11:22 AM

I never use braces for single-line statement blocks (unless the required coding style prevents it). My primary rationales for this is that I write the majority of my code on an 11" MacBook Air, so vertical screen real estate is really kind of precious.

<humorous rant>

I would argue that the whole 'lack of braces causes bugs' line of reasoning is baloney. Curly braces (no matter where you put them) are much harder to spot than proper indentation, so I would say that you have all spent too long in curly-brace land, and have come to use them as a crutch, to support poor code formatting and/or code reading skills.

</humorous rant>

Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#19 SiCrane   Moderators   -  Reputation: 9628

Like
0Likes
Like

Posted 14 November 2011 - 11:32 AM

If it all fits on a single line I don't bother with braces. If it needs two or more lines, then the braces go in. This means that every time I use else then both sides get braces, because else always gets it's own line the way I format code.

#20 Telastyn   Crossbones+   -  Reputation: 3726

Like
0Likes
Like

Posted 14 November 2011 - 12:12 PM

Curly braces (no matter where you put them) are much harder to spot than proper indentation,


As long as you have a good auto-formatter, yeah. Otherwise you get the
if(condition)
	do stuff;
	and stuff we added later;

bug.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS