Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

gil.fernandes :

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);
}
Ousmane D. :

Whenever I come to think of using the Optional API for a specific purpose I always remind my self of what it was intended to do and why it was brought into the JDK and i.e.

Optional in intended to provide a limited mechanism for library method return types where there is a clear need to represent “no result” and where using null for this is overwhelmingly likely to cause errors - Stuart Marks

Optional is primarily focused on a return type that might or might not have a return value.

Over using this construct like in this specific example of yours just causes extra memory allocation and GC overhead.

I’d keep things simple and instead do:

String hi = sayHi();
if(hi == null) hi = “-“;
...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=36293&siteId=1