To ternary or not to ternary? [closed]

2018-12-31 21:49发布

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?

30条回答
裙下三千臣
2楼-- · 2018-12-31 22:27

I think the ternary operator should be used when needed. It is obviously a very subjective choice, but I find that a simple expression (specially as a return expression) is much clearer than a full test. Example in C/C++:

return (a>0)?a:0;

Compared to:

if(a>0) return a;
else return 0;

You also have the case where the solution is between the ternary operator and creating a function. For example in Python:

l = [ i if i > 0 else 0 for i in lst ]

The alternative is:

def cap(value):
    if value > 0:
        return value
    return 0
l = [ cap(i) for i in lst ]

It is needed enough that in Python (as an example), such an idiom could be seen regularly:

l = [ ((i>0 and [i]) or [0])[0] for i in lst ]

this line uses properties of the logical operators in Python: they are lazy and returns the last value computed if it is equal to the final state.

查看更多
听够珍惜
3楼-- · 2018-12-31 22:28

I like using the operator in debug code to print error values so I don't have to look them up all the time. Usually I do this for debug prints that aren't going to remain once I'm done developing.

int result = do_something();
if( result != 0 )
{
  debug_printf("Error while doing something, code %x (%s)\n", result,
                result == 7 ? "ERROR_YES" :
                result == 8 ? "ERROR_NO" :
                result == 9 ? "ERROR_FILE_NOT_FOUND" :
                "Unknown");
}
查看更多
牵手、夕阳
4楼-- · 2018-12-31 22:31

For simple tasks like assigning a different value depending on a condition they're great. I wouldn't use them when there are longer expressions depending on the condition tho.

查看更多
泪湿衣
5楼-- · 2018-12-31 22:33

The Ternary ?: operator is merely a functional equivalent of the procedural if construct. So as long as you are not using nested ?: expressions, the arguments for/against the functional representation of any operation applies here. But nesting ternary operations can result in code that is downright confusing (exercise for the reader: try writing a parser that will handle nested ternary conditionals and you will appreciate their complexity).

But there are plenty of situations where conservative use of the ?: operator can result in code that is actually easier to read than otherwise. For example:

int compareTo(Object object) {
    if((isLessThan(object) && reverseOrder) || (isGreaterThan(object) && !reverseOrder)) {
       return 1;
    if((isLessThan(object) && !reverseOrder) || (isGreaterThan(object) && reverseOrder)) {
       return -1;
    else
      return 0;              
}

Now compare that with this:

int compareTo(Object object) {
    if(isLessThan(object))
        return reverseOrder ? 1 : -1;         
    else(isGreaterThan(object))
        return reverseOrder ? -1 : 1;
    else        
       return 0;              
}

As the code is more compact it there is less syntactic noise, and by using the ternary operator judiciously (that is only in relation with the reverseOrder property) the end result isn't particularly terse.

查看更多
看淡一切
6楼-- · 2018-12-31 22:33

Like so many opinion questions, the answer is inevitably: it depends

For something like:

return x ? "Yes" : "No";

I think that is much more concise (and quicker for me to parse) than:

if (x) {
    return "Yes";
} else {
    return "No";
}

Now if your conditional expression is complex, then the ternary operation is not a good choice. Something like:

x && y && z >= 10 && s.Length == 0 || !foo

is not a good candidate for the ternary operator.

As an aside, if you are a C programmer, GCC actually has an extension that allows you to exclude the if-true portion of the ternary, like this:

/* 'y' is a char * */
const char *x = y ? : "Not set";

Which will set x to y assuming y is not NULL. Good stuff.

查看更多
零度萤火
7楼-- · 2018-12-31 22:35

I like Groovy's special case of the ternary operator, called the Elvis operator: ?:

expr ?: default

This code evaluates to expr if it's not null, and default if it is. Technically it's not really a ternary operator, but it's definitely related to it and saves a lot of time/typing.

查看更多
登录 后发表回答