Java Optional vs Null-Checking – Why Use Optional?

javajava8

Take the two code examples:

if(optional.isPresent()) {
    //do your thing
}

if(variable != null) {
    //do your thing
}

As far as I can tell the most obvious difference is that the Optional requires creating an additional object.

However, many people have started rapidly adopting Optionals. What is the advantage of using optionals versus a null check?

Best Answer

Optional harnesses the type system for doing work that you'd otherwise have to do all in your head: remembering whether or not a given reference may be null. This is good. It's always smart to let the compiler handle boring drugework, and reserve human thought for creative, interesting work.

Without Optional, every reference in your code is like an unexploded bomb. Accessing it may do something useful, or else it may terminate your program wth an exception.

With Optional and without null, every access to a normal reference succeeds, and every reference to an Optional succeeds unless it's unset and you failed to check for that. That is a huge win in maintainability.

Unfortunately, most languages that now offer Optional haven't abolished null, so you can only profit from the concept by instituting a strict policy of "absolutely no null, ever". Therefore, Optional in e.g. Java is not as compelling as it should ideally be.