How to use @Nullable and @Nonnull annotations more effectively? How to use @Nullable and @Nonnull annotations more effectively? java java

How to use @Nullable and @Nonnull annotations more effectively?


Short answer: I guess these annotations are only useful for your IDE to warn you of potentially null pointer errors.

As said in the "Clean Code" book, you should check your public method's parameters and also avoid checking invariants.

Another good tip is never returning null values, but using Null Object Pattern instead.


Other than your IDE giving you hints when you pass null to methods that expect the argument to not be null, there are further advantages:

This can help your code be more maintainable (since you do not need null checks) and less error-prone.


I think this original question indirectly points to a general recommendation that run-time null-pointer check is still needed, even though @NonNull is used. Refer to the following link:

Java 8's new Type Annotations

In the above blog, it is recommended that:

Optional Type Annotations are not a substitute for runtime validation Before Type Annotations, the primary location for describing things like nullability or ranges was in the javadoc. With Type annotations, this communication comes into the bytecode in a way for compile-time verification. Your code should still perform runtime validation.