gpt4 book ai didi

java - 声纳 - 条件不应无条件评估为 "TRUE"或 "FALSE"

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:35:36 25 4
gpt4 key购买 nike

你好我写了下面的代码来检查列表是否相等

 private  boolean equalTypeLists(List<Type> one, List<Type> two){
if (one == null && two == null){
return true;
}
if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}
one = new ArrayList<>(one);
two = new ArrayList<>(two);

Collections.sort(one, new Comparator<Type>() {
@Override
public int compare(Type o1, Type o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Collections.sort(two, new Comparator<Type>() {
@Override
public int compare(Type o1, Type o2) {
return o1.getValue().compareTo(o2.getValue());
}
});

return checkForTwoEqualTypeLists(one,two);
}

但 Sonar 正在为以下代码行提供 Blocker 消息“条件不应无条件地评估为“TRUE”或“FALSE””

if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}

请你帮我解决上述情况。

最佳答案

来自 sonar website :

条件不应无条件地评估为“真”或“假”

Conditional statements using a condition which cannot be anything but FALSE have the effect of making blocks of code non-functional. If the condition cannot evaluate to anything but TRUE, the conditional statement is completely redundant, and makes the code less readable.

It is quite likely that the code does not match the programmer's intent. Either the condition should be removed or it should be updated so that it does not always evaluate to TRUE or FALSE.

最后一句有助于确定要带来的更正:

要么删除该条件,要么对其进行更新,使其不总是求值为 TRUE 或 FALSE。

在您的情况下,Sonar 发现的违反规则的条件语句不应更新,而应删除,因为即使它们是正确的,它们也是多余的。


在这段代码中,如果if语句为false,则表示至少有一个两个 (甚至可能两者)不是 null :

if (one == null && two == null){
return true;
}

但是在第二个 if 语句中,你重复这个测试:

if((one == null && two != null)
|| one != null && two == null
|| one.size() != two.size()){
return false;
}

检查 != null 在这里:(one == null && two != null)one != null && two == null 不是必需的,因为我们知道当我们到达此代码时,如果其中一个(onetwo)为 null,则另一个one 不一定是 null(第一个 if 语句的结论)。

所以这应该足够了:

if (one == null && two == null){
return true;
}

if(one == null || two == null || one.size() != two.size()){
return false;
}

关于java - 声纳 - 条件不应无条件评估为 "TRUE"或 "FALSE",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43185209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com