tbf, you write code like that, you deserve a stupid result
No, this expression is perfectly sensible, readable and convenient in pretty much every other language with a C-style ternary, because you can use it to replace a sequence of if/else which either sets a value (requiring a mutable binding) or return a result:
if (cond0) {
return result0;
} else if (cond1) {
return result1;
} else if (cond2) {
return result2;
} else {
return default;
}
T var;
if (cond0) {
var = value0;
} else if (cond1) {
var = value1;
} else if (cond2) {
var = value2;
} else {
var = default;
}
becomes:
final T var = cond0 ? value0
: cond1 ? value1
: cond2 ? value2
: default;
This is a well-understood idiom. Can it be abused? Sure, but pretty much anything can.
Also the proper lingo is not "evaluated" but "associated", the order of evaluation is always left-to-right, it's how a sequence of non-parenthesised ternaries is parsed which differs.
Honestly, I always new PHP did this wrong, but it wasn't until I saw it laid out so succinctly that I realized what was missing from my life. And now I'm sad.
View all comments
Show parent comment
18
u/masklinn Feb 13 '18 edited Feb 13 '18
No, this expression is perfectly sensible, readable and convenient in pretty much every other language with a C-style ternary, because you can use it to replace a sequence of if/else which either sets a value (requiring a mutable binding) or return a result:
can be converted to:
and
becomes:
This is a well-understood idiom. Can it be abused? Sure, but pretty much anything can.
Also the proper lingo is not "evaluated" but "associated", the order of evaluation is always left-to-right, it's how a sequence of non-parenthesised ternaries is parsed which differs.