For the More Curious: Conditional (ternary) operator

It is not uncommon that you will use if and else to set the value of an instance variable. For example, you might have the following code:

i​n​t​ ​m​i​n​u​t​e​s​P​e​r​P​o​u​n​d​;​
i​f​ ​(​i​s​B​o​n​e​l​e​s​s​)​
 ​ ​ ​ ​m​i​n​u​t​e​s​P​e​r​P​o​u​n​d​ ​=​ ​1​5​;​
e​l​s​e​
 ​ ​ ​ ​m​i​n​u​t​e​s​P​e​r​P​o​u​n​d​ ​=​ ​2​0​;​

Whenever you have a scenario where a value is assigned to a variable based on a conditional, you have a candidate for the conditional operator, which is ?. (You will sometimes see it called the ternary operator).

i​n​t​ ​m​i​n​u​t​e​s​P​e​r​P​o​u​n​d​ ​=​ ​i​s​B​o​n​e​l​e​s​s​ ​?​ ​1​5​ ​:​ ​2​0​;​

This one line is equivalent to the previous example. Instead of writing if and else, you write an assignment. The part before the ? is the conditional. The values after the ? are the alternatives for whether the conditional is found to be true or false.

If this notation strikes you as odd, there is nothing wrong with continuing to use if and else instead. I suspect over time you will embrace the ternary operator as a concise way to do conditional value assignment. More importantly, you will see it used by other programmers, and it will be nice to understand what you see!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset