我读过一些关于 Java 8 中 Optional
的用途(不幸的是我不记得在哪里),我很惊讶作者没有提到 Optional 的使用
作为类中的属性。
由于我在类里面经常使用可选项,我想知道这是否是一个好习惯。或者我可以更好地使用普通属性,当它们未设置时返回 null
?
注意:看起来我的问题是基于意见的,但我觉得在类里面使用 Optional
确实不是可行的方法(在阅读了提到的帖子)。但是,我喜欢使用它,并且找不到使用它的任何缺点。
示例
我想举个例子来澄清一下。我有一个类Transaction
,它是这样构建的:
public class Transaction {
private Optional<Customer> = Optional.empty();
....
对比
public class Transaction {
private Customer = null;
....
检查 Customer
时,我认为使用 transaction.getCustomer().isPresent()
比使用 transaction.getCustomer() 更合乎逻辑! = 空
。在我看来,第一个代码比第二个更干净。
最佳答案
Java 8 的 Optional
主要用于方法的返回值,而不是用于 Java 类的属性,如 Optional in Java SE 8 中所述。 :
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
orSome
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 usingnull
for such was overwhelmingly likely to cause errors.The key here is the focus on use as a return type. The class is definitively not intended for use as a property of a Java Bean. Witness to this is that
Optional
does not implementSerializable
, which is generally necessary for widespread use as a property of an object.
关于java - 使用 Optional 作为类中的属性是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29033518/