Gary Haran.com


The Proper Use For The Ternary Operators

Posted in Programming by gary.haran on the June 8th, 2007

Ternary operators are not there so you can obfuscate your code. They are a tool to reduce the useless if-else dances. If used correctly they can help readability and maintainability greatly.

The top error I’ve seen in php code when using the ternary operator is to use it when doing an assignement.

The Improper Way

($special ? $foo = 'bar' : $foo = 'foo');

- the left of the screen where you normally read variable declarations is now polluted. To scan quickly you must read your code.
- you write more code than required

The Proper Way

$foo = $special ? 'bar' : 'foo' ;

- scanning variable declarations and assignements is easier this way.
- it’s shorter and you don’t have to add parenthesis.

One Response to 'The Proper Use For The Ternary Operators'

Subscribe to comments with RSS or TrackBack to 'The Proper Use For The Ternary Operators'.

  1. Marc-Andre said,

    on June 8th, 2007 at 3:09 pm

    There is the same semantic in Java , and it is particularly usefull to check null variable….
    For example , you want to return the result of the method foo.bar()

    return foo.bar() will generate an exception if foo is null….
    But this is perfectly good and failsafe
    return foo != null ? foo.bar() : null;

Leave a Reply