The Javadoc for Preconditions from Google's Guava library states that:
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.)
What is the motivation behind this recommendation? I can't find any in the Javadoc.
I mean, they pretty much do the same thing, and in these cases it is typically better to use the standard API (for example, the people behind Joda-Time now recommends people to use java.time
, pretty much deprecating their own framework).
As an example, these two rows of input validation do the same thing:
class PreconditionsExample {
private String string;
public PreconditionsExample(String string) {
this.string = Objects.requireNonNull(string, "string must not be null");
this.string = Preconditions.checkNotNull(string, "string must not be null");
}
}
Guava's version offers a number of overloads that accept a format string and arguments. To quote the PreconditionsExplained wiki:
We preferred rolling our own preconditions checks over e.g. the comparable utilities from Apache Commons for a few reasons. Briefly:
...
- Simple, varargs "printf-style" exception messages. (This advantage is also why we recommend continuing to use
checkNotNull
over Objects.requireNonNull introduced in JDK 7.)
AFAIK,
For additional way of doing following,
String world = "world";
Preconditions.checkNotNull(string, "Hello %s",world);
With Objects, you have to use String.format. Moreover, implementation of both the methods is same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With