hm1
hm1

Reputation: 186

SonarQube shows Possible null pointer dereference

Possible null pointer dereference error in this code:

if(!Util.isNull(dir)){
    if (dir.isDirectory()){
        if(!Util.isNull(dir.list()))
            if((!Util.isNull(dir.list().length))) // issue reported here
                if(dir.list().length == 0) // another issue reported here
                    if (dir.delete())
                        LOGGER.info("deleted:");
                    }
                }

How can I fix these issues?

Upvotes: 4

Views: 7486

Answers (1)

slartidan
slartidan

Reputation: 21576

You check, that dir.list() is not null. Afterwards you do other calls to dir.list(), and assume, that is cannot be null in this case.

SonarJava tries to tell you, that even though dir.list() has not been null in the first place, it could have turned null for the second/third call.

To solve this issue:

  1. save the result of dir.list() in a variable
  2. check that the variable is not null
  3. use the variable

This is also know as the extract variable refactoring, and it has additional good effects. If you don't expect the result of dir.list() to change between calls, then you will improve the performance as well, since the program doesn't need to access the filesystem again to produce the content of the directory.

Upvotes: 9

Related Questions