Should Optional.ofNullable() be used for null check?

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.

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);

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.

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.

Leave a Comment