eclipse if(x!=y) vs if(x==y)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13257272/
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
if(x!=y) vs if(x==y)
提问by someone
I have run the PMD pluginin Eclipse against my code and I'm getting a high priority warning for code similar to the one shown below:
我已经在 Eclipse 中针对我的代码运行了PMD 插件,并且我收到了类似于下面显示的代码的高优先级警告:
if(singleRequest !=null){
// do my work
}else{
// do my other work
}
PMD says `Avoid if (x != y) ..; else ..
;
PMD 说`Avoid if (x != y) ..; else ..
;
And the description of the error looks like this:
错误的描述如下所示:
In an "if" expression with an "else" clause, avoid negation in
the test. For example, rephrase:
if (x != y) diff(); else same();
as:
if (x == y) same(); else diff();
Most "if (x != y)" cases without an "else" are often return
but I still can't understand the impact on my code. If someone could guide me with an example, I would appreciate it.
但我仍然无法理解对我的代码的影响。如果有人能用一个例子来指导我,我将不胜感激。
回答by Steven Schlansker
A number of PMD rules are more style opinions than correctness alerts. If you don't agree with this rule or the rule doesn't match your project's coding standards, you could consider suppressing warningsor even configuring PMD to enforce only the rules you like
许多 PMD 规则比正确性警报更具风格。如果您不同意此规则或该规则与您项目的编码标准不匹配,您可以考虑取消警告甚至配置 PMD 以仅执行您喜欢的规则
回答by someone
PMD is a tool. PMD works based on heuristics. Someone decided upon this heuristic; that negative conditionalswith else statements are not "good style".
PMD 是一种工具。PMD 基于启发式工作。有人决定采用这种启发式方法;带有 else 语句的否定条件不是“好的风格”。
However, in this case, as I have argued in my comments, the code posted is how Iwould write it. (In particular with x != null
, but not exclusively to this construct.)
但是,在这种情况下,正如我在评论中所争论的那样,发布的代码就是我将如何编写它。(特别是与x != null
,但不仅限于此构造。)
This is because I don't look at the conditional(excepting as it can be simplified; e.g. removing double-negatives as shown by Jim Kin) but rather I look at the logic of the branchesor "flow".
这是因为我不看条件(除非它可以被简化;例如删除双否定,如 Jim Kin 所示),而是我看分支或“流程”的逻辑。
That is, I place the positive branchfirst. In this case I contend that
也就是说,我先放置正分支。在这种情况下,我认为
if (x != null) {
doValid // positive branch
} else {
doFallback
}
is semantically equivalent to
在语义上等同于
if (isValid(x)) { // it looks like a "positive conditional" now
doValid // still positive branch
} else {
doFallback
}
and is thus positive branchfirst.
因此首先是正分支。
Of course, not all situations have such a "clear" positive flow, and some expressions might be expressed much easier in a negative manner. In these cases I will "invert" the branches - similar to what PMD is suggesting - usually with a comment stating the action at the top of the block if the positive branch/flow was reversed.
当然,并非所有情况都有如此“清晰”的积极流程,有些表达可能更容易以消极方式表达。在这些情况下,我将“反转”分支 - 类似于 PMD 所建议的 - 通常会在块顶部添加注释,说明如果正分支/flow 被反转。
Another factor that may influence the conditional choice used is "immediate scope exiting" branches like:
另一个可能影响使用的条件选择的因素是“立即范围退出”分支,例如:
if (x == null) {
// return, break, or
throw new Exception("oops!");
} else {
// But in this case, the else is silly
// and should be removed for clarity (IMOHO) which,
// if done, avoids the PMD warning entirely
}
This is how Iconsistently(a few occasional exceptions aside) write mycode: if (x != null) { .. }
. Use the tools available; and make them work foryou. See Steven's answer for how PMD can be configured to a more suitable "taste" here.
这就是我一直(少数偶然的例外除外)写我的代码:if (x != null) { .. }
。使用可用的工具;并让它们为你工作。请参阅史蒂文的回答,了解如何将 PMD 配置为更合适的“口味”。
回答by Bob Kaufman
It's a readability issue. Consider
这是一个可读性问题。考虑
if ( x != y )
{
}
else // "if x doesn't not equal y"
{
}
vs.
对比
if ( x == y )
{
}
else // "if x doesn't equal y"
{
}
The latter example is more immediately identifiable. Mind you, I see nothing wrong with using negatives... it can make a lot more sense, consider
后一个例子更容易识别。请注意,我认为使用否定词没有错……它可以更有意义,请考虑
if ( x != null )...
回答by Jin Kim
The only reason I would avoid using the negative-case is if it resulted in double-negatives, which might be confusing.
我避免使用否定案例的唯一原因是它是否会导致双重否定,这可能会令人困惑。
e.g.
例如
if (!checkbox.disabled) {
// checkbox is enabled
}
else {
// checkbox is disabled
}
回答by Aki Suihkonen
Who reads your code? You do. The compiler does. Or maybe the assistant of the lecturer. A co-worker, who can't make difference between == and != ? Hope not.
谁读了你的代码?你做。编译器可以。或者也许是讲师的助手。一个无法区分 == 和 != 的同事?希望不是。
I can only think negatives being bad in complex expressions. (Context being: at least for me. I know I've frustrated in debugging in my head while(!expr && !expr2 || expr3) { }
)
我只能认为在复杂的表达中否定是不好的。(上下文是:至少对我而言。我知道我在调试时感到沮丧while(!expr && !expr2 || expr3) { }
)
ch=getch(); if (ch!='a')
is a pattern that is easily extended toif (ch!='a' || ch!='b')
which is always true, while sounding semantically correct.
ch=getch(); if (ch!='a')
是一种易于扩展的模式,if (ch!='a' || ch!='b')
它始终为真,同时在语义上听起来是正确的。
From performance standpoint, it's best to sort the probabilities.
从性能的角度来看,最好对概率进行排序。
if (more_probable) {
....
unconditional_jump_to_end_of_block;
} else {
...
}
This choice should lead to better performance, as the there is no mis-prediction penalty in the more probable branch.
这种选择应该会带来更好的性能,因为在更可能的分支中没有错误预测惩罚。
if (p && p->next)
evaluated from performance standpoint gives poor results.
if (p && p->next)
从性能的角度评估得出的结果很差。
回答by user1700184
You have to avoid having "not equals" in the if condition. This is because when someone else looks at your code, there is a real possibility that the person might ignore the != and might jump to wrong conclusion about the logic of your program.
您必须避免在 if 条件中使用“不等于”。这是因为当其他人查看您的代码时,该人很有可能会忽略 != 并可能对您的程序逻辑得出错误的结论。
For your case, you may have to interchange the if logic with else logic and change != to ==
对于您的情况,您可能需要将 if 逻辑与 else 逻辑交换并将 != 更改为 ==
回答by Alex
It's a balancing case of code readability vs. code organization. The warning is basically suggesting that it's confusing for people reading the code to navigate the negation of a negative.
这是代码可读性与代码组织的平衡案例。该警告基本上表明人们阅读代码以导航否定的否定是令人困惑的。
My personal rule of thumb is, whatever you expect to be the "normal" case is what you should test for in the if. Consider:
我个人的经验法则是,无论您期望“正常”情况是什么,您都应该在 if 中进行测试。考虑:
if (x != y) {
// do work here...
} else {
throw new IllegalArgumentException();
}
In this situation I'd say that the important work is being done in the x != y
case, so that's what you should test for. This is because I like to organize code so that the important work comes first, followed by handling for exceptional cases.
在这种情况下,我会说这个x != y
案例中的重要工作正在完成,所以这就是您应该测试的内容。这是因为我喜欢组织代码,让重要的工作在前,然后处理异常情况。
回答by Bohemian
It's because "good style" says that if possible tests should be "positive", so:
这是因为“良好的风格”说,如果可能的话,测试应该是“积极的”,所以:
if (singleRequest == null){
// do my other work
} else {
// do my work
}
Is easier to read because the test is "positive" (ie "equals" not "not equals"), and ultimately better readability leads to less bugs.
更容易阅读,因为测试是“肯定的”(即“等于”而不是“不等于”),最终更好的可读性会导致更少的错误。
Edited
已编辑
This is particularly the case with test like:
对于像这样的测试来说尤其如此:
if (!str.equals("foo")) {
you can easily miss the !
at the front, but if you make the test positive, it's a lot cleaner.
您很容易错过!
前面的 ,但如果您使测试呈阳性,则它会干净得多。
The only time you should have a negative test is when there's no else
block - then a negative test is unavoidable unless you have an empty true
block, which itself is considered a style problem.
唯一应该进行否定测试的时间是在没有else
块时 - 那么否定测试是不可避免的,除非您有一个空true
块,这本身被认为是一个样式问题。
回答by Hubert Grzeskowiak
Not really an answer, but you can minimise the overall complexity and improve readability by returning or failing early and then continuing without indentation:
不是真正的答案,但您可以通过提前返回或失败然后继续而不缩进来最小化整体复杂性并提高可读性:
if (something == null) {
throw new IllegalArgumentException("something must not be null");
}
// continue here