I'm personally an advocate of the ternary operator: () ? : ; I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.
What are your feelings on it? What interesting code have you seen using it?
I think the ternary operator should be used when needed. It is obviously a very subjective choice, but I find that a simple expression (specially as a return expression) is much clearer than a full test. Example in C/C++:
Compared to:
You also have the case where the solution is between the ternary operator and creating a function. For example in Python:
The alternative is:
It is needed enough that in Python (as an example), such an idiom could be seen regularly:
this line uses properties of the logical operators in Python: they are lazy and returns the last value computed if it is equal to the final state.
I like using the operator in debug code to print error values so I don't have to look them up all the time. Usually I do this for debug prints that aren't going to remain once I'm done developing.
For simple tasks like assigning a different value depending on a condition they're great. I wouldn't use them when there are longer expressions depending on the condition tho.
The Ternary
?:
operator is merely a functional equivalent of the proceduralif
construct. So as long as you are not using nested?:
expressions, the arguments for/against the functional representation of any operation applies here. But nesting ternary operations can result in code that is downright confusing (exercise for the reader: try writing a parser that will handle nested ternary conditionals and you will appreciate their complexity).But there are plenty of situations where conservative use of the
?:
operator can result in code that is actually easier to read than otherwise. For example:Now compare that with this:
As the code is more compact it there is less syntactic noise, and by using the ternary operator judiciously (that is only in relation with the reverseOrder property) the end result isn't particularly terse.
Like so many opinion questions, the answer is inevitably: it depends
For something like:
I think that is much more concise (and quicker for me to parse) than:
Now if your conditional expression is complex, then the ternary operation is not a good choice. Something like:
is not a good candidate for the ternary operator.
As an aside, if you are a C programmer, GCC actually has an extension that allows you to exclude the if-true portion of the ternary, like this:
Which will set
x
toy
assumingy
is notNULL
. Good stuff.I like Groovy's special case of the ternary operator, called the Elvis operator: ?:
This code evaluates to expr if it's not null, and default if it is. Technically it's not really a ternary operator, but it's definitely related to it and saves a lot of time/typing.