且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否应该使用Optional.ofNullable()进行null检查?

更新时间:2022-06-13 23:10:39

在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.