Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should Objects.requireNonNull() not be used if com.google.common from Guava is used?

Tags:

java

guava

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");
  }
}
like image 872
Magnilex Avatar asked Jan 27 '17 09:01

Magnilex


2 Answers

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.)
like image 74
shmosel Avatar answered Nov 17 '22 05:11

shmosel


AFAIK,

  1. For consistency
  2. 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.

like image 23
GauravJ Avatar answered Nov 17 '22 06:11

GauravJ