Why use Optional.of over Optional.ofNullable?

JavaJava 8NullpointerexceptionNullOptional

Java Problem Overview


When using the Java 8 Optional class, there are two ways in which a value can be wrapped in an optional.

String foobar = <value or null>;
Optional.of(foobar);         // May throw NullPointerException
Optional.ofNullable(foobar); // Safe from NullPointerException

I understand Optional.ofNullable is the only safe way of using Optional, but why does Optional.of exist at all? Why not just use Optional.ofNullable and be on the safe side at all times?

Java Solutions


Solution 1 - Java

Your question is based on assumption that the code which may throw NullPointerException is worse than the code which may not. This assumption is wrong. If you expect that your foobar is never null due to the program logic, it's much better to use Optional.of(foobar) as you will see a NullPointerException which will indicate that your program has a bug. If you use Optional.ofNullable(foobar) and the foobar happens to be null due to the bug, then your program will silently continue working incorrectly, which may be a bigger disaster. This way an error may occur much later and it would be much harder to understand at which point it went wrong.

Solution 2 - Java

In addition, If you know your code should not work if object is null, you can throw exception by using Optional.orElseThrow

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .orElseThrow(NullPointerException::new);
                   // .orElseThrow(CustomException::new);

Solution 3 - Java

This depends upon scenarios.

Let's say you have some business functionality and you need to process something with that value further but having null value at time of processing would impact it.

Then, in that case, you can use Optional<?>.

String nullName = null;

String name = Optional.ofNullable(nullName)
                      .map(<doSomething>)
                      .orElse("Default value in case of null");

Solution 4 - Java

Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwhirlwinView Question on Stackoverflow
Solution 1 - JavaTagir ValeevView Answer on Stackoverflow
Solution 2 - JavaKaran AroraView Answer on Stackoverflow
Solution 3 - JavaGautamView Answer on Stackoverflow
Solution 4 - JavaespendennisView Answer on Stackoverflow