Java 使用带有 4 个表达式的三元运算符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1815187/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using ternary operator with 4 expressions
提问by Brandon Coffman
Is this an acceptable coding practice?
这是一种可接受的编码实践吗?
public class MessageFormat {
private static final Color DEFAULT_COLOR = Color.RED;
private Color messageColor = DEFAULT_COLOR;
public MessageFormat(Person person) {
Color color = person.getPreferredColor();
messageColor = (color != null) ? color : messageColor; // this line
}
}
or am I better off going with the classic ...
还是我最好选择经典...
if (color != null) {
messageColor = color;
}
采纳答案by Christopher Gutteridge
Use of the ?: operator should be confined to make code more readable. A classic example:
?: 运算符的使用应仅限于使代码更具可读性。一个经典的例子:
a = sprintf( "There are %i green bottle%s on the wall.", i, (i==1?"":"s") );
In this case the code would be less readable if you broke it up into about 5 if/else lines.
在这种情况下,如果将代码分成大约 5 个 if/else 行,代码的可读性会降低。
I generally put brackets around the entire operator so that when reading it I mentally parse it as a single value.
我通常在整个运算符周围加上括号,以便在阅读它时我将其解析为单个值。
messageColor = (color != null ? color : messageColor);
Another variant is
另一种变体是
messageColor = color || messageColor;
Which in some languages will evaluate to "color, unless color evaluates to "false", in which case value of messageColor. In my opinion this should be avoided as it may confuse people.
在某些语言中,这将评估为“颜色”,除非颜色评估为“假”,在这种情况下为 messageColor 的值。在我看来,应该避免这种情况,因为它可能会使人们感到困惑。
The most important thing is to be consistent so the next person reading your code (even if it's you) has minimum cognitive overhead.
最重要的是保持一致,这样下一个阅读你代码的人(即使是你)的认知开销最小。
回答by djc
Seems fine to me (I use Python's ternary operator a lot), but this kind of style issue is usually highly subjective. If the project has a coding style document, you may want to check that.
对我来说似乎很好(我经常使用 Python 的三元运算符),但这种风格问题通常是非常主观的。如果项目有编码样式文档,您可能需要检查一下。
回答by Mark Byers
I prefer the second because it is more clearly expressing what you mean: you only want to change the color if it is not null. The first method doesn't make this so clear.
我更喜欢第二种,因为它更清楚地表达了您的意思:如果颜色不为空,您只想更改颜色。第一种方法并没有使这一点如此清楚。
回答by Gabriel Reid
Use of the ternary operator is often a sensitive issue, along with other coding standards. It's use is probably best determined by coding standards at your site.
与其他编码标准一样,三元运算符的使用通常是一个敏感问题。它的用途可能最好由您站点的编码标准决定。
However, in this specific situation I would definitely recommend the second option; not only is it more clear, but the use of the ternary operator is totally unnecessary here. There's no need to re-assign messageColor to itself, so the only function of the ternary operator in this particular situation is code obfuscation.
但是,在这种特定情况下,我肯定会推荐第二种选择;不仅更清楚,而且这里完全没有必要使用三元运算符。无需将 messageColor 重新分配给自身,因此在这种特殊情况下三元运算符的唯一功能是代码混淆。
回答by Alon
Ternary operators often get abused as the code they produce seems clever and compact.
三元运算符经常被滥用,因为它们生成的代码看起来既聪明又紧凑。
In fact they make the code less readable and more error prone. Whenever possible it is advisable to use the longer version of
事实上,它们使代码的可读性降低并且更容易出错。只要有可能,建议使用更长的版本
if ( <condition> ) {
<action> ;
}
Instead of a ternary syntax.
而不是三元语法。
回答by brianegge
The ternary operator is more common among C programmers. In C if you avoid control structures you can often getting better pipelining, as there is no branch prediction to go wrong. I doubt you would see any performance difference in Java, and the if-null-then-assign pattern is far more common than the ternary. However, if you are maintaining a existing codebase, it's usually best to stay consistent with the existing code.
三元运算符在 C 程序员中更为常见。在 C 中,如果你避免控制结构,你通常可以获得更好的流水线,因为没有分支预测会出错。我怀疑您会在 Java 中看到任何性能差异,并且 if-null-then-assign 模式比三元模式更常见。但是,如果您要维护现有代码库,通常最好与现有代码保持一致。
If you find yourself doing this a lot, you can write a defaultIfNull
, firstNonNull
or coalesce
function which may make the code even more concise. Apache Commons Lang includes a defaultIfNull
function.
如果您发现自己经常这样做,您可以编写一个defaultIfNull
,firstNonNull
或coalesce
函数,这可能会使代码更加简洁。 Apache Commons Lang 包含一个defaultIfNull
函数。
Some languages include a ||=
operator, which is the usual idiom for defaulting values in those languages.
某些语言包括||=
运算符,这是这些语言中默认值的常用习惯用法。
回答by Andreas Dolk
In your case, I'd prefer the 'classic' implementation, because to me it's faster to understand, that you only want to use a new color if the person has a preferred one.
在你的情况下,我更喜欢“经典”的实现,因为对我来说理解起来更快,如果这个人有一个喜欢的颜色,你只想使用一种新颜色。
I sometimes use it in method calls if I want to avoid NPEs, but I usually elimate those ugly pieces of code in one of the next refactorings ;)
如果我想避免 NPE,我有时会在方法调用中使用它,但我通常会在下一次重构之一中消除那些丑陋的代码;)
回答by Svante
Readability, ease of understanding etc. are the same in this case (I mean, come on...). I don't like the duplication and apparent self assignment in the first example; it would translate to something like:
在这种情况下,可读性、易于理解等是相同的(我的意思是,来吧......)。我不喜欢第一个例子中的重复和明显的自我分配;它会转化为类似的东西:
if (colour != null) {messageColour = colour;}
else {messageColour = messageColour;};
which is a bit stupid.
这有点愚蠢。
I would usually write the second in one line, but that's a question of individual fancy resp. coding style guidelines:
我通常会在一行中写第二个,但这是个人幻想的问题。编码风格指南:
if (colour != null) {messageColour = colour;};
EDIT(I am now more opinionated than 8 years ago)
编辑(我现在比 8 年前更有主见)
Since you are looking for best practices:
由于您正在寻找最佳实践:
// Use default visibility by default, especially in examples.
// Public needs a reason.
class MessageFormat {
static final Color DEFAULT_COLOR = Color.RED;
// Strongly prefer final fields.
private final Color messageColor;
// Protect parameters and variables against abuse by other Java developers
MessageFormat (final Person person) {
// Use Optionals; null is a code smell
final Optional<Color> preferredColor = person.getPreferredColor();
// Bask in the clarity of the message
this.messageColor = preferredColor.orElse(DEFAULT_COLOR);
}
}