Which coding style you use for ternary operator?

52,008

Solution 1

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.

Solution 2

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';

Solution 3

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

Solution 4

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.

Solution 5

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!
Share:
52,008
Imran
Author by

Imran

Updated on July 05, 2022

Comments

  • Imran
    Imran almost 2 years

    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.

  • Tomalak
    Tomalak over 15 years
    If I'd really have to use it, I'd probably use this layout. +1
  • pilsetnieks
    pilsetnieks over 15 years
    If I'd have to use it this way, I'd use a switch statement.
  • Simon Howard
    Simon Howard over 15 years
    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.
  • rmeador
    rmeador over 15 years
    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.
  • T.E.D.
    T.E.D. over 15 years
    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
  • Tomalak
    Tomalak over 15 years
    I consider syntactic sugar misused a code smell. Nesting ternaries definitively falls into this category.
  • Jonathan Leffler
    Jonathan Leffler over 15 years
    @Nouveau: you can't use a switch if bar, baz, qux and quux are not constants -- certainly not in the majority of languages.
  • unwind
    unwind over 15 years
    @meador: Take a look at Ruby. :)
  • jcoby
    jcoby over 15 years
    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.
  • Tomalak
    Tomalak over 15 years
    Which more or less defines "not in the majority of languages". :-D
  • Admin
    Admin over 15 years
    @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.
  • Admin
    Admin over 15 years
    Hm... SO's comments clobber newlines. Imagine that COND well-formatted.
  • Theo Orphanos
    Theo Orphanos over 14 years
    This structure needs alot more parenthesis before it will work correctly in PHP!
  • JD Isaacks
    JD Isaacks over 13 years
    @simon, you can use a switch statement like switch(true) then put an expression to be evaluated in each case.
  • Simon Howard
    Simon Howard over 13 years
    @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.
  • JD Isaacks
    JD Isaacks over 13 years
    @Simon then I must be using a magic version of PHP.
  • Zak Henry
    Zak Henry over 12 years
    Take heed! Nested ternaries in PHP are a tricky beast. Probably advised to steer clear of them, but we all like to dice with the tricky.
  • Ryall
    Ryall about 12 years
    "The ternary operator is generally to be avoided" - Why? This seems more like an opinion rather than a rule. The ternary operator is a useful tool in many situations where an if-else would seem like overkill. Maybe we should also avoid PHP, because people don't know how to use that properly too?
  • Apostle
    Apostle about 11 years
    Why? There is precedence (priority) of operators. For C++, PHP, ...
  • ICoffeeConsumer
    ICoffeeConsumer almost 11 years
    I compared my if-block to its alternative as a ternary statement, and when the ternary had some formatting (parens, spacing, etc), it was 20 bytes larger than my if-block, and it was practically unreadable. When I optimized the ternary (but not the if-block), it was only two bytes smaller than the if-block and even less readable than before.
  • jurchiks
    jurchiks almost 11 years
    Makes it easier to discern the condition from the true/false statements. I put parentheses around any and all conditions in my code.
  • jurchiks
    jurchiks almost 11 years
    I style it the same except I don't line them up (I only indent with tabs, I don't mix tabs and spaces together, bad style IMO).
  • Emanuil Rusev
    Emanuil Rusev over 10 years
    @pilsetnieks, Ternary operators have return values. Switch statements don't. In the code above, result would always be defined. The code that would follow could rely on that. In a switch statement result wold be less reliable as it would depend on each individual switch case.
  • user2880616
    user2880616 about 7 years
    Its easy to pooh-pooh nested ternary operators, but if you're writing an Automapper configuration and you need an expression that's supported by Linq-to-SQL, suddenly they don't seem so bad.
  • neaumusic
    neaumusic over 6 years
    this is not nesting, nesting is when you have more than one consecutive conditions, rather than falling back immediately
  • cmeza
    cmeza over 2 years
    Readability is king, IMO. I love this quote.