Linting for null safety

A few times a year, I hit a NullPointerException in the course of more or less normal implementation work. Java (unlike e.g. Kotlin) is a language which offers no null safety despite painfully verbose typing.

I just ran into one in openmrs-core. Calling getPatientIdentifiers with a null argument results in an NPE. This behavior isn’t actually surprising to a human being, but the compiler knows nothing about it, and it may not be obvious to the person writing client code that the variable they are passing in might be null.

This kind of problem is probably epidemic. I feel like it would be really, really great if we had some way of catching NPEs before they become runtime errors. I am not really “a Java guy” so I don’t know what the right approach for that is, though it appears that the Java community doesn’t really either. We already use Spring, so maybe Spring Null-Safety Annotations?

@ibacher @dkayiwa @mksd @mseaton

Sonar might be helpful here too.

It might be even better to take a look a SonarCloud as integrating quality checks into PRs could help fix these things before they get committed.

Using SonarCloud sounds very nice. And free for open-source projects!

Sonar (and SpotBugs) use the FindBugs null-safety annotations. How do we feel about introducing those to the codebase?

I’d be hesitant to actually add anything from FindBugs to the code base, as my understanding is that it’s dead. I suppose we could add the JSR-305 version (which is also dead, but slightly closer to being a “standard” way of doing things).

This GitHub Issue on Guava looks like it makes a strong argument against jsr305. Maybe Checker Framework?

1 Like

Have you tried the SonarLint plugin in your IDE?

2 Likes

@dkayiwa Yes, that is very helpful. I suspect it would be much more helpful and powerful if we adopted the Checker Framework’s @NotNull annotation. I expect that it would catch many more possible NPEs.