Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sonar critical violation - Nullcheck of value previously dereferenced

Tags:

java

For the below piece of code I have in one of my test classes, Sonar throws me a critical violation - Correctness - Nullcheck of value previously dereferenced

 if (testLst != null && !testLst.isEmpty()) {
        for (Test test : testLst) {
            if (test.getName().equalsIgnoreCase("TEST")) {
            // do blah
            }

Can someone throw some light on this on what am I doing wrong here?

EDIT: One of the answers here suggested this is because I could have accessed the variable before, and so the null check is redundant. That's not true though. Here is the line of code before my null check.

 testLst = myTest.getValues(); //I am basically populating the array by doing a get, but I am not accessing the list itself by doing a get on it directly - like testLst.get()
 if (testLst != null && !testLst.isEmpty()) {
            for (Test test : testLst) {
                if (test.getName().equalsIgnoreCase("TEST")) {
                // do blah
                }
like image 850
rickygrimes Avatar asked Nov 03 '14 20:11

rickygrimes


1 Answers

This message is shown when you're checking if a variable's value is null (in this case testLst) whereas you already accessed the variable before. The null check is not needed since if the value was null, a NullPointerException would have been thrown.

Example:

testLst.remove(something);
if (testLst != null && !testLst.isEmpty()) {
    for (Test test : testLst) {
       if (test.getName().equalsIgnoreCase("TEST")) {
        // do blah
        }

The check testLst != null is redundant since at the time the program reaches the if statement, testLst cannot be null, otherwise the previous statement testLst.remove(something) would have thrown a NullPointerException. In this case, you should place the null check before accessing testLst, in a place where it can be null:

if(testLst != null) {
   testLst.remove(something);
   if (!testLst.isEmpty()) {
       for (Test test : testLst) {
          if (test.getName().equalsIgnoreCase("TEST")) {
           // do blah
          }
like image 140
M A Avatar answered Oct 06 '22 01:10

M A