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?
A so many answers have said, it depends. I find that if the ternary comparison is not visible in a quick scan down the code, then it should not be used.
As a side issue, I might also note that its very existence is actually a bit of an anomoly due to the fact that in C, comparison testing is a statement. In Icon, the
if
construct (like most of Icon) is actually an expression. So you can do things like:... which I find much more readable than a ternery comparison operator. :-)
There was a discussion recently about the possibility of adding the
?:
operator to Icon, but several people correctly pointed out that there was absolutely no need because of the wayif
works.Which means that if you could do that in C (or any of the other languages that have the ternery operator), then you wouldn't, in fact, need the ternery operator at all.
I use it quite often in places where I'm constrained to work in a constructor - for example, the new .NET 3.5 LINQ to XML constructs - to define default values when an optional parameter is null.
Contrived example:
or (thanks asterite)
No matter whether you use the ternary operator or not, making sure your code is readable is the important thing. Any construct can be made unreadable.
For simple if cases, I like to use it. Actually it's much easier to read/code for instance as parameters for functions or things like that. Also to avoid the new line I like to keep with all my if/else.
Neseting it would be a big NO-NO in my book.
So, resuming, for a single if/else I'll use the ternary operator. For other cases a regular if/else if/else (or switch)
I typically use in things like this:
I love them, especially in type-safe languages.
I don't see how this:
is any harder than this:
edit -
I'd argue that ternary operators make everything less complex and more neat than the alternative.
I like 'em. I don't know why, but I feel very cool when I use the ternary expression.