Absolutely not evil. In fact, it's pure, and if-then-else isn't.
In functional languages like Haskell, F#, ML etc., it's the if-then-else statements that are considered evil.
The reason for this is that any "action" like an imperative if-then-else statement requires you to separate a variable declaration from its definition, and introduces state to your function.
For instance, in the following code:
const var x = n % 3 == 1
? Parity.Even
: Parity.Odd;
vs.
Parity x;
if (n % 3 == 1)
x = Parity.Even;
else
x = Parity.Odd;
The first one has two advantages aside from being shorter:
x
is a constant, and so offers much fewer chance of introducing bugs, and can potentially be optimized in ways the second could never be.
- The type is made clear by the expression, so the compiler can effortlessly infer that
x
needs to be of type Parity
.
Confusingly, in functional languages, the ternary operator is often called if-then-else. In Haskell, you might say x = if n mod 3 == 1 then Odd else Even
.
((x > y) && (x > z)) ? ((x > w) ? x : w) : ( ((y > z) && (y > w)) ? y : ((z > w) ? z : w) )
or you could useint max2(int x, int y) { return (x > y) ? x : y; }
andint max4 (int x, int y, int z, int w) { return max2 (max2 (x, y), max2 (z, w)); }
for more readability. – Jan 26 '11 at 01:19super()
in a constructor because?:
evaluates. E.g. `public Kitty(String favFood) { super(favFood == null ? Cat.DEFAULT_FOOD : favFood); } See also the answer @Benjol gave. – GlenPeterson Nov 26 '12 at 15:29if - then - else
and the ternary operator are the same thing. – Giorgio Nov 26 '12 at 16:39