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.
Among frequently used linters in the Java ecosystem:
NP
)SonarLint
There is the Sonar rule RSPEC-2259 that deals with the Law of Demeter (LoD):
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:See also:
Checkstyle
To write your own checkstyle rule, see:
Further Reading