Optional type introduced in Java 8 is a new thing for many developers.

Is a getter method returning Optional<Foo> type in place of the classic Foo a good practice? Assume that the value can be null.

推荐答案

Of course, people will do what they want. But we did have a clear intention when adding this feature, and it was not to be a general purpose Maybe type, as much as many people would have liked us to do so. Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.

For example, you probably should never use it for something that returns an array of results, or a list of results; instead return an empty array or list. You should almost never use it as a field of something or a method parameter.

I think routinely using it as a return value for getters would definitely be over-use.

There's nothing wrong with Optional that it should be avoided, it's just not what many people wish it were, and accordingly we were fairly concerned about the risk of zealous over-use.

(Public service announcement: NEVER call Optional.get unless you can prove it will never be null; instead use one of the safe methods like orElse or ifPresent. In retrospect, we should have called get something like getOrElseThrowNoSuchElementException or something that made it far clearer that this was a highly dangerous method that undermined the whole purpose of Optional in the first place. Lesson learned. (UPDATE: Java 10 has Optional.orElseThrow(), which is semantically equivalent to get(), but whose name is more appropriate.))

Java相关问答推荐

在FML中删除关键帧动画

Android视图覆盖不阻止点击它后面的控件

弹簧靴和龙目岛

为什么在枚举中分支预测比函数调用快?

Java Swing:初始化身份验证类后未检测到ATM_Interface键事件

在AVL树的Remove方法中使用NoSuchElementException时遇到问题

将带有js文件的 bootstrap 程序导入maven项目时出错

为什么S的文档中说常量方法句柄不能在类的常量池中表示?

SonarLint:只能有条件地调用方法(S)

如何集成语义发布和BitBucket(Java项目)

为什么同步数据块无效?

找出承载Cargo 的最小成本

深度优先搜索实现:算法只向右搜索

在一行中检索字符分隔字符串的第n个值

字符串的Gzip压缩在java11和java17中给出了不同的结果

Java返回生成器的实现

如何在JSP中从select中获取值并将其放入另一个select

如何判断元素计数并在流的中间抛出异常?

转换为JSON字符串时,日期按天递减-Java

如何显示新布局