So I’ve heard it or read it at least 5 times in the past few days: everyone hates the ternary operator. Why? What’d it ever do to you? Wait wait, what’s the ternary operator? Srsly? You’re on my blog and you don’t know what it is? Ok, so normally one writes a conditional like this:
if (someCondition equals some value) {
do stuff;
} else
{
do other stuff;
}
Lots of code for not so much of anything else (outside of readability). Ok, so for those cases where the stuff and other stuff are single lines or some other simple deal (e.g. returning a boolean or integer value), the ternary operator is great. Take a look:
(someCondition equals some value) ? do stuff : do other stuff;
Look at how nice and neat that is — how’s it difficult to read? What if you want to set a value?
x = (someCondition equals some value) ? true : false;
So if someCondition equals some value, x is set to true, otherwise it’s set to false. Nothing difficult or complicated about it. There’s nothing hard to read about it either, imo. Having said all of this, don’t go doing something stupid like this (because it IS hard to read):
(someCondition equals some value and another Condition equals some value or .............. and ............. yada yada more conditions and stuff that eventually evaluates to a boolean) ? do a ton of stuff : do some other ton other stuff;
Bad. Skip it, keep things simple, and go with the regular conditional syntax. Trust me, other people will look at your code and some might even want to slap you for it. Anyway, don’t hate on the ternary operator. If it’s not your style, that’s fine, but you should know that it’s very useful and saves some typing. If people didn’t hate it so much, it would have saved me this blog post..but then again that would have been sort of boring.
How I Roll