Null defense for Android: static analysis with PMD

Last time we wrote about null defense in the context of runtime null checks and unit tests, verifying presence checks.

Today we’ll tell you about additional layer on which we can fight null related problems. This layer is static analysis.

You’ve probably heard of the static analysis tool called PMD. Cool things about it are that it’s completely free and open source, and it supports writing your own rules to check code for. You can check out how to write your own custom rule on their documentation. There are two ways you can write your custom rules: with Java code, or with XPath. We are demonstrating the second approach in this article.

So what can we do is to write a rule for checking correct null defense implementation. We usually do our null defense with lombok @NonNull  annotation, so here the XPath based rule we came up with:

It’s a little bit long, so let’s try to understand it. The general simplified structure looks like this:

So what it does is looking for parameters in methods and constructors which doesn’t have lombok.NonNull  annotation. Pretty simple! The other parts of full rule accomplish the following:

  • we allow argument to not have @NonNull  annotation if its type is primitive, so it can’t contain null value;
  • we allow the argument to have @Nullable  annotation instead of @NonNull  to clearly indicate cases where we permit null argument as valid value. @Nullable  annotation can be from any package you’d like, it’s checked only by name;
  • we allow methods to not have @NonNull  annotations on its arguments if this methods override some other methods. We have this one for the cases where we need to subclass some third party class which allows for nulls, so we shouldn’t add null defense there to not break Liskov Substitution Principle.

Here at BeSmart Mobile we often use this approach to make our null defense a bit better. We hope you’ll find it useful too 🙂

Back to Top