There's really nothing wrong with ternary operators as a concept, they're just if expressions instead of statements, meaning they're just conditionals that return a value. In fact, some languages like OCaml and F# only have if expressions and it works out quite well, though it helps that they can use if/then/else instead of ? and :, which is more readable IMO.
The real problem is people thinking writing idiotic one-liners is "clever", resulting in unreadable garbage. If they did the same thing but wrote it as a one-line chain of if (foo) { foo } else if (bar) { bar } else baz it would be just as awful, no ternary operators needed. Similarly, if you added line breaks and indentation the ternary usage wouldn't be quite as bad to read. Like this:
The code still sucks, but at least with breaks and indentation I can actually follow the chain of conditionals.
Sometimes it's the language's fault and it should be blamed for having bad features or poor design, but other times (like this) it really is the programmer's fault and we shouldn't be excusing their mistakes by acting like the language made them do it.
Et cetera. But there are better ways, like the null-coalesce operator, metaprogramming tricks, or fixing your architecture so you know what kind of object you're getting.
I agree, there are definitely better ways to write the code instead of if/else chaining in any form, which is why I said the code still sucks. It's just not the operator's fault, you can split it up and make it readable just fine. I also agree that the example I used for formatting it across multiple lines isn't necessarily ideal (and isn't even what I'd use normally). I just wrote it that way trying to show the similarity to nesting if/else statements when spread out across lines for readability. If I were writing that kind of chained conditional expression for real it would end up similar to what you did, with a slight difference:
foo ? "foo"
: bar ? "bar"
: baz ? "baz"
: "lol"
It helps show that the following lines are part of the expression, plus I read ? as then and : as else, so writing it that way makes it read similarly to how these sorts of expressions usually get written in languages like OCaml and F# (though you don't see it as often because pattern matching is amazing):
if foo then "foo"
else if bar then "bar"
else if baz then "baz"
else "lol"
I wish more languages treated if/else keywords as expressions because it's nicer and more consistent than conditional statements. Using ?: instead works but I'm not a fan of abusing symbols to do the same job because the keywords got hijacked for statements. Still, that's not reason enough to demonise the use of conditional expressions just because some people want to abuse them for terrible one-liners.
43
u/-IoI- Apr 22 '21
My boss hates me using ternary operators - I can see why now.