I can see that @Nullable
and @Nonnull
annotations could be helpful in preventing NullPointerException
s but they do not propagate very far.
- The effectiveness of these annotations drop off completely after one level of indirection, so if you only add a few they don't propagate very far.
- Since these annotations are not well enforced there is a danger of assuming a value marked with
@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
or@Nonnull
, but if they are worth it is very "likely to solicit debate" – Pander@Nonnull
when calling an@Nonnull
method with a nullable variable. Of course, casting with an annotation is not possible in Java 7, but Java 8 will be adding the ability to apply annotations to the use of a variable, including casts. So this may become possible to implement in Java 8. – Swellfish(@NonNull Integer) y
is syntactically possible, but a compiler is not allowed to emit any specific byte code based on the annotation. For runtime assertions tiny helper methods are sufficient as discussed in bugs.eclipse.org/442103 (e.g.,directPathToA(assertNonNull(y))
) - but mind you, this only helps to fail fast. The only safe way is by performing an actual null check (plus hopefully an alternative implementation in the else branch). – Fumigate@NonNull
when calling a method that takes an@NonNull
parameter, because we now have an easier way to make that assertion when necessary. – Swellfish@Nonnull
and@Nullable
you are talking about, as there are multiple similar annoations (See this question). Are you talking about the annotations in packagejavax.annotation
? – Plasty