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
?
requireNonNull(bar, "bar must not be null"); is ok in constructors, but potentially dangerous in other methods if two or more variables are set in the same method.
The method checkArgument of the Preconditions class ensures the truthfulness of the parameters passed to the calling method. This method accepts a boolean condition and throws an IllegalArgumentException when the condition is false.
The requireNonNull method is a static method of the Objects class in Java. It checks whether the input object reference supplied to it is null . If the supplied object reference is null , then NullPointerException is thrown. If the object reference is not null , then the reference is returned as it is.
Precondition sentence exampleGod sets no preconditions here, not even the precondition of repentance. The first precondition for the development of acute otitis media is exposure to an organism capable of causing the infection. Yet such a desire seems to be a precondition of the highest kind of creative originality.
I have noted that many Java 8 methods in Oracle JDK use Objects.requireNonNull (), which internally throws NullPointerException if the given object (argument) is null. public static <T> T requireNonNull (T obj) { if (obj == null) throw new NullPointerException (); return obj; }
Java Preconditions.checkNotNull - 30 examples found. These are the top rated real world Java examples of Preconditions.checkNotNull extracted from open source projects. You can rate examples to help us improve the quality of examples.
An aggressively safe strategy could be to check null for every object. However, this causes a lot of redundant null checks and makes our code less readable. In the next few sections, we'll go through some of the alternatives in Java that avoid such redundancy.
Here, we can use Java Assertions instead of the traditional null check conditional statement: In line 2, we check for a null parameter. If the assertions are enabled, this would result in an AssertionError. Although it is a good way of asserting preconditions such as non- null parameters, this approach has two major problems:
It's just for consistency. The implementations are the 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