声纳错误条件不应无条件地评估为“真”。或“假”; [英] Sonar error Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"
问题描述
我正在违反声纳:
条件不应无条件地评估为 TRUE或 FALSE
"Conditions should not unconditionally evaluate to "TRUE" or to "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;
}
在两个if块下面,它给出了错误
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;
}
推荐答案
if(savedList == null && supplierList == null){
return false;
}
if(savedList == null && supplierList != null){
条件 supplierList!= null
始终为true。
由于Java中& 运算符的短路行为,在
supplierList之前的
,
!= null
savedList == 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.
但是,如果 savedList == null
为true,则
则从上一个条件知道 supplierList
不是 null
,所以这是没有意义的条件。
But if savedList == null
is true,
then we know from the previous condition that supplierList
is not null
, so it's a pointless condition.
另一方面,如果 savedList = = null
为假,则
则由于短路行为,
supplierList!= null
不会
On the other hand, if savedList == null
is false,
then the due to the short-circuiting behavior,
the supplierList != null
will not be evaluated.
因此,无论 savedList == null
的结果如何,
supplierList!= null
永远不会被评估,
,因此您只需删除该条件即可。
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;
}
下一步:
if(savedList != null && supplierList == null){
感谢之前的简化,现在很明显 savedList
不能为 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;
}
这篇关于声纳错误条件不应无条件地评估为“真”。或“假”;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!