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?
As others have pointed out they are nice for short simple conditions. I especially like them for defaults (kind of like the || and or usage in javascript and python), e.g.
Another common use is to initialize a reference in C++. Since references have to be declared and initialized in the same statement you can't use an if statement.
Chained I'm fine with - nested, not so much.
I tend to use them more in C simply b/c they're an if statement that has value, so it cuts down on unnecessary repetition or variables:
rather than
In assignments like this, I find it's less to refactor, and clearer.
When I'm working in ruby on the other hand, I'm more likely to use
if...else...end
because it's an expression too.(although, admittedly, for something this simple, I might just use the ternary operator anyway).
It's a question of style, really; the subconscious rules I tend to follow are:
foo = (bar > baz) ? true : false
, but NOTfoo = (bar > baz && lotto && someArray.Contains(someValue)) ? true : false
<%= (foo) ? "Yes" : "No" %>
Only really use it for assignment; never flow logic (so neverFlow logic in ternary is itself a lie, ignore that last point.(foo) ? FooIsTrue(foo) : FooIsALie(foo)
)I like it because it's concise and elegant for simple assignment operations.
If you're using the ternary operator for a simple conditional assignment I think it's fine. I've seen it (ab)used to control program flow without even making an assignment, and I think that should be avoided. Use an if statement in these cases.
I use the ternary operator where ever I can, unless it makes the code extremely hard to read, but then that's usually just an indication that my code could use a little refactoring.
It always puzzles me how some people think the ternary operator is a "hidden" feature or is somewhat mysterious. It's one of the first things I learnt when I start programming in C, and I don't think it decreases readability at all. It's a natural part of the language.
I agree with jmulder: it shouldn't be used in place of a
if
, but it has its place for return expression or inside an expression:The former is just an example, a better i18n support of plural should be used!