fastcodejava
fastcodejava

Reputation: 41097

Sonar is wrongly reporting Remove this expression which always evaluates to "true"

If I have this code sonar does not complain :

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

But if I put one line of code above

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

Then sonar reports this weird error. How does sonar know what getEmptyListForNull does and that does not matter.

Obviously sonar is thinking the code is like:

myResponse.forEach(this::method);

The method getEmptyListForNull is a simple method that does a null check and returns an empty list if it is so. There is no other annotation or anything fancy.

Upvotes: 1

Views: 3224

Answers (2)

mdoflaz
mdoflaz

Reputation: 571

Actually SonarQube does not know about your function. It is not about your function. It is about forEach().

If you could iterate over a collection with .forEach() without an exception is thrown it means that collection was NOT null.

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.");
        }
     }
}

If an exception is thrown on line 9, line 11 is not executed.

If there is no exception is thrown on line 9, it means that list was not null.

Upvotes: 3

Matt Durlin
Matt Durlin

Reputation: 29

A little more clarification on your example would be helpful, but in searching the Sonar docs, https://rules.sonarsource.com/java/type/Bug/RSPEC-1145?search=expression, I found an example that might closely resemble what you are doing.

http://cwe.mitre.org/data/definitions/571.html

In the example noted in the link above, there is a variable never set in the method. Since I am not able to see what your method does, I will guess that Sonar is detecting something similar in your code.

Could you edit your question to provide a little more insight into what your function does, and also verify whether something similar is happening?

I apologize for not simply commenting; my reputation does not allow for that, but wanted to also provide links to documentation sites since most often good suggestions and answers can be found there.

Upvotes: 0

Related Questions