guava icon indicating copy to clipboard operation
guava copied to clipboard

Suggest Objects.requireNonNullElseGet in our Javadoc

Open bjmi opened this issue 2 years ago • 2 comments

Every now and then I'd like to check a variable for a non-null value or otherwise provide a reasonable non-null default value. Sometimes the second value is computed or should be created on-demand for different reasons. Therefore please provide T firstNonNull(T first, Supplier<? extends T> second) for that.

firstNonNull is much more concise and expressive than requireNonNullElseGet or Optional.ofNullable(first).orElseGet(() -> second()).

Additionally: java.util.Objects.requireNonNullElseGet(T obj, Supplier<? extends T> supplier) should be mentioned in Javadoc as an alternative for incoming parameter validation.

Thank you for your great library.

bjmi avatar Dec 29 '22 07:12 bjmi

Thanks. Previously: #741.

While I agree that "requireNonNullElseGet" is a clumsy name, we'd want to pick our own descriptive name (to avoid ambiguity about whether a call is to the (T, T) overload or the (T, Supplier<T>) overload), so it might end up just as clumsy. And even if we could do better with naming, we don't want to provide methods that differ from JDK methods only in naming.

I do think we should add the Javadoc that you mention.

cpovirk avatar Jan 03 '23 15:01 cpovirk

(to avoid ambiguity about whether a call is to the (T, T) overload or the (T, Supplier<T>) overload)

Is there an actual problem adding firstNonNull overload? I'd stick with that precise name.

In contrast to JDKs requireNonNullElseGet(obj, supplier) Guava should always check second parameter for null to follow its null-hostile policy.

bjmi avatar Jan 03 '23 17:01 bjmi