It's far from "arbitrary" --- and I suspect that this dogmatic, misguided way of (not) thinking about it is responsible for the majority of the complaints and aversion, since as others have mentioned, it is completely equivalent in structure to if/else!
What do I mean by "far from arbitrary"? Well... what is the character used in basically all Latin (and even some widely-used non-Latin) languages to denote a question? I've already used that character twice in this post so far, and you should've found the previous two sentences to be pretty clear, so stop pretending the ternary operator is something scary and "unreadable" and see it for what it is: it is literally asking a question!
understand ? done() : keep_thinking();We ask questions with ? but we don't offer alternative answer to the question with :. If anything, maybe it should be ; or even .?
I disagree. I find no clarity in using nested ternaries, but I understand it's a matter of opinion.
x = if | a < b -> -1
| a > b -> 1
| otherwise -> 0
(and `cond` in lisps)Thats very subjective. As a beginner dev, the ternary series is almost un-understandable for me. While the if/else blocks are far easier to glance at and digest.
if a < b: x = -1
else if a > b: x = 1
else: x = 0
Which a lot of people seem to hate for some reason, but I always appreciated the compromise between terseness and clarity. x = (-1 if a < b else
1 if a > b else
0)
This emphasizes the possible values that x may be assigned to.
It's not about the line count, it's about expressing the main idea clearly and succinctly, which this code does.
My nitpick would be with the language constructs themselves. The ternary operator is simply a crutch for lack of an if-then expression returning a value.
Or can add some white space to make the structure a little more clear: Expressions like the ternary operator micro-optimize by replacing tokens recognizable as natural language words with arbitrary punctuation. But that's a language level complaint, which you generally don't have any control over once you've started the project or when editing existing code.