Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
592 views
in Technique[技术] by (71.8m points)

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

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In JDK 9 or later, use this:

String hi = Objects.requireNonNullElse(sayHi(), "-");

This avoids having to repeat sayHi() if a ternary operator is used, or to assign its value to a local variable that is reused within the ternary. It might be a small improvement. It also sidesteps the question of whether to use Optional. :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...