Consider the usage of this expression:
String hi = Optional.ofNullable(sayHi()).orElse("-");
which effectively corresponds to this ternary expression:
String hi = sayHi() != null ? sayHi() : "-";
Is this usage of Optional.ofNullable
with a method call a good practice? Or just extra verbose coding?
I recognise that Optional.ofNullable
actually creates a variable and avoids calling the sayHi()
method twice. To avoid this problem you actually could create an extra variable but this adds to the verbosity of the ternary option:
String hi = sayHi();
hi = hi != null ? hi : "-";
On the other hand Optional.ofNullable
creates in case of hi
not being null
an extra Optional
object. So there is for sure more overhead to it.
So there seem to be some pros and cons to using this type of construct to replace the ternary constructor.
By the way: this is the Java 8 implementation of Optional.ofNullable
:
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}