I can see that @Nullable
and @Nonnull
annotations could be helpful in preventing NullPointerException
s but they do not propagate very far.
@Nonnull
is not null and consequently not performing null checks. The code below causes a parameter marked with @Nonnull
to be null
without raising any complaints. It throws a NullPointerException
when it is run.
public class Clazz { public static void main(String[] args){ Clazz clazz = new Clazz(); // this line raises a complaint with the IDE (IntelliJ 11) clazz.directPathToA(null); // this line does not clazz.indirectPathToA(null); } public void indirectPathToA(Integer y){ directPathToA(y); } public void directPathToA(@Nonnull Integer x){ x.toString(); // do stuff to x } }
Is there a way to make these annotations more strictly enforced and/or propagate further?
@Nullable The @Nullable annotation helps you detect: Method calls that can return null. Variables (fields, local variables, and parameters), that can be null.
The @NonNull annotation is the most important among all the annotations of the null-safety feature. We can use this annotation t0 declare non-null constraint anywhere an object reference is expected: a field, a method parameter or a method's return value.
@NonNull – The compiler can determine cases where a code path might receive a null value, without ever having to debug a NullPointerException. @ReadOnly – The compiler will flag any attempt to change the object. This is similar to Collections.
Annotation Type CheckForNull The annotated element might be null, and uses of the element should check for null. When this annotation is applied to a method it applies to the method return value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With