PDA

View Full Version : Quick question on ternary operations




dreilly1982
Mar 6, 2012, 09:55 AM
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.



robvas
Mar 6, 2012, 10:30 AM
Preference for readability.

ScoobyMcDoo
Mar 6, 2012, 10:58 AM
I typically only use the ternary form for simple assignments.

EG: absval = (a < 0) ? a * -1.0 : a;

GorillaPaws
Mar 6, 2012, 12:26 PM
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.

robvas
Mar 6, 2012, 01:05 PM
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...


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


compared to:


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.

dmi
Mar 6, 2012, 04:40 PM
I would use the ternary form if I wanted the expression to return a value.

blevins321
Mar 6, 2012, 04:50 PM
I prefer to use it for simple string assignments, but regular if statement for any numerical operations.

Sydde
Mar 7, 2012, 10:34 PM
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
x = a != b ? a > b ? a : b : a ;

gnasher729
Mar 8, 2012, 11:20 AM
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
x = a != b ? a > b ? a : b : a ;

I do concatenate them sometimes. Like

NSString* message = value == 1 ? @"First message"
: value == 2 ? @"Second message"
: value == 3 ? @"Third message"
: value == 4 ? @"Fourth message" : @"Whatever";

notjustjay
Mar 8, 2012, 12:11 PM
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:

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.

Sander
Mar 8, 2012, 01:37 PM
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).

notjustjay
Mar 8, 2012, 02:16 PM
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.