I would like to formally annotate my function signatures to clarify their contracts—especially if null
params and return values are permitted or prohibited—in a way that FindBugs’ static code analysis tool (and maybe other) can make use of it.
There are two packages (annotations.jar
and jsr305.jar
) with four annotations each to achieve this, as well as the option not to put an annotation at all.
These are my findings after some trying around:
Method parameters:
null
: Do not put any annotation. In this case a bug marker appears if null
is passed to the method. (I had expected this behaviour when putting the @Nonnull
annotation, but when I put it, no bug marker came up at all.)null
: Put @Nullable
annotation. (Same effect for @CheckForNull
. The @Nullable
documentation reads: “FindBugs will treat the annotated items as though they had no annotation.” This is not true. If I call string.length()
and String string
has been marked @Nullable
, it causes a bug marker to appear, if there is no annotation no bug marker showed.)Method return value:
null
: Put @Nonnull
. Causes a bug marker if you try to return null;
from inside the method.null
: Do you want to enforce checks for it? Checks may be an overhead if the return value does depend on the method parameters only which can be assumed known at call time, like “my method returns null
if parameter one is negative”. I would not put an annotation in that case. However, you may want to consider throwing an IllegalArgumentException
instead of returning null
.null
and the return object should always be checked: Put @CheckForNull
. However, in many cases there are better ways to go, you may want to consider returning Collections.emptyList()
instead of null
lists, or throwing MissingResourceException
, IOException
or another appropriate exception.Which JAR file to use:
annotations.jar
are showing as deprecated in Eclipse. So use jsr305.jar
.