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

Well, the syntax for it is horrid. I find functional ifs very useful, and often makes code more readable.

I would suggest making a macro to make it more readable, but I'm sure someone can come up with a horrible edge case (as there always is with CPP).

查看更多
骚的不知所云
3楼-- · 2018-12-31 22:23

I almost never use the ternary operator because whenever I DO use it, it always makes me think a lot more than I have to later when I try to maintain it.

I like to avoid verbosity, but when it makes the code a lot easier to pick up, I will go for the verbosity.

Consider:

String name = firstName;

if (middleName != null) {
    name += " " + middleName;
}

name += " " + lastName;

Now, that is a bit verbose, but I find it a lot more readable than:

String name = firstName + (middleName == null ? "" : " " + middleName)
    + " " + lastName;

or:

String name = firstName;
name += (middleName == null ? "" : " " + middleName);
name += " " + lastName;

It just seems to compress too much information into too little space, without making it clear what's going on. Everytime I see ternary operator used, I have always found an alternative that seemed much easier to read... then again, that is an extremely subjective opinion, so if you and your colleagues find ternary very readable, go for it.

查看更多
旧时光的记忆
4楼-- · 2018-12-31 22:23

I treat ternary operators a lot like GOTO. They have their place, but they are something which you should usually avoid to make the code easier to understand.

查看更多
孤独寂梦人
5楼-- · 2018-12-31 22:24

In my mind, it only makes sense to use the ternary operator in cases where an expression is needed.

In other cases, it seems like the ternary operator decreases clarity.

查看更多
像晚风撩人
6楼-- · 2018-12-31 22:25

I recently saw a variation on ternary operators (well, sort of) that make the standard "() ? :" variant seem to be a paragon of clarity:

var Result = [CaseIfFalse, CaseIfTrue][(boolean expression)]

or, to give a more tangible example:

var Name = ['Jane', 'John'][Gender == 'm'];

Mind you, this is Javascript, so things like that might not be possible in other languages (thankfully).

查看更多
不再属于我。
7楼-- · 2018-12-31 22:26

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

查看更多
登录 后发表回答