将 Optional 用作类中的属性是一种好习惯吗? [英] Is it a good practice to use Optional as an attribute in a class?

查看:31
本文介绍了将 Optional 用作类中的属性是一种好习惯吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have read something about the purpose of Optional (unfortunately I don't remember where) in Java 8, and I was surprised the writer didn't mention the use of an Optional as an attribute in a class.

由于我在课堂上经常使用可选项,我想知道这是否是一个好习惯.或者我可以更好地使用普通属性,当它们未设置时返回 null 吗?

Since I am using optionals pretty frequently in my classes, I was wondering if this is a good practice. Or could I better just use normal attributes, which return null when they are not set?

注意: 看起来我的问题是基于意见的,但我觉得在课堂上使用 Optional 真的不是办法(阅读完提到的帖子).但是,我喜欢使用它并且找不到使用它的任何缺点.

Note: It may look like my question is opinion based, but I get the feeling using Optional in a class is really not the way to go (after reading the mentioned post). However, I like to use it and can't find any downside of using it.

示例

我想举一个例子来澄清.我有一个 Transaction 类,它是这样构建的:

I would like to give an example to clarify. I have a class Transaction, which is built like this:

public class Transaction {

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

对比

public class Transaction {

     private Customer = null;
     ....

在检查 Customer 时,我认为使用 transaction.getCustomer().isPresent() 比使用 transaction.getCustomer() 更合乎逻辑!= 空.在我看来,第一个代码比第二个代码更简洁.

When checking on a Customer, I think it is most logical to use transaction.getCustomer().isPresent() than transaction.getCustomer() != null. In my opinion the first code is cleaner than the second one.

推荐答案

Java 8 的 Optional 主要用于方法的返回值,而不是 Java 类的属性,如 Java SE 8 中可选:

Java 8's Optional was mainly intended for return values from methods, and not for properties of Java classes, as described in Optional in Java SE 8:

当然,人们会做他们想做的.但是我们在添加这个功能时确实有一个明确的意图,它不是一个通用的MaybeSome类型,就像很多人希望我们的那样这样做.我们的目的是为库方法返回类型提供一种有限的机制,其中需要有一种明确的方式来表示无结果",而对于这种情况,绝大多数情况下使用 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 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.

这里的关键是专注于用作返回类型.该类绝对不打算用作 Java Bean 的属性. 证明这一点的是 Optional 没有实现 Serializable,这是通常需要作为对象的属性广泛使用.

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.

这篇关于将 Optional 用作类中的属性是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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