Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why checkNotNull() is not annotated with @Nonnull

Tags:

java

guava

I found inconvenient that checkNotNull() precondition in guava is not marked with @Nonull annotation. Consider following example:

State(Set<Model> models, Set<Variation> variations) {
  this.models = checkNotNull(models);
  this.variations = checkNotNull(variations);

  if (this.variations == null) {
     throw new IllegalArgumentException();
  }
  this.engine = createEngine();
}

So IDE could not found that variations == null is always false. Is there any particular reasons why this precondition is not marked with @Nonull (even if it's arguments are defined using @Nullable).

like image 595
Denis Bazhenov Avatar asked Dec 05 '11 07:12

Denis Bazhenov


2 Answers

We haven't used @Nonnull anywhere, sorry. Why? We tried adding more null-checking annotations, and we found that:

  • Adding all the other annotations is highly verbose.
  • @Nullable is all we need for NullPointerTester. Admittedly that's more important to Guava developers than Guava users.
  • @Nullable appeared to have caught most problems. I admit it's hard to say how many un-checked-in bugs other annotations would have caught before the user found them.

The verbosity was the main thing. It gets crazy, especially with subtyping and with parameterized types. We tried to pick a sweet spot for annotations. Maybe we'll change it one day. For the moment, though, that's why things are the way they are.

(If we did do something, I suspect we'd try to make @Nonnull the default, using @CheckForNull for the exceptions instead. But I haven't looked into it even enough to make sure I've got the meanings right.)

like image 71
Chris Povirk Avatar answered Sep 28 '22 09:09

Chris Povirk


It would indeed be interesting to annotate its result with @Nonnull, since checkNotNull() throws a NPE if the reference is null, which means it never returns null:

  @Nonnull
  public static <T> T checkNotNull(T reference) {
    if (reference == null) {
      throw new NullPointerException();
    }
    return reference;
  }

Note that you'd need to change your code to:

if(this.variations == null)

since the @Nonnull would only apply to the result of checkNotNull(), but says nothing about its argument. Note that we cannot annotate the argument with @Nonnull, since we might often be checking nullable variables.

like image 26
Etienne Neveu Avatar answered Sep 28 '22 10:09

Etienne Neveu