声纳错误条件不应无条件地评估为“ TRUE”或“ FALSE”

use*_*479 4 java collections sonar-runner sonarqube

我越来越违反声纳:

“条件不应无条件地评估为“ TRUE”或“ FALSE””

对于下面的代码。

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;
}
Run Code Online (Sandbox Code Playgroud)

在两个if块下面,它给出错误

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Sto*_*ica 5

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

if(savedList == null && supplierList != null){
Run Code Online (Sandbox Code Playgroud)

supplierList != null达到条件时始终为真。由于&&Java中运算符的短路行为,在supplierList != null达到之前, savedList == null必须首先为真。

但是,如果savedList == null为真,那么从前面的条件中我们知道supplierList不是null,所以这是没有意义的条件。

另一方面,如果savedList == null为假,则由于短路行为,supplierList != null将不进行评估。

因此,无论的结果如何savedList == nullsupplierList != null都不会被评估,因此您只需删除该条件即可。

if (savedList == null) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)

下一个:

if(savedList != null && supplierList == null){
Run Code Online (Sandbox Code Playgroud)

由于前面的简化,现在显然savedList不能null。因此我们也可以删除该条件:

if (supplierList == null) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)

简而言之,这等效于您发布的代码:

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

if (savedList == null || supplierList == null) {
    return true;
}
Run Code Online (Sandbox Code Playgroud)