Which coding style you use for ternary operator? [

2019-01-07 08:18发布

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.

15条回答
欢心
2楼-- · 2019-01-07 08:27

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.

查看更多
Viruses.
3楼-- · 2019-01-07 08:27

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);
查看更多
贪生不怕死
4楼-- · 2019-01-07 08:29

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.

查看更多
成全新的幸福
5楼-- · 2019-01-07 08:29

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

查看更多
时光不老,我们不散
6楼-- · 2019-01-07 08:33

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.

查看更多
仙女界的扛把子
7楼-- · 2019-01-07 08:34

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

查看更多
登录 后发表回答