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)
Run Code Online (Sandbox Code Playgroud)if(savedList == null && supplierList == null){ return false; } if(savedList == null && supplierList != null){
supplierList != null
达到条件时始终为真。由于&&
Java中运算符的短路行为,在supplierList != null
达到之前,
savedList == null
必须首先为真。
但是,如果savedList == null
为真,那么从前面的条件中我们知道supplierList
不是null
,所以这是没有意义的条件。
另一方面,如果savedList == null
为假,则由于短路行为,supplierList != null
将不进行评估。
因此,无论的结果如何savedList == null
,
supplierList != null
都不会被评估,因此您只需删除该条件即可。
if (savedList == null) {
return true;
}
Run Code Online (Sandbox Code Playgroud)
下一个:
Run Code Online (Sandbox Code Playgroud)if(savedList != null && supplierList == null){
由于前面的简化,现在显然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)