Optionalclass, a container that is either empty or contains a non-null value.
Optionalhas numerous problems without countervailing benefits.
Optionaldoes not make your code more correct or robust. There is a real problem that
Optionaltries to solve, and there is a better way to solve it. Therefore, you are better off using a regular possibly-null Java reference, rather than using
The Web and blogosphere are full of claims that the
Optionalclass solves the problem of null pointer exceptions. This is not true. Changing your code to use the
Optionalclass has these effects:
- It transforms a
NoSuchElementException, which still crashes your program.
- It creates new problems that were not a danger before.
- It clutters your code.
- It adds both space and time overheads.
When your code throws a
NoSuchElementException, the underlying logic bug is that you forgot to check all possibilities when processing data. It's best to use a tool that guarantees you don't forget. That helps you to understand and fix the underlying problem.
(These criticisms aren't specific to Java's implementation of
Optional. Other languages that claim to have solved the problem have also merely transformed it into a different manifestation.)
Optionalclass isn't all bad: if you have to use
Optional, it defines methods for reducing code clutter when dealing with possibly-present data. However, you should still avoid the
I have written an article that expands on the above points and offers a better solution. Here is the outline of that article:
- Changing the exception that is thrown doesn't fix the defect or improve the code
Optionalis prone to misuse
Optionalclutters your code
- The real problem: remembering to perform checks
Optional's handy methods