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.
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.I personally only use it for an assignment of a variable (in java) for example :
and (other example) when using function that doesn't allow null parameter such as :
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.
I tend not to use the ternary operator at all as I find if .. else much more readable.
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.
I tend to enclose the condition in parentheses : (a == b) ? 1 : 0