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:08

I've seen such beasts like (it was actually much worse since it was isValidDate and checked month and day as well, but I couldn't be bothered trying to remember the whole thing):

isLeapYear =
    ((yyyy % 400) == 0)
    ? 1
    : ((yyyy % 100) == 0)
        ? 0
        : ((yyyy % 4) == 0)
            ? 1
            : 0;

where, plainly, a series of if-statements would have been better (although this one's still better than the macro version I once saw).

I don't mind it for small things like:

reportedAge = (isFemale && (Age >= 21)) ? 21 + (Age - 21) / 3 : Age;

or even slightly tricky things like:

printf ("Deleted %d file%s\n", n, (n == 1) ? "" : "s");
查看更多
孤独总比滥情好
3楼-- · 2018-12-31 22:08

If you and your workmates understand what they do and they aren't created in massive groups I think they make the code less complex and easier to read because there is simply less code.

The only time i think ternary operators make code harder to understand is when you have more than 3 or 4 in one line. Most people don't remember that they are right based precedence and when you have a stack of them it makes reading the code a nightmare.

查看更多
其实,你不懂
4楼-- · 2018-12-31 22:08

(Hack of the day)

#define IF(x) x ?
#define ELSE :

Then you can do if-then-else as expression:

int b = IF(condition1)    res1
        ELSE IF(condition2)  res2
        ELSE IF(conditions3) res3
        ELSE res4;
查看更多
只靠听说
5楼-- · 2018-12-31 22:09

By the measure of cyclomatic complexity, the use of if statements or the ternary operator are equivalent. So by that measure, the answer is no, the complexity would be exactly the same as before.

By other measures such as readability, maintainability, and DRY (Don't-Repeat-Yourself), either choice may prove better than the other.

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 22:10

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;
查看更多
春风洒进眼中
7楼-- · 2018-12-31 22:11

Only when:

$var = (simple > test ? simple_result_1 : simple_result_2);

KISS.

查看更多
登录 后发表回答