@Nullable/@NotNull best practices


It is a very common case a method returns Null only under very narrow
conditions and then stays not null for the rest of its life.

For example during bean initialization by a factory or while an instance is
being added to
a data structure - getParent(), getType() would be a very typical example

Very often such initialization is package private or done within factory or
in some other way is very
localized and when object is finally presented to API user it is fully
initialized and its methods does not return null.
While API developer (guy who writes this initialization code) might benefit
from this method
being marked as nullable, API user will suffer tons of false positives while
they for all means and purposes could enjoy @NotNull for those methods

My biggest issue is whether to be "pure" and declare any method which could
return null @Nullable (and suffer tons of false positives which I know must
not happen) or declare it's @NotNull if it is not null for API user and had
some invalid null analysis very localized though

I wonder could do a trick when programming to interfaces by declaring
interface method as @NotNull and implementation @Nullable. This way when
using API we would see them as @NotNull and when programming to
implementation (i.e. inside of factories) we se them as @Nullable

I know it's dirty but has anyone any better solution?



1 comment
Comment actions Permalink

I suggest using a builder and making the fields final/not null but that can be difficult to retrofit and creates extra classes.

Another approach I've used is just to mark the getter not null and have it test for null.  It can throw an uninitialized exception of some sort or just do an assert to ensure the variable isn't null when called.


Please sign in to leave a comment.