简体   繁体   中英

Why checkNotNull() is not annotated with @Nonnull

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 ).

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.)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM