java - 使用 Optional 作为类中的属性是一种好习惯吗?

标签 java java-8 option-type

我读过一些关于 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 or Some 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.

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 implement Serializable, which is generally necessary for widespread use as a property of an object.

关于java - 使用 Optional 作为类中的属性是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29033518/

相关文章:

java - do...while() 使用 Java 8 流?

java - 如何将 Modelmapper Converter 重写为 Lambda 表达式 (java 1.8)?

scala - 到底是什么让 Option 成为 Scala 中的 monad?

java - AsyncTask 中的循环器

java - Java API 中的条件字符串解析器?

java - 表达式j+=j-=j*j和j+=j*=j-=j的结果和解析结果是什么? (多个等于)

java - 使用 java 8 流查找平均值

Java 8 流分组依据

没有 "Optional"的 Swift 字符串/字符可选打印

iphone - 调用可选的委托(delegate)方法