Log in

View Full Version : Ternary operators


Robototes2412
04-04-2010, 22:30
Was I the only one that used these on the robot?

For those not in the know, Ternary operators are essentially an inline if statment.

Example using if statements, like mama told you to do so:
boolean getState() {
if(this.thing.state) {
return true;
else {
return false;
}
}

Example using the ternary operators:
boolean getStateTernary() {
return this.thing.state ? true : false;
}

It does the same thing but is way easier.

The layout is:
variable = [boolean condiditon] ? [if its true] : [if its false];

This works in C, C++, Java, and I believe C#.

Did anyone else use these?

biojae
04-04-2010, 22:36
Instead of using the ternary operators or the if statements in your examples, why don't you just return the value of the boolean going into the if or ternary?

Instead if this:


boolean getState() {
if(this.thing.state) {
return true;
else {
return false;
}
}


or this:



boolean getStateTernary() {
return this.thing.state ? true : false;
}




why not just this?



boolean getState() {
return this.thing.state;
}

Radical Pi
04-04-2010, 22:38
I used them a couple of times in our robot code. It's a little unreadable, but it gets the job done well

Robototes2412
04-04-2010, 22:45
why not just this?



boolean getState() {
return this.thing.state;
}



Its bad practice, according to my dad, who uses java at his work. It can also lead to memory leaks.

@Radical Pi: Yay, can you post some memorable examples of using them?

Al3+
04-04-2010, 22:48
I would use them if I had a reason to. This year I never did.

and @above how so? (booleanValue ? true : false) is equivalent to booleanValue for all intents and purposes, and booleanValue is more succinct. There's no way the former could cause a memory leak, unless the latter does too.

Radical Pi
04-04-2010, 23:28
@Radical Pi: Yay, can you post some memorable examples of using them?

This one got me messed up a few times

kickerJag->Set(jr->GetTrigger() || dsio->GetDigital(11) ? 0.0 : dsio->GetAnalogInRatio(1));

Explanation: We use a rotating kicker mounted on pneumatic sliders with a clutch so that we can spin it inside the robot then slide it out to kick. If the trigger on the right joystick or the big red kick button is pressed, then disable the spinner motor (no reason to leave it spinning freely). If neither button is pressed (kicker retracted), then set the speed to the value of a potentiometer on the DS.

virtuald
04-04-2010, 23:44
I tend to use Ternary operators in printf() statements in C/C++ when trying to print boolean values.


printf("Some boolean value is : %s\n", some_bool ? "true" : "false");


Generally speaking, ternary operators are usually more difficult to read, so I try to avoid them. However, if you space it out and format them correctly then they aren't so bad.

FRC4ME
04-04-2010, 23:58
I use these all the time. In my opinion, they make code more readable (so long as the person reading it knows what they are) and clarify the intent of what you are doing in many places.

Some places I like to use them include when the arguments to a method call are dependent on a condition:


wpiRelay.set(isOn
? edu.wpi.first.wpilibj.Relay.Value.kOn
: edu.wpi.first.wpilibj.Relay.Value.kOff);


when the return value of a function is dependent on a condition:


return isReversed
? !wpiSolenoid.get()
: wpiSolenoid.get();


when initializing a variable conditionally (you're almost required to use it here):


final double csd = isRedFriendly
? redScore - blueScore
: blueScore - redScore;


and in the middle of a complex statement I don't want to write twice just for the conditional (this one's from WPILib):


m_digitalOut |= ((value ? 1 : 0) << (channel - 1));


I try to follow the rule that a method should have only one return statement. One point of entry, one point of exit. Ternary operators make that much easier.

rsisk
05-04-2010, 00:20
I don't see how this could cause a memory leak. I use this type of statement all the time in C without a problem.

Robototes2412
05-04-2010, 00:33
never mind about the memory leaks

gvarndell
05-04-2010, 06:24
It can also lead to memory leaks.

I think it can also contribute to global warming... ;)

360skier
05-04-2010, 09:03
I think it can also contribute to global warming... ;)

Not to mention put your robot overweight... :p

Zme
05-04-2010, 12:55
we used them a couple of times, primarily where an if statement would be inconvenient, or when we are trying to count outputs (if could result in double counting).

some of our mentors really don't appreciate them, so using them is kinda limited

Robototes2412
05-04-2010, 13:11
I use them like sprinkles, with verbose comments following them

Al3+
05-04-2010, 14:48
return isReversed
? !wpiSolenoid.get()
: wpiSolenoid.get();


Technically this could be also written:
return isReversed ^ wpiSolenoid.get(); // if reversed, then flip solenoid value
though the ?: version is arguably more readable.

LukeS
05-04-2010, 21:59
Yeah, we do all the time. Although, prior to this year I was the only one on the team who knew about them. I distinctly remember explaining them last year, saying that they are the text equivalent of that triangle thing in LabVIEW (bleh!), though apparently no one remembered.

examples from our code:

text output:
C.lcd.lines[0]="compressor:"+(comp.getPressureSwitchValue()?"off":"on");
C.lcd.lines[1]="SideKicker: "+(C.sideKickLoaded<0?"released":"loaded");

flipping a roller based on a switch:
roller.set(C.rollerSpeed*(C.rollerForward?1:-1));

only spinning the extend-able wheels if they're extended
fDrive.set(C.upFront? C.fDrive:0);//if they're up, don't bother
bDrive.set(C.upBack ?-C.bDrive:0);//if they're up, don't bother

mathking
05-04-2010, 22:25
A ternary operator statement is kind of like a small switch statement. They can be useful, and if you like them go ahead and use them. But don't fall into the trap of thinking that they are necessarily more efficient. That depends on the language and compiler, and exactly how the if statement and the ternary statement are set up. Just because one piece of code is longer than another does not mean that it will be compiled into less efficient code. In a great many cases both pieces of code will compile into identical or nearly identical object code.

I would tend to argue that they almost never make code easier to understand than a well written if - else. If you know what you are doing then they may not be any more difficult to read, but I don't think the use of a ternary statement will make an unclear if - else statement suddenly clear.

Using the cRIO and Java or C++, I think the most important thing to do with the code is to make it easily readable. There is no compelling reason to have a small code size, just good efficient code. Think of how much time you spend tweaking and debugging for any program. But then place this in the context of a robotics competition where finding the problem code and fixing it must often be done in a very short, fixed period of time. Code clarity is essential. So use structures that all of the programmers agree upon ahead of time. A set of coding standards is never a bad idea. (And it will help student programmers get some real world experience.) So use the format that your team understands and wants to use.

Greg Marra
05-04-2010, 22:44
Using the cRIO and Java or C++, I think the most important thing to do with the code is to make it easily readable.

I agree 100%. I have heard that code is read on average ten times more often than it is written. Style is personal preference, but would you rather save some keystrokes now, or a debugging headache a month later?

Robototes2412
05-04-2010, 23:11
i always have three lines of comments after ternary operators explaining them and instructions to yell at me if they dont understand.

keehun
05-04-2010, 23:15
I use these all the time in my computer science class at the University of Minnesota

Chris27
05-04-2010, 23:46
Was I the only one that used these on the robot?

For those not in the know, Ternary operators are essentially an inline if statment.

Example using if statements, like mama told you to do so:
boolean getState() {
if(this.thing.state) {
return true;
else {
return false;
}
}

Example using the ternary operators:
boolean getStateTernary() {
return this.thing.state ? true : false;
}

It does the same thing but is way easier.

The layout is:
variable = [boolean condiditon] ? [if its true] : [if its false];

This works in C, C++, Java, and I believe C#.

Did anyone else use these?

I would recommend against coding in this style as not only is it not concise, but there is an overhead to making function/method calls. Why bury a simple boolean test in a bunch of syntax? As a rule of thumb, if you can code something with fewer lines of code, it is typically better to do so.

FRC4ME
06-04-2010, 00:05
Technically this could be also written:
return isReversed ^ wpiSolenoid.get(); // if reversed, then flip solenoid value
though the ?: version is arguably more readable.

Once again, it's about clarity of intent. Make it obvious to the reader what you are doing. IMO, if you're choosing what to return conditionally, putting the conditional inside the return statement is more readable (provided, of course, the reader knows what a ternary operator is).

The XOR, on the other hand, would make even someone familiar with that operator stop and think, "now what could he possibly be doing here?"

Yeah, we do all the time. Although, prior to this year I was the only one on the team who knew about them. I distinctly remember explaining them last year, saying that they are the text equivalent of that triangle thing in LabVIEW (bleh!), though apparently no one remembered.

examples from our code:

text output:
C.lcd.lines[0]="compressor:"+(comp.getPressureSwitchValue()?"off":"on");
C.lcd.lines[1]="SideKicker: "+(C.sideKickLoaded<0?"released":"loaded");

flipping a roller based on a switch:
roller.set(C.rollerSpeed*(C.rollerForward?1:-1));

only spinning the extend-able wheels if they're extended
fDrive.set(C.upFront? C.fDrive:0);//if they're up, don't bother
bDrive.set(C.upBack ?-C.bDrive:0);//if they're up, don't bother

Try this:


C.lcd.lines[0] = "compressor:" + (comp.getPressureSwitchValue()
? "off"
: "on");
C.lcd.lines[1]= "SideKicker: " + (C.sideKickLoaded < 0
? "released"
: "loaded");



roller.set(C.rollerSpeed * (C.rollerForward
? 1
: -1));



// If they're up, don't bother
fDrive.set(C.upFront
? C.fDrive
: 0);
bDrive.set(C.upBack
? -C.bDrive
: 0);


See what some well-placed white space can do for readability? Granted, breaking after ternary operators is my personal preference, but you should at the very least surround your operators with spaces. "Well-placed white space will save mistakes!" Say it with me now...:D

LukeS
07-04-2010, 00:39
See what some well-placed white space can do for readability? Granted, breaking after ternary operators is my personal preference, but you should at the very least surround your operators with spaces. "Well-placed white space will save mistakes!" Say it with me now...:D

Oh, I know, I'm our teams white-space nazi! (if you don't believe me, just check (http://servb.ath.cx:3445/~luke/1024/Brooke-wch.zip)*) I just generally feel that ternaries should be a single line, although, looking at how you did it, I like how newlines looks with text strings. However, I still feel that for the others, a single line is more readable. Looking at the drive code in black, I would probably add more spaces, but with syntax highlighting, I think it's fine how it is.

Also, for text output, the reason the compressor line has NO spaces at all is that with 2 4-character tabs (class and method) we were squeezing for 80 columns (something which I am also a nazi for).

* although, it does look like some spacing got messed up when tweaking numbers in autonomous. I'll fix this and update it today or tomorrow. (that URL is always the newest version)