使用Optional.ofNullable作为三元运算符的替代是一种好的做法吗? [英] Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

查看:12181
本文介绍了使用Optional.ofNullable作为三元运算符的替代是一种好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑使用此表达式:

String hi = Optional.ofNullable(sayHi()).orElse("-");

有效对应于这个三元表达式:

which effectively corresponds to this ternary expression:

String hi = sayHi() != null ? sayHi() : "-";

是否使用 Optional.ofNullable 一种方法叫做好的做法?或者只是额外的详细编码?

Is this usage of Optional.ofNullable with a method call a good practice? Or just extra verbose coding?

我认识到 Optional.ofNullable 实际创建一个变量并避免两次调用 sayHi()方法。为了避免这个问题,你实际上可以创建一个额外的变量,但这增加了三元选项的详细程度:

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 : "-";

另一方面 Optional.ofNullable 创建如果 hi 不是 null 额外的可选对象。所以肯定会有更多的开销。

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.

顺便说一下:这是 Optional.ofNullable 的Java 8实现:

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);
}


推荐答案

每当我想到使用Optional API用于特定目的我总是提醒自己它打算做什么以及为什么它被带入JDK,即

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.


可选用于为库方法提供有限的机制
返回类型,其中明确需要表示无结果和
,其中使用null可能会导致错误 - Stuart Marks

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.

过度使用此结构就像在你的这个具体例子中一样,只会导致额外的内存分配和GC开销。

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

我会保持简单而改为:

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

这篇关于使用Optional.ofNullable作为三元运算符的替代是一种好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆