On 06.10.2015 16:58, Roger Riggs wrote:
Hi Ivan,

Easy enough, but I have not surveyed the codebase to see if it would be used or is necessary.
Most of the cases I've seen are simple if/then/else or ?: expressions.

I found a few possible candidates with grep:

share/classes/java/net/InetSocketAddress.java: addr == null ? InetAddress.anyLocalAddress() : addr,
==> Objects.nonNull(addr, InetAddress::anyLocalAddress)

share/classes/java/net/InetAddress.java: throw ex == null ? new UnknownHostException(host) : ex;
==> throw Objects.nonNull(ex, () -> new UnknownHostException(host))

share/classes/java/util/TreeMap.java: value = (defaultVal != null ? defaultVal : (V) str.readObject()); ==> value = Objects.nonNull(defaultVal, () -> (V) str.readObject())

share/classes/java/time/format/DateTimeFormatter.java: ParsePosition pos = (position != null ? position : new ParsePosition(0));
==> ParsePosition pos = Objects.nonNull(position, () -> new ParsePosition(0)
etc.

I'm not sure, though, they should be really changed, as using this nonNull() method doesn't really make the code shorter.

My point is that if someone wants to use Objects.nonNull() in a case, where the second argument is calculated, it would be better to provide her with that additional variant with Supplier.

Sincerely yours,
Ivan

Using the Supplier for does have some extra overhead not readily observable in the code. There is precedent for such a method in requireNonNull, where the cost of composing/formatting
the exception text can be avoided using a supplier.

Roger


On 10/6/2015 9:53 AM, Ivan Gerasimov wrote:
Hi Roger!

I didn't notice the message, so first commented in the Jira.

Would it make sense to also add a variant with the second argument of type Supplier, so that it can be lazily calculated only if needed?
Something like:
public static <T> T nonNull(T obj, Supplier<T> nullDefaultSupplier) {
    return (obj != null) ? obj : nullDefaultSupplier.get();
}

Sincerely yours,
Ivan

On 06.10.2015 16:43, Roger Riggs wrote:
Java.lang.Objects contains a number of convenience methods to make it easier to handle references that are null.
For example, toString(obj, nullDefault),

A new method is proposed to return the reference or a default value if the reference is null.
   static <T> T nonNull(T obj, T nullDefault);

Alternatives to the method name include
nonNullOrElse ( using the java.util.Optional name pattern) or
nonNullOrDefault

Please review and comment.

Webrev:
http://cr.openjdk.java.net/~rriggs/webrev-object-non-null/

Issue:
https://bugs.openjdk.java.net/browse/JDK-8138963

Thanks, Roger





Reply via email to