Java 声纳误差条件不应无条件评估为;“真的”;或;假;

Java 声纳误差条件不应无条件评估为;“真的”;或;假;,java,collections,sonarqube,sonar-runner,Java,Collections,Sonarqube,Sonar Runner,我受到声纳干扰: 条件不应无条件计算为“真”或“假” 对于下面的代码 List<MediaContent> savedList = source.getChildMediaContents(); List<MediaContent> supplierList = target.getChildMediaContents(); // if existing and incoming both empty if(savedList == null && su

我受到声纳干扰:

条件不应无条件计算为“真”或“假”

对于下面的代码

List<MediaContent> savedList = source.getChildMediaContents();
List<MediaContent> supplierList = target.getChildMediaContents();

// if existing and incoming both empty
if(savedList == null && supplierList == null){
    return false;
}

// if one is null and other is not then update is required
if(savedList == null && supplierList != null){
    return true;
}

if(savedList != null && supplierList == null){
    return true;
}
条件
供应商列表!=达到空值时,空值始终为真。
由于Java中
&
运算符的短路行为, 在<代码>供应商列表之前!=达到空值
savedList==null
必须首先为true

但是如果
savedList==null
为真, 然后我们从前面的条件知道,
supplierList
不是
null
,因此这是一个无意义的条件

if (savedList == null) {
    return true;
}
另一方面,如果
savedList==null
为false, 然后,由于短路行为,
供应商列表!=将不计算null

因此,无论
savedList==null的结果如何,
供应商列表!=空值
将永远不会被计算, 因此,您可以简单地删除该条件

if (savedList == null) {
    return true;
}
下一步:

由于前面的简化,现在很明显,
savedList
不能为
null
。因此,我们也可以消除这种情况:

if (supplierList == null) {
    return true;
}
简而言之,这相当于您发布的代码:

if (savedList == null && supplierList == null) {
    return false;
}

if (savedList == null || supplierList == null) {
    return true;
}

基于上述情况,您可以避免后两个if条件,并使用else情况

if(savedList == null && supplierList == null){
    return false;
} else {
    return true; // either savedList or supplierList is not null
}
或者您可以简单地让return语句删除所有if语句

return (savedList != null || supplierList != null);
您可以尝试:

if(savedList == null && supplierList == null){
  return false;
}
return true;

您甚至可以将最后两个if子句合并到
if(savedList==null | | supplierList==null)返回true
return (savedList != null || supplierList != null);
if(savedList == null && supplierList == null){
  return false;
}
return true;