Sonar error Conditions should not unconditionally evaluate to “TRUE” or to “FALSE”

故事扮演 提交于 2019-12-07 07:10:24

问题


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



回答3:


You can try:

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


来源:https://stackoverflow.com/questions/41228788/sonar-error-conditions-should-not-unconditionally-evaluate-to-true-or-to-fals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!