【问题标题】:Sonar error Conditions should not unconditionally evaluate to "TRUE" or to "FALSE"声纳错误条件不应无条件地评估为“TRUE”或“FALSE”
【发布时间】:2017-05-04 20:53:47
【问题描述】:

我收到声纳违规:

“条件不应无条件地评估为“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;
}

在两个 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;
}

【问题讨论】:

    标签: java collections sonarqube sonar-runner


    【解决方案1】:
    if(savedList == null && supplierList == null){
        return false;
    }
    
    if(savedList == null && supplierList != null){
    

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

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

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

    因此,不管savedList == null的结果如何, supplierList != null 永远不会被评估, 所以你可以简单地删除那个条件。

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

    下一步:

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

    感谢之前的简化,现在很明显savedList 不能是null。所以我们也可以去掉那个条件:

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

    简而言之,这相当于你发布的代码:

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

    【讨论】:

    • 您甚至可以将最后两个 if 子句合并到 if (savedList == null || supplierList == null) return true
    【解决方案2】:

    基于上述,您避免了后两个 if 条件并有一个 else 情况

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

    或者您可以简单地使用 return 语句删除所有 if 语句

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

    【讨论】:

      【解决方案3】:

      你可以试试:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-17
        • 2018-08-17
        • 1970-01-01
        • 1970-01-01
        • 2016-11-25
        • 1970-01-01
        • 2015-03-15
        • 2017-06-12
        相关资源
        最近更新 更多