One of the nicest features in FindBugs is its support for annotations indicating whether a certain value is nullable or not, and the way it uses that information to perform additional checks.
There are three annotations: @NonNull
, @CheckForNull
and @UnknownNullnes
.
By default, FindBugs assumes that method parameters, method return values and fields are annotated implicitly with @UnknownNullness
.
But, to me, the best policy is:
- For method parameters: use
@CheckForNull
. - For method return values: use
@NonNull
. - For object fields: use
@NonNull
.
Why?
Easy. We are trying to follow this principle: give as much as as you can, demanding as little as possible -in a safe way.
For method parameters, the worst case is receiving a null value, because your code will need to be careful and check for null if it uses the value in any meaningful way. Therefore, we should use @CheckForNull
by default because this demands less from our code users.
For method return values, life will be easier for our code users if they need not care about a returned value being null. Therefore, use @NonNull
to give as much as you can.
For object fields, things are not that clear cut, because they do not affect the user (directly), as they should be private. I just chose to make them @NonNull
because I feel this is the safest policy.
Of course, these are the “ideal” settings: you will have to provide an override from time to time, annotating an element explicitly with a different annotation.
How to do this?
You can provide the desired default annotations for a package by adding the following annotations to package-info.java
:
@DefaultAnnotationForParameters( value=CheckForNull.class) @DefaultAnnotationForFields( value=CheckForNull.class) @DefaultAnnotationForMethods( NonNull.class)
Really neat!
If you start using these annotations with FindBugs, you will be surprised by the clarity they add and the way they can help diagnose null values misuse.