Writing custom Lint rule to ensure null-check before every using to avoid NullPointerException

893 Views Asked by At

I want make a custom Lint rule to ensure null-check before every reference to a sever returned JavaBean object or its fields to avoid NullPointerException. For example:

error case:

SomeBean bean = fetchDataFromServer();
bean.getSomeField().doSomeThing();//-->Lint should report error, missing null-check before using

right case:

if (bean != null && bean.getSomeField() != null) {
    bean.getSomeField().doSomeThing();//-->Lint should check this ok, have checked for both reference
}

My question: Are there any implemented rules already for this check? If no, could somebody give me some idea how to write one such custom rule?

Any help would be appreciated.

1

There are 1 best solutions below

0
On

Among frequently used linters in the Java ecosystem:

  1. SonarLint (also SonarQube) has a rule to avoid NPE
  2. FindBugs (also successor SpotBugs) has bug patterns to detect NPE (prefixed with NP)
  3. Checkstyle allows to add a custom rule

SonarLint

There is the Sonar rule RSPEC-2259 that deals with the Law of Demeter (LoD):

Null pointers should not be dereferenced

A reference to null should never be dereferenced/accessed. Doing so will cause a NullPointerException to be thrown. At best, such an exception will cause abrupt program termination. At worst, it could expose debugging information that would be useful to an attacker, or it could allow an attacker to bypass security measures.

You can use the free SonarLint plugin for your Java IDE (e.g. IntelliJ or Eclipse). To install the free IDE extension, visit the official website: SonarLint

FindBugs

Among other bug-descriptions in the NP category, NP_ALWAYS_NULL for example:

NP: Null pointer dereference (NP_ALWAYS_NULL)

A null pointer is dereferenced here. This will lead to a NullPointerException when the code is executed.

See also:

Checkstyle

To write your own checkstyle rule, see:

Further Reading