Reputation: 3166
The documentation for Guava Preconditions notes:
Projects which use
com.google.common
should generally avoid the use ofObjects.requireNonNull(Object)
. Instead, use whichever ofcheckNotNull(Object)
orVerify.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
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
Reputation: 198033
It's just for consistency. The implementations are the same.
Upvotes: 19