首页 > 解决方案 > 声纳错误报告删除这个总是评估为“真”的表达式

问题描述

如果我有这个代码声纳不会抱怨:

if (null != myResponse) {
     // some code
}

但是如果我在上面放一行代码

getEmptyListForNull(myResponse).forEach(this::method);

然后声纳报告这个奇怪的错误。声纳如何知道做什么getEmptyListForNull和那无关紧要。

显然声纳认为代码是这样的:

myResponse.forEach(this::method);

该方法getEmptyListForNull是一个简单的方法,它进行null检查并返回一个空列表(如果是)。没有其他注释或任何花哨的东西。

标签: javanullpointerexceptionsonarqube

解决方案


实际上 SonarQube 不知道您的功能。这与您的功能无关。它是关于 forEach() 的。

如果您可以使用 .forEach() 迭代集合而不会引发异常,则意味着该集合不为空。

import java.util.List;

public class NoFalsePositiveHere{

     public static void main(String []args){

        List<String> nullList = null;

        nullList.forEach(s -> System.out.println(s));

        if(nullList != null){
            System.out.println("Since an exception is already thrown on line 9,");
            System.out.println("this block is unreachable.");
            System.out.println("It means that,");
            System.out.println("if no exception was thrown on line 9,");
            System.out.println("You could see these lines on console.");
        }
     }
}

如果第 9 行抛出异常,则不执行第 11 行。

如果第 9 行没有抛出异常,则表示该列表不为空。


推荐阅读