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

This topic is 2255 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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

##### Share on other sites
Always!

Extra work but clean code, and no error-prone

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
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]

##### Share on other sites
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.

##### Share on other sites
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...

##### Share on other sites
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.

##### Share on other sites
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.

##### Share on other sites
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

##### Share on other sites
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(); vsif( 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.

##### Share on other sites
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.

##### Share on other sites

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.

##### Share on other sites
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.

##### Share on other sites
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.

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

##### Share on other sites
Always! I'm a kinda braces-parenthesis-space-tabs nazi. I also hate compact code style...

##### Share on other sites
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>

##### Share on other sites
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.

##### Share on other sites

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.

##### Share on other sites
I answered "Sometime...". That might seem weird, but i got used to write my if and for loop that way:

if(){
...
} else {
....
}

for( ; ; ){
....
}

This save a line or two of code, lol, and it's not hard to understand once you got used to it. I still write functions and switch the "right" way though.

##### Share on other sites

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>

You are a python hacker aren't you where indentation level is block structuring

##### Share on other sites
I prefer to leave them out if they're unnecessary. My two reasons are:

1. Vertical white space is premium real-estate, especially on laptops and/or widescreen monitors. My brand new 27" monitor at work is a 1080p screen (with no rotation support) that's not a lot of space, honestly.

2. I use vertical white space to create "code paragraphs" within functions. When quickly scanning source, a brace that's taking up a whole line to itself registers to me
as a blank line.

Also, if the 'if' is executing an assignment, then I use the conditional assignment operator (? -- its more conise, and expresses intent more clearly. I may or may not put unbraced statements on the same line as the conditional depending on a number of factors such as length, and whether similar conditionals follow on subsequent lines (in which case, I often don't separate the 'if' lines at all: one 'if' per line, no white space between).

##### Share on other sites

Folks, I've seen a lot of code. A lot. Over 30 years, many languages, many styles.

And you know, it really just does not matter. It's nice to have consistency within the same source file, but even that doesn't matter too much. Really.

Heathen.

Braces always. Single line statements I use the ternary operator if applicable or try to remove the branch.

Hodgman's example could have just used abs though. There's rarely a legitimate use of a single line if and in any case this is always preferable:
if (foo) { Foo(); }
Notice the "if (" and not "if( ", important. Also remember tabs for indentation and spaces for alignment.