java Optional.ofNullable(i).ifPresent... vs if (i != null)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42285448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:30:57  来源:igfitidea点击:

Optional.ofNullable(i).ifPresent... vs if (i != null)

javaoptional

提问by James Fry

I've recently seen a blog post(tweeted by @java) that suggests the following code is becoming increasingly common:

我最近看到一篇博客文章@java 发推文)表明以下代码变得越来越普遍:

Optional.ofNullable(i).ifPresent(x -> doBlah(x));

instead of:

代替:

if (i != null) {
  doBlah(i);
}

The use of Optional in this case appears very awkward to me, even ignoring the naming of the variables - the latter is easier to read and more idiomatic for the use case (handling nulls). I believe this also captures semantics better - i is likely from code that doesn't adhere to the semantics that Optional is trying to capture (as described in the possible duplicateand in this Oracle article).

在这种情况下使用 Optional 对我来说似乎很尴尬,甚至忽略变量的命名 - 后者更容易阅读并且更适合用例(处理空值)。我相信这也能更好地捕获语义 - 我很可能来自不符合 Optional 试图捕获的语义的代码(如可能的副本这篇 Oracle 文章中所述)。

I do not see one, but is there a good semantic cause to prefer the Optional.isNullable approach (ignoring the performance impact it may have depending on how it is used)?

我没有看到,但是是否有一个很好的语义原因更喜欢 Optional.isNullable 方法(忽略它可能具有的性能影响,这取决于它的使用方式)?

回答by Kylos

It doesn't make much sense for the same unit of code to wrap a potentially null object in an Optional only to call ifPresent()on it.

对于相同的代码单元,将可能为空的对象包装在 Optional 中只是为了调用它并没有多大意义ifPresent()

The more useful case is for an API that can return null objects to instead return an Optional. This forces the caller to handle potential null results in a null-safe way. Since the API and the caller are separate units of code, the extra work of wrapping an object in an Optional and forcing the caller to invoke ifPresent()is not just busy-work but actually enforces a safer contract that protects against null-pointer exceptions.

更有用的情况是 API 可以返回 null 对象而不是返回 Optional。这迫使调用者以空安全的方式处理潜在的空结果。由于 API 和调用者是独立的代码单元,将对象包装在 Optional 中并强制调用者调用的额外工作ifPresent()不仅仅是繁忙的工作,而且实际上强制执行了一个更安全的契约,以防止空指针异常。