在 class 中使用 Optional 作为属性是一种好习惯吗?

Is it a good practice to use Optional as an attribute in a class?

我在 Java 8 中读到过一些关于 Optional 的用途(不幸的是我不记得在哪里),我很惊讶作者没有提到 Optional 作为 class.

中的属性

由于我在 classes 中经常使用可选值,所以我想知道这是否是一个好的做法。或者我可以更好地使用普通属性,当它们未设置时 return null

注意: 看起来我的问题是基于个人意见的,但我感觉在 class 中使用 Optional 确实不是办法去(阅读后提到post)。但是,我喜欢使用它,并且找不到使用它的任何缺点。

例子

我想举个例子来说明一下。我有一个 class Transaction,它是这样构建的:

public class Transaction {

     private Optional<Customer> = Optional.empty();
     ....

vs

public class Transaction {

     private Customer = null;
     ....

检查 Customer 时,我认为使用 transaction.getCustomer().isPresent()transaction.getCustomer() != null 更符合逻辑。在我看来,第一个代码比第二个代码更清晰。

我觉得是个理论题

可选值的概念来自函数式语言世界。这些语言通常还支持语言级别的模式匹配,并允许您对可选值进行模式匹配。

在函数式语言中,函数调用通常 return 其他代码可以对其进行模式匹配的可选值。

我从未见过将可选参数作为参数传递,但这并不意味着这是一个糟糕的想法。虽然看起来很奇怪。

Java 8 的 Optional 主要用于方法中的 return 值,而不是 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.