vpiTriumph
vpiTriumph

Reputation: 3166

java.util.Objects.requireNonNull vs Preconditions.checkNotNull

The documentation for Guava Preconditions notes:

Projects which use com.google.common should generally avoid the use of Objects.requireNonNull(Object). Instead, use whichever of checkNotNull(Object) or Verify.verifyNotNull(Object) is appropriate to the situation. (The same goes for the message-accepting overloads.)

Can someone explain the rationale for this suggestion?

Is it for the purpose of consistency or is there something fundamentally wrong with the implementation of Objects.requireNonNull?

Upvotes: 23

Views: 8744

Answers (2)

Ajay Yadav
Ajay Yadav

Reputation: 806

Although from the example in the question it seems that OP is asking specifically about the particular form of checkNotNull, there is one more subtle difference in general in favor of using checkNotNull which is reflected in the printf style varargs form. For example using Guava Preconditions you can do following:

public void getInput(String companyName) {
   String context = "Google";
   String moreContext = "Facebook";
   checkNotNull(companyName, "Why not try %s or %s", context, moreContext);
}

with Objects.requireNonNull you will have to do something like

public void getInput(String companyName) {
   String context = "Google";
   String moreContext = "Facebook";
   requireNonNull(companyName, "Why not try " + context + " or " + moreContext);
}

Reference: See bottom section of Preconditions Explained

Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use checkNotNull over Objects.requireNonNull introduced in JDK 7.)

EDIT: One thing to note though is that all args to the errorMessageTemplate are converted to String using String.valueOf(arg) so you can use only %s and not other type specifiers like %d or %f etc.

Upvotes: 14

Louis Wasserman
Louis Wasserman

Reputation: 198033

It's just for consistency. The implementations are the same.

Upvotes: 19

Related Questions