Sonar error Conditions should not unconditionally

2019-07-02 00:38发布

问题:

I am getting sonar violation:

"Conditions should not unconditionally evaluate to "TRUE" or to "FALSE""

for the code below.

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;
}

Below the two if blocks it is giving an error

// 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;
}

回答1:

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

if(savedList == null && supplierList != null){

The condition supplierList != null is always true when reached. Due to the short-circuiting behavior of the && operator in Java, before supplierList != null is reached, savedList == null must be true first.

But if savedList == null is true, then we know from the previous condition that supplierList is not null, so it's a pointless condition.

On the other hand, if savedList == null is false, then the due to the short-circuiting behavior, the supplierList != null will not be evaluated.

Thus, regardless of the outcome of savedList == null, supplierList != null will never be evaluated, so you can simply remove that condition.

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

Next:

if(savedList != null && supplierList == null){

Thanks to the simplification earlier, now it's clear that savedList cannot be null. So we can remove that condition too:

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

In short, this is equivalent to your posted code:

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

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


回答2:

Based on the above you avoid the second two if conditions and have an else case

if(savedList == null && supplierList == null){
    return false;
} else {
    return true; // either savedList or supplierList is not null
}

or you can simply have return statement removing all the if statements

return (savedList != null || supplierList != null);