Java 8 Optional Anti-pattern

One occasionally comes across an anti-pattern involving the java.util.Optional<T> class that was introduced by Java 8. It looks like this:

Optional<String> maybeName = getName();
if (maybeName.isPresent()) {
    return maybeName.toUpperCase();
} else {
    return "NOBODY";
}

The above code is written in the imperative style: a sequence of statements that the computer is instructed to follow. The code works, but it's well... awkward by comparison with the following alternative:

return getName()
    .map(String::toUpperCase)
    .orElse("NOBODY");

The alternative (immediately above) is written in the functional style: expressions chained together to form other more powerful expressions. For my money, the functional style more clearly expresses the programmer's intent: get a name and transform it to upper case, or else return "NOBODY". I get that in one glance, whereas I have to pause a little to walk my mind through the steps specified in the previous example.

If you needed to do some processing to construct the or-else part, you might prefer to use the orElseGet() method, which will only do the expensive work if it's needed:

return getName()
    .map(String::toUpperCase)
    .orElseGet(() -> getDefaultName());

In fact, supposing that getDefaultName() is defined as a static method on MyClass, the orElseGet() could be further refined as follows:

return getName()
    .map(String::toUpperCase)
    .orElseGet(MyClass::getDefaultName);

If you wanted to throw an exception if the 'happy' path could not be traveled, you could use the orElseThrow() method, like this:

return getName()
    .map(String::toUpperCase)
    .orElseThrow(() -> 
        new IllegalArgumentException("No name"));

The imperative style will gradually become less idiomatic as the influence of Java 8 and its successors takes hold.

The functional style of programming encouraged by Java 8 features like the Optional class is worth learning because it makes for more perspicuous code.