java-8 – Where does it make sense to use Optional?


The next article on Optional has the following summary:

don't pollute your code with Optional everywhere, use them carefully where it makes sense.

Where does it make sense to use Optional ? Is there a clear separation (or at least some guidelines) when it is better to use if-else , and when Optional ?


First of all, all talk about Optional is holivar. However, there are a number of consequences:

  1. Correct use of Optional simplifies the contract in the application where the library developer explicitly indicates which fields can be null. And the developer of the final application clearly sees where checks need to be made and where they can be dispensed with. Key words are important here, correct use and clearly sees . In reality, a variable of type Optional <*> itself can be null.
  2. Working with Optional hits performance, since it may require the allocation of additional objects in the heap – the Optional classes themselves, labdas. At the same time, the likelihood of boxing primitive values ​​increases.
  3. When working with Optional'ami, the amount of code increases.

There are important consequences from all this:

  • The Optional questions are closer to the Code Review questions, the Style Guide. With the right approach, the code will be cleaner, with the wrong approach, everything will only get worse.
  • For the JVM, the Optional class has no positive effect, but it can have a negative effect.
  • If reliability is more important to you than speed (for example, the load is not so heavy, and the data is serious), then Optional can help make your code better.

And once again – this is holivar, there is no clear and unambiguous answer.

Scroll to Top