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

Started by
46 comments, last by Vectorian 12 years, 4 months ago
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

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

Advertisement
Always!

Extra work but clean code, and no error-prone

https://www.kbasm.com -- My personal website

https://github.com/wqking/eventpp  eventpp -- C++ library for event dispatcher and callback list

https://github.com/cpgf/cpgf  cpgf library -- free C++ open source library for reflection, serialization, script binding, callbacks, and meta data for OpenGL Box2D, SFML and Irrlicht.

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.
[size=2][ 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 ]
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.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

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;

//vs

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;
}

// vs

for( int i = 0; i != 4; ++i )
{
float value = vec;

if( value < 0 )
{
vec = -value;
}
}[/source]
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.
[size="1"]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!
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...


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.
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, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

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

I restore Nintendo 64 video-game OST’s into HD! https://www.youtube.com/channel/UCCtX_wedtZ5BoyQBXEhnVZw/playlists?view=1&sort=lad&flow=grid

This topic is closed to new replies.

Advertisement