Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

dreilly1982

macrumors newbie
Original poster
Feb 7, 2011
28
0
Just a quick question, on standard style. When is it OK to use a ternary operation as opposed to an if/else?

if (a>b){
do this
}
else{
do that
}

VS

(a>b) ? do this : do that

Is it just a matter of preference or are there rules for when you use one over the other? I am just learning, and nothing I've read spells anything out.
 
Many people (and employers) avoid the ternary operator. I hate it personally, because it creates lines of code that are too "dense."

I'd much rather sacrifice a bit of scrolling and immediately see a few simple, unambiguous statements that don't require any mental processing cycles to grok, instead of: "ok it's a ternary operator, so the first thing is if it's true (I think) and the second is if it's false...let me double check...google and confirm I'm right, etc." If you decide to use it, I would only use it for the simplest of situations. Files length can go on forever, and screens are big these days, so why not trade a little vertical space for making your code simpler? Caveat: this is ultimately a style decision, so you're going to find people who have very different preferences than I do. I'm dyslexic, so whitespace is my friend; I use it as a tool to help clarify the intent of the code.

My advice is to play around with it and decide if it's a good fit for your style, and what situations it might improve/hinder the readability of your code.
 
We have people here that put multiple ones on the same line. I really hate that. It can save alot of lines but then again we all have dual 21 or 27 inch monitors so...

Code:
if home_team.score > away_team.score Constant[:HomeTeamWin] ? home_team.score < away_team.score : Constant[:AwayTeamWin] ? Constant[:Tie]

compared to:

Code:
if home_team.score > away_team.score
 Constant[:HomeTeamWin]
elseif home_team.score < away_team.score
  Constant[:AwayTeamWin]
else
  Constant[:Tie]

That's Ruby and it's not the exact code but you get the idea.
 
I would use the ternary form if I wanted the expression to return a value.
 
The ternary form is designed to return a value based on a condition, so using it with "do this" : "do that" arguments does not really make logical sense. Sometimes it does make sense as a simple value selector, but really should be used sparingly. You should view it as fundamentally discreet, by which I mean that if you were to use a function as one or both arguments, the functions should not have a significant effect on anything else.

And never, ever, nest them
Code:
x = a != b ? a > b ? a : b : a ;
 
The ternary form is designed to return a value based on a condition, so using it with "do this" : "do that" arguments does not really make logical sense. Sometimes it does make sense as a simple value selector, but really should be used sparingly. You should view it as fundamentally discreet, by which I mean that if you were to use a function as one or both arguments, the functions should not have a significant effect on anything else.

And never, ever, nest them
Code:
x = a != b ? a > b ? a : b : a ;

I do concatenate them sometimes. Like

Code:
NSString* message = value == 1 ? @"First message"
                  : value == 2 ? @"Second message"
                  : value == 3 ? @"Third message"
                  : value == 4 ? @"Fourth message" : @"Whatever";
 
Our company coding standard generally forbids the use of the ternary operator but exceptions can be made, for example if using it actually increases the readability of the code.

For example, consider this:
Code:
cout << "Apollo launch status:" << endl;
cout << "BOOSTER is "  << launch.booster  ? "GO" : "NO GO" << endl;
cout << "RETRO is "    << launch.retro    ? "GO" : "NO GO" << endl;
cout << "FIDO is "     << launch.fido     ? "GO" : "NO GO" << endl;
cout << "GUIDANCE is " << launch.guidance ? "GO" : "NO GO" << endl;
cout << "SURGEON is "  << launch.surgeon  ? "GO" : "NO GO" << endl;
cout << "EECOM is "    << launch.eecom    ? "GO" : "NO GO" << endl;
...

You could do the same with if/then statements, but the code would be four times as long, even more so if your coding standard mandates the { and } braces around every if/else block. And the use of all those if/else blocks would actually take away from the readability of the code -- you can see exactly what's going on up there because of the way all that similar code is grouped.
 
Last edited:
if your coding standard mandates the { and } braces around every if/else block.

If your coding standard contains that, it was written by someone who feels he knows every detail of the language and every other programmer in the team is far inferior and needs to be protected against himself; the rule forbidding ternary ops would be right above it in the list (and the next one is forbidding to use exceptions, templates, variable names with less than 20 characters, lines with more than 72, or files with more code than comment).
 
If your coding standard contains that, it was written by someone who feels he knows every detail of the language and every other programmer in the team is far inferior and needs to be protected against himself; the rule forbidding ternary ops would be right above it in the list (and the next one is forbidding to use exceptions, templates, variable names with less than 20 characters, lines with more than 72, or files with more code than comment).

Well, like I said, people make exceptions all the time if it's justifiable. In a code review, someone will comment "coding standard says ___" and I can simply respond "yes I know but in this case..." and they're OK with that.

You're right, rules like always including the braces are to protect us from ourselves. Have I made the mistake of starting a compound statement before realizing that I need to add braces? Sure have. Did it ever escape into production code? No, I caught it almost immediately. But I don't have a problem with the intent behind the rule.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.