To ternary or not to ternary?

I'm personally an advocate of the ternary operator: () ? : ; I do realize that it has its place, but I have come across many programmers that are completely against ever using it, and some that use it too often.

What are your feelings on it? What interesting code have you seen using it?


Use it for simple expressions only :

int a = (b > 10) ? c : d;

Don't chain or nest ternary operators as it hard to read and confusing:

int a = b > 10 ? c < 20 ? 50 : 80 : e == 2 ? 4 : 8;

Moreover, when using ternary operator, consider formatting the code in a way that improve readability:

int a = (b > 10) ? some_value                 
                 : another_value;

It makes debugging slightly more difficult since you can not place breakpoints on each of the sub expressions. I use it rarely.


I love them, especially in type-safe languages.

I don't see how this:

int count = (condition) ? 1 : 0;

is any harder than this:

int count;

if (condition)
{
  count = 1;
} 
else
{
  count = 0;
}

edit -

I'd argue that ternary operators make everything less complex and more neat than the alternative.

链接地址: http://www.djcxy.com/p/42860.html

上一篇: 在Go中表示枚举的惯用方式是什么?

下一篇: 三元或不三元?