问题描述
使用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.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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!