为什么在 Optional.ofNullable 上使用 Optional.of? [英] Why use Optional.of over Optional.ofNullable?

查看:53
本文介绍了为什么在 Optional.ofNullable 上使用 Optional.of?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Java 8 Optional 类时,有两种方法可以将值包装在可选中.

When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional.

String foobar = <value or null>;
Optional.of(foobar);         // May throw NullPointerException
Optional.ofNullable(foobar); // Safe from NullPointerException

我知道 Optional.ofNullable 是使用 Optional 的唯一安全方式,但是为什么 Optional.of 存在?为什么不直接使用 Optional.ofNullable 并始终保持安全?

I understand Optional.ofNullable is the only safe way of using Optional, but why does Optional.of exist at all? Why not just use Optional.ofNullable and be on the safe side at all times?

推荐答案

你的问题是基于这样的假设,即可能抛出 NullPointerException 的代码比可能不会抛出的代码更糟糕.这个假设是错误的.如果您希望 foobar 由于程序逻辑而永远不会为 null,那么使用 Optional.of(foobar) 会更好,因为您会看到 NullPointerException 表示您的程序有错误.如果您使用 Optional.ofNullable(foobar) 并且 foobar 由于该错误而恰好为 null,那么您的程序将默默地继续错误地工作,这可能是更大的灾难.这样一来,错误可能会发生得更晚,而且更难理解是在哪个点出错了.

Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.

这篇关于为什么在 Optional.ofNullable 上使用 Optional.of?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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