google / guava

Google core libraries for Java

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Suggest Objects.requireNonNullElseGet in our Javadoc

bjmi opened this issue · 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.

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.

(to avoid ambiguity about whether a call is to the (T, T) overload or the (T, Supplier) 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.