While I have known of the ternary operator for years, in the past, I have found it uselessly obtuse and preferred to use the classic "if" statement. In my mind, the two were equivalent. I have just recently discovered that this is in fact untrue, as far as Flex is concerned. So very untrue indeed. Read on and I will explain why I have discovered a new-found appreciation for the long lost operator.
The ternary isn't an if, no "ands or buts"
To me, the main reason not to use the ternary operator was if the two were equivalent, the clarity of the "if" trumped its brevity. Besides, it looked a little too much like PERL (the "Language of a thousand operators").
The following two statements are indeed equivalent:
Statement 1.
if (value1 == value2) {value3 = true;} else {value3 = false;}Statement 2.value3 = (valueA == valueB ? true : false);
OR statements using the ternary operator
Just for fun, it is also possible to write a one-line "or" statement using a ternary operator.
e.g. (if a is true or b is true, c is true, otherwise c is false)
is equivalent to:c = (a ? true : b ? true : false);
if (a || b) {
c = true;
} else {
c = false;
}
Where Bindings Come InSo far, I haven't covered anything particularly earth-shattering, however, if you're a Flex developer, you'll appreciate how much you depend on the maintainability and brevity of using binding statements in your Components (i.e. the MXML statements inside curly brackets e.g. "{bindMe}"). Sometimes, you'd love to, but Flex won't allow you to conditionally bind a value.
Despair not. Although if/else statements aren't allowed inside a binding statement, a ternary expression is allowed. That means that you can now write conditional binding expressions, rather than having to take the more complex statements that you'd like bound and putting them into a function, add on a bunch of event-handling code, wasting precious moments out of the prime of your life.
e.g.
<mx:text text="{data as String}"toolTip="{(data as String).length > 20 ? data as String : null}"/>
This statement allows me to display a bound toolTip value if the string inside the Text Component is longer than 20 characters. Otherwise, it shows no toolTip.
...now let that sink in.
What it means is that you can create dynamic bindings with conditional "smarts" in them. If you're anything like me, that's pretty freaking sweet. Not too shabby for an operator that I personally had condemned to the slag heap of obscurity.