将三元运算符与 4 个表达式一起使用
这是可接受的编码实践吗?
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
}
}
或者我最好选择经典的......
if (color != null) {
messageColor = color;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
应限制 ?: 运算符的使用,以使代码更具可读性。一个经典的例子:
在这种情况下,如果将代码分成大约 5 个 if/else 行,代码的可读性就会降低。
我通常将整个运算符放在括号中,以便在阅读它时我在心里将其解析为单个值。
另一种变体是
,在某些语言中,它会计算为“颜色”,除非颜色计算为“假”,在这种情况下,值为 messageColor。在我看来,应该避免这种情况,因为它可能会让人们感到困惑。
最重要的是保持一致,以便下一个人阅读你的代码(即使是你)的认知开销最小。
Use of the ?: operator should be confined to make code more readable. A classic example:
In this case the code would be less readable if you broke it up into about 5 if/else lines.
I generally put brackets around the entire operator so that when reading it I mentally parse it as a single value.
Another variant is
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.
The most important thing is to be consistent so the next person reading your code (even if it's you) has minimum cognitive overhead.
在这种情况下,可读性、易于理解性等都是相同的(我的意思是,来吧......)。我不喜欢第一个示例中的重复和明显的自我分配;它会翻译成这样:
这有点愚蠢。
我通常会把第二个写在一行中,但这是个人喜好的问题。编码风格指南:
编辑(我现在比 8 年前更加固执己见)
因为您正在寻找最佳实践:
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:
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:
EDIT (I am now more opinionated than 8 years ago)
Since you are looking for best practices:
三元运算符的使用以及其他编码标准通常是一个敏感问题。它的使用可能最好由您站点的编码标准决定。
然而,在这种具体情况下,我肯定会推荐第二种选择;不仅更加清晰,而且这里完全不需要使用三元运算符。不需要将 messageColor 重新分配给自身,因此在这种特殊情况下三元运算符的唯一功能是代码混淆。
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.
三元运算符在 C 程序员中更为常见。在 C 语言中,如果避免控制结构,通常可以获得更好的流水线,因为没有分支预测会出错。我怀疑您会看到 Java 中的任何性能差异,并且 if-null-then-assign 模式比三元模式更常见。但是,如果您正在维护现有的代码库,通常最好与现有代码保持一致。
如果您发现自己经常这样做,则可以编写
defaultIfNull
、firstNonNull
或coalesce
函数,这可能会使代码更加简洁。 Apache Commons Lang 包含一个defaultIfNull
函数。某些语言包含一个
||=
运算符,这是这些语言中默认值的常用习惯用法。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.
If you find yourself doing this a lot, you can write a
defaultIfNull
,firstNonNull
orcoalesce
function which may make the code even more concise. Apache Commons Lang includes adefaultIfNull
function.Some languages include a
||=
operator, which is the usual idiom for defaulting values in those languages.我更喜欢第二个,因为它更清楚地表达了您的意思:您只想在颜色不为空时更改颜色。第一种方法并没有把这一点说得那么清楚。
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.
就您而言,我更喜欢“经典”实现,因为对我来说,理解起来更快,如果用户有首选颜色,您只想使用新颜色。
如果我想避免 NPE,有时我会在方法调用中使用它,但我通常会在接下来的重构之一中消除那些丑陋的代码片段;)
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 ;)
三元运算符经常被滥用,因为它们生成的代码看起来聪明而紧凑。
事实上,它们使代码的可读性降低并且更容易出错。
只要有可能,建议使用较长版本的
而不是三元语法。
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
Instead of a ternary syntax.
对我来说似乎很好(我经常使用Python的三元运算符),但这种风格问题通常是非常主观的。如果项目有编码风格文档,您可能需要检查它。
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.