Java 8 getter应该返回可选类型吗? [英] Should Java 8 getters return optional type?
问题描述
Java 8中引入的可选
类型对许多开发人员来说是一个新东西。
Optional
type introduced in Java 8 is a new thing for many developers.
是一个getter方法返回可选< Foo>
代替经典 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
.
推荐答案
当然,人们会做他们想做的事。但是在添加此功能时我们确实有一个明确的意图,并且不是一个通用的可能类型,就像许多人希望我们这样做。我们的目的是为库方法返回类型提供一种有限的机制,其中需要一种明确的方式来表示无结果,并且使用 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.
没有任何错误的可选,应该避免它,这不是很多人所希望的,因此我们非常关注热心过度使用的风险。
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.
(公共服务公告:从不致电 Optional.get
除非您能证明它永远不会为null;而是使用其中一种安全方法,例如 orElse
或 ifPresent
回想起来,我们应该调用 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屋!