[Java] Optional used as replacement for local null check

Optionals are often used unnecessarily as tools to perform local null checks instead of using regular if-else statements. My understanding is that they are used because it is a fairly new feature and it looks “modern.” However, there is no functional reason for it, as the same if-else statements are executed beneath the API. It is counterproductive as it generates several throwaway object initializations where none should be required.

One of the architects behind the Optional class describes the intentions behind Optionals in this StackOverflow comment: Should Java 8 getters return optional type? - Stack Overflow

In general, whenever a programmer uses an Optional without returning the created instance, a code smell should be flagged.

Noncompliant Code

A recent post in StackOverflow triggered me to suggest this. There are many such examples of this anti-pattern on the site and I have seen it several times “in real life” too.

return Optional
    .ofNullable(customEnum)
    .map(Enum::name)
    .orElse("");

Compilant Code

The correct solution is to use a regular if-else statement:

if (customEnum != null) {
    return customEnum.name();
} else {
    return "";
}

Ternary operator is also a viable solution:

return customEnum != null ? customEnum.name() : "";