First, I realize this is on the commonly rejected changes list, but I think I'm bringing new information to the table.
I would never have been inclined to propose this before, because I like the ternary operator and have no trouble reading it. That said, I keep meeting experienced programmers (really smart people!) that have no trouble reading
if someCondition { firstThing() }
else if otherCondition { secondThing() }
else { thirdThing() }
and yet are confused by the analogous ternary construction:
some.long.lvalue[expression]
= someCondition ? firstThing()
: otherCondition ? secondThing()
: thirdThing()
Usually when they see this code they ask that I rewrite it in terms of a switch or and if/else that initializes some.long.lvalue[expression]
in three different places instead of once, or create some new intermediate variable, either of which is bad for readability, and sometimes, efficiency.
I could just keep telling myself that these people should get over themselves and learn to read ternary chains, but at some point, after hearing the same complaint from many people, one has to accept that user experience is real. The people I'm hearing from are clearly not going to get comfortable with ternary chains. Therefore I propose legalizing this form:
some.long.lvalue[expression]
= if someCondition { firstThing() }
else if otherCondition { secondThing() }
else { thirdThing() }
Note: I am only proposing that this work when the {}
-enclosed clauses are single expressions with a common type. I think this can be expressed in terms of simple textual rewrite rules that transform if/else expressions into ternary expressions inside the compiler.