views:

2487

answers:

14

I keep it in single line, if it's short. Lately I've been using this style for longer or nested ternary operator expressions. A contrived example:

$value = ( $a == $b ) 
            ? 'true value # 1'
            : ( $a == $c )
                ? 'true value # 2'
                : 'false value';

Personally which style you use, or find most readable?

Edit: (on when to use ternary-operator)

I usually avoid using more than 2 levels deep ternary operator. I tend prefer 2 levels deep ternary operator over 2 level if-else, when I'm echoing variables in PHP template scripts.

+1  A: 

I don't use it. It always smelled to me like trying to save space and typing in source code with the expectation that small source == more efficient compiled code.

I don't find it readable at all, but much of that is because I just never use it.

Tim
Heh. This is dead on, and that whole attitude pervades the design of C. Arrays == pointers, the comma operator, and the pre and post increment and decrement operators are other sterling examples.This is one of the reasons why I think Ada is better. It was designed for producing maintainable code
T.E.D.
A: 

I tend not to use the ternary operator at all as I find if .. else much more readable.

Shane MacLaughlin
+16  A: 

Personally, I only use the ternary operator if it fits on one line. If it need to span, then it's time for the good old

if else if else
biozinc
+6  A: 

ternary operators are short effective ways to write simple if statements. They shouldn't be nested or difficult to read. Remember: You write the software once but is is read 100 times. It should be easier to read than write.

Rick Kierner
+1  A: 

I'll dissent with the common opinion. I'm sort of like Imran with my conditional operator style. If it fits cleanly on one line, I keep it on one line. If it doesn't fit cleanly on one line, I do break it, but I use only a single tab (4 spaces; I have VS set to insert spaces for tabs) for the indent. I don't immediately jump to if-else, because a lot of the time the conditional operator makes more sense contextually. (If it doesn't make sense contextually, however, I simply don't use it.)

Also, I don't nest conditional operators. At that point, I do find it too difficult to read, and it's time to go to the more verbose if-else style.

John Rudy
+36  A: 

I try not to use a ternary operator to write nested conditions. It defies readability and provides no extra value over using a conditional.

Only if it can fit on a single line, and it's crystal-clear what it means, I use it:

$value = ($a < 0) ? 'minus' : 'plus';
Tomalak
100% agreed. and ONLY if the operator is used as a single statement and ONLY if it's less than 80 chars, including indentation.at a previous employer, the previous lead dev liked to use the ternary op in the middle of 1k echo statements. EVIL. I outlawed its use altogether in that codebase.
jcoby
+3  A: 

I tend to enclose the condition in parentheses : (a == b) ? 1 : 0

Guillaume Gervais
I tend to do that, too.
John Rudy
A: 

Imran, you have formatted this beautifully. However, the ternary operator does tend to get unreadable as you nest more than two. an if-else block may give you an extra level of comprehensible nesting. Beyond that, use a function or table-driven programming.

Yuval F
+24  A: 

The ternary operator is generally to be avoided, but this form can be quite readable:

  result = (foo == bar)  ? result1 :
           (foo == baz)  ? result2 :
           (foo == qux)  ? result3 :
           (foo == quux) ? result4 : 
                           fail_result;

This way, the condition and the result are kept together on the same line, and it's fairly easy to skim down and understand what's going on.

Simon Howard
If I'd really *have* to use it, I'd probably use this layout. +1
Tomalak
If I'd have to use it this way, I'd use a switch statement.
Nouveau
In this particular situation, you could use a switch statement, as they're == comparisons, but they could be any expressions. In the general case, a switch statement isn't always possible.
Simon Howard
This is why I think more languages need a "select" construct which is to "switch" as the ternary operator is to if/else. Basically, it's a control structure that returns a value. I've only ever seen it in VHDL, and I think Matlab.
rmeador
I consider syntactic sugar misused a code smell. Nesting ternaries definitively falls into this category.
Tomalak
@Nouveau: you can't use a switch if bar, baz, qux and quux are not constants -- certainly not in the majority of languages.
Jonathan Leffler
@meador: Take a look at Ruby. :)
unwind
Which more or less defines "not in the majority of languages". :-D
Tomalak
@rmeador: So you're thinking of something like lisp's COND, then?(setq foo 3)(cond ((>= foo 4) 'result1) ((= foo 3) 'result2) ((= foo 2) 'result3) ((<= foo 1) 'result4))returns result2.
Hm... SO's comments clobber newlines. Imagine that COND well-formatted.
This structure needs alot more parenthesis before it will work correctly in PHP!
too much php
@simon, you can use a switch statement like `switch(true)` then put an expression to be evaluated in each `case`.
John Isaacks
@John - erm, no, you can't, at least in curly braces languages. The expressions in the case statement have to reduce to an integer constant.
Simon Howard
@Simon then I must be using a magic version of PHP.
John Isaacks
A: 
$foo = (isset($bar)) ? $bar : 'default';
A: 

I personally only use it for an assignment of a variable (in java) for example :

String var = (obj == null) ? "not set" : obj.toString();

and (other example) when using function that doesn't allow null parameter such as :

String val; [...]
int var = (val == null) ? 0 : Integer.parseInt(val);
Vinze
+2  A: 

a style I sometimes use, which I'm bringing up since it hasn't been mentioned, is like this:

$result = ($x == y)
        ? "foo"
        : "bar";

..but usually only if putting it all on one line makes it too long. I find that having the = ? : all line up makes it look neater.

nickf
A: 

The "contrived example" is how I would indent it, except that I would indent from the left margin, not based on where the ( or whatever is on the line above.

To the ternary detractors - readability is the point. If you don't think it makes for more readable code, don't use it. But I find the contrary to be the case at least some of the time.

ysth
A: 

PHP nested ternary operators behave differently.

This syntax passes all the following tests. Based on http://deadlytechnology.com/web-development-tips/php-ternary-syntax/

$myvar = ($x == $y)
?(($x == $z)?'both':'foo')
:(($x == $z)?'bar':'none');

.

See: http://au.php.net/ternary

Example #3 "Non-obvious Ternary Behaviour" explains why the following does not work in PHP.

$x = 1;
$y = 2;
$z = 3;   
$myvar = ($x == $y) 
       ? "foo" 
       : ($x == $z) 
         ? "bar" 
         : "none";  
$myvar == 'none'; // Good

$x = 1;
$y = 2;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Good

$x = 1;
$y = 1;
$z = 3;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!

$x = 1;
$y = 1;
$z = 1;   
$myvar = ($x == $y) ? "foo" : ($x == $z) ? "bar" : "none";  
$myvar == 'bar'; // Bad!
Chris Jacob