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

The Javadoc for Preconditions from the Google Guava library states that:

Projects that use com.google.common should generally avoid using Objects.requireNonNull (Object) . Instead, use checkNotNull (Object) or Verify.verifyNotNull (Object) as appropriate. (The same goes for messages accepting congestion.)

What is the motivation for this recommendation? I can not find in Javadok.

I mean, they pretty much do the same thing, and in these cases it's usually better to use the standard API (for example, the people behind Joda-Time now recommend that people use java.time , pretty much discounting their own framework )

As an example, these two lines 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"); } } 
+5
source share
2 answers

The Guava version offers a number of overloads that take a format string and arguments. To quote the PreconditionsExplained wiki:

We preferred to copy our own preconditions of verification, for example. comparable utilities from Apache Commons for several reasons. In short:

...

  • Simple, varargs "printf-style" exception messages. (This advantage is also that we recommend that you continue to use checkNotNull over Objects.requireNonNull , introduced in JDK 7.)
+4
source

AFAIK,

  • For consistency
  • An additional way to do the following:

    String world = "world"; Preconditions.checkNotNull(string, "Hello %s",world);

Using objects you should use String.format. Moreover, the implementation of both methods is the same.

+2
source

Source: https://habr.com/ru/post/1263432/


All Articles