Benefits of using the conditional ?: (ternary) operator
What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:
Conditional ?: Operator
Standard If/Else
Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given that I work with many non-programmers?
I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.
Good example:
int result = Check() ? 1 : 0;
Bad example:
int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
This is pretty much covered by the other answers, but "it's an expression" doesn't really explain why that is so useful...
In languages like C++ and C#, you can define local constants (within a method body) using them. This is not possible with a conventional if/then statement because the value of a const all has to be assigned within that single statement:
const int speed = (shiftKeyDown) ? 10 : 1;
is not the same as:
const int speed;
if (shifKeyDown)
speed = 10; // error - can't assign to a const
else
speed = 1; // error
In a similar way you can embed a tertiary expression in other code. As well as making the source code more compact (and in some cases more readable as a result) it can also make the generated machine code more compact and efficient:
MoveCar((shiftKeyDown) ? 10 : 1);
...may generate less code than having to call the same method twice:
if (shiftKeyDown)
MoveCar(10);
else
MoveCar(1);
Of course, it's also a more convenient and concise form (less typing, less repetition, and can reduce the chance of errors if you have to duplicate chunks of code in an if/else). In clean "common pattern" cases like this:
object thing = (reference == null) ? null : reference.Thing;
... it is simply faster to read/parse/understand (once you're used to it) than the long-winded if/else equivalent, so it can help you to 'grok' code faster.
Of course, just because it is useful does not mean it is the best thing to use in every case. I'd advise only using it for short bits of code where the meaning is clear (or made more clear) by using ?:
- if you use it in more complex code, or nest ternary operators within each other it can make code horribly difficult to read.
如果我想要将变量设置为在请求中发送的值(如果已定义),或者将某个变量设置为默认值(如果未定义),那么我发现它在Web开发中特别有用。
链接地址: http://www.djcxy.com/p/53860.html上一篇: 空条件操作符
下一篇: 使用条件?:(三元)运算符的好处