是否应该使用Optional.ofNullable()进行null检查? [英] Should Optional.ofNullable() be used for null check?

查看:1071
本文介绍了是否应该使用Optional.ofNullable()进行null检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种null检查更可取?

Which null-check is preferable?

Optional.ofNullable(port).ifPresent(settings::setPort);

if (port != null) {
   settings.setPort(port);
}

推荐答案

在Java中,Optional值是指示存在或不存在的位与任意引用类型T或a的融合.原始intlongdouble.

In Java, an Optional value is a fusion of a bit that indicates presence or absence, with a value of an arbitrary reference type T or a primitive int, long, or double.

当从方法返回值时,将它们融合起来特别有用,因为方法只有一个返回值.对于引用类型,通常需要使用特殊值,例如null,对于int则使用-1作为标记,以指示无值"情况.使用Optional作为返回值可以避免呼叫者意外地将哨兵值误用作实际返回值的问题.

Fusing these is especially useful when returning a value from a method, as methods have only a single return value. It's often necessary to use a special value such as null in the case of reference types, or -1 in the case of int, as a sentinel to indicate the "no-value" case. Using Optional as a return value avoids the problem of the caller accidentally misusing the sentinel value as the real return value.

给出这样的代码行,例如

Given this, line of code such as

Optional.ofNullable(port).ifPresent(settings::setPort);

的奇怪之处在于,它在行的第一部分中将值与当前/不存在的位相融合,然后立即在行的第二部分中将它们分开.这增加了最终相当简单的任务的复杂性:检查port是否为非null并有条件地执行某些操作.替代代码段:

is strange in that it fuses a value with the present/absent bit in the first part of the line and then immediately separates them in the second part of the line. This adds complexity to what is ultimately a fairly simple task: checking whether port is non-null and conditionally performing some action. The alternative code snippet:

if (port != null) {
    settings.setPort(port);
}

非常清楚地表达了它的作用.

expresses quite clearly exactly what it does.

的确,if语句比Optional链占用更多的垂直空间. Optional链比较密集,但也很难理解:权衡取舍.

It's true that the if-statement takes more vertical space than the Optional chain. The Optional chain is denser, but it's also harder to understand: a poor tradeoff.

这篇关于是否应该使用Optional.ofNullable()进行null检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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