Java 8 getter 应该返回可选类型吗? [英] Should Java 8 getters return optional type?

查看:39
本文介绍了Java 8 getter 应该返回可选类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Optional 类型对于很多开发者来说是一个新事物.

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

返回 Optional 类型的 getter 方法代替经典的 Foo 是一个好习惯吗?假设该值可以为 null.

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

推荐答案

当然,人们会做他们想做的.但是我们在添加此功能时确实有明确的意图,并且不是成为通用的 Maybe 类型,尽管很多人都希望我们这样做.我们的目的是为库方法返回类型提供一种有限的机制,需要一种明确的方式来表示无结果",而使用 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.

我认为经常使用它作为 getter 的返回值肯定会被过度使用.

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

Optional 没有任何错误应该避免它,只是它不是很多人希望的那样,因此我们相当担心过度使用的风险.

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.

(公共服务公告:NEVER 调用 Optional.get 除非你能证明它永远不会为空;而是使用一种安全的方法,比如 orElseifPresent.回想起来,我们应该调用 get 之类的东西,例如 getOrElseThrowNoSuchElementException 或者更清楚地表明这是一个高度危险的方法首先破坏了 Optional 的整个目的.经验教训.(更新:Java 10 有 Optional.orElseThrow(),在语义上等同于 get(),但名字更合适.))

(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 8 getter 应该返回可选类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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