Code review: Are you using Optional.orElse wrong?

Marcus Höjvall
Alphadev thoughts
Published in
3 min readMay 21, 2018

--

After using Java 8 for a few years now I’ve seen one particular misuse of the new APIs pop up a few times and it’s when using the orElse and orElseGet methods. The mistake is easy to make and there is a chance that it exists in your code base too!

TL;DR

It’s easy to make the mistake and use Optional.orElse when you should have used orElseGet. The result is that what you thought would have been executed lazily or not at all will be called immediately. So make sure you aren’t for example accessing the database in your orElse methods.

If you like reading code more than text, skip to the Try it out section. There is a regex down there as well so you can search your own code base.

🐛 The bug

In our example we have a method for fetching a users inventory from the database. The contents of the inventory is not important so you are free to decide whatever fun stuff it contains.

The method declaration is:

public Optional<Inventory> findInventoryByUser(User user)

Which means that if we find an Inventory for the user the returned Optional will contain it. Otherwise the Optional will be empty.

--

--