• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
L. Spiro

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


47 posts in this topic

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

[code]if ( dog > you )
run();
else
pet();[/code]

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:
[code]if ( doit )
okay();
for ( ; ; )
{
blah();
}[/code]
to this:
[code]if ( doit )
//okay();
for ( ; ; )
{
blah();
}[/code]

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 [i]actual[/i] 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 [b]always[/b] add the braces, [b]never[/b] add the braces, or [b]sometimes[/b] add the braces?


L. Spiro

2

Share this post


Link to post
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.
0

Share this post


Link to post
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.
1

Share this post


Link to post
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[i];

if( value < 0 )
{
vec[i] = -value;
}
}[/source]
2

Share this post


Link to post
Share on other sites
If its kept on a single line, i.e:

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

Then i'd add braces just to make things clear and avoid future mistakes.
0

Share this post


Link to post
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;

[code]
if(a > b)
{
x = c;
}
else
{
x = d;
}
[/code]

vs:

[code]
x = (a > b ? c : d);
[/code]

8 lines vs 1...


1

Share this post


Link to post
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:
[code]
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; }
[/code]

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.
0

Share this post


Link to post
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.
0

Share this post


Link to post
Share on other sites
I also put the braces on the same lines as the if and friends, so spacing is not a problem.

[code]if ( dog > you ) {
run();
}
else {
pet();
}[/code]
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.
[code]if ( dog > you ) { run(); }
else { pet(); }[/code]
This is not a particularly good example though because the calls to run() and pet() do not align well. Usually it is more like:
[code]if ( doBad ) { return false; }
if ( doGood ) { return false; }
if ( always ) { return false; }[/code]





Aside from that, I am finding it a bit hard to skim his code. I am used to seeing this:
[code]myFunc( parm0, parm1, parm2, parm2,
parm3, parm4 );[/code]
So when I see:
[code]if(doItToItAllDayAllNightGetItDoneOrGoHomeCrying)
okayIllDoItToItAllDayAllNight(parm0);[/code]
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.
[code]if ( doItToItAllDayAllNightGetItDoneOrGoHomeCrying )
okayIllDoItToItAllDayAllNight( parm0 );[/code]
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
2

Share this post


Link to post
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:
[code]if( something )
x();
else
y();
[/code]vs[code]if( something ) {
x();
} else {
y();
}[/code]
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.
1

Share this post


Link to post
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.
0

Share this post


Link to post
Share on other sites
[quote name='YogurtEmperor' timestamp='1321269571' post='4883735']
I also put the braces on the same lines as the if and friends, so spacing is not a problem.

[code]if ( dog > you ) {
run();
}
else {
pet();
}[/code]
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.
[code]if ( dog > you ) { run(); }
else { pet(); }[/code]
This is not a particularly good example though because the calls to run() and pet() do not align well. Usually it is more like:
[code]if ( doBad ) { return false; }
if ( doGood ) { return false; }
if ( always ) { return false; }[/code]





Aside from that, I am finding it a bit hard to skim his code. I am used to seeing this:
[code]myFunc( parm0, parm1, parm2, parm2,
parm3, parm4 );[/code]
So when I see:
[code]if(doItToItAllDayAllNightGetItDoneOrGoHomeCrying)
okayIllDoItToItAllDayAllNight(parm0);[/code]
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.
[code]if ( doItToItAllDayAllNightGetItDoneOrGoHomeCrying )
okayIllDoItToItAllDayAllNight( parm0 );[/code]
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
[/quote]
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.
0

Share this post


Link to post
Share on other sites
In the past if done all manner of things but now, I endeavor to use braces.

[code]

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

[/code]

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.
0

Share this post


Link to post
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.
0

Share this post


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

Share this post


Link to post
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>
[indent]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.
[/indent]</humorous rant>
0

Share this post


Link to post
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.
0

Share this post


Link to post
Share on other sites
[quote name='swiftcoder' timestamp='1321291378' post='4883842']
Curly braces (no matter where you put them) are much harder to spot than proper indentation,
[/quote]

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

bug.
0

Share this post


Link to post
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.
0

Share this post


Link to post
Share on other sites
[quote name='swiftcoder' timestamp='1321291378' post='4883842']
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>
[indent]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.
[/indent]</humorous rant>
[/quote]

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

Share this post


Link to post
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).


2

Share this post


Link to post
Share on other sites
[quote name='Bregma' timestamp='1321300233' post='4883901']
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.
[/quote]
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:
[code]if (foo)
{
Foo();
}[/code]
Notice the "if (" and not "if( ", important. Also remember tabs for indentation and spaces for alignment.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0