Optional.orElse

Intro:

The moment the API defeats the purpose as I’ve quite recently found out.

Problem:

Let’s consider the following scenario:

I’ve asked most of my colleagues what they think this code returns and I’ve got all sorts of combos as you can imagine:

  • “A” , “B”, “A”
  • “A”, “A”
  • even got the correct “B”, “A”, “A”

However when I’ve asked them the infamous question “why?” none seem to be able to provide an answer as why this is happening.

Before stating the obvious consider the following pre-conditions:

  • most methods in the Optional API receive Suppliers, Consumers, Predicates or Functions
  • Optional was introduced in Java 8 so it resides alongside all the functional and lazy API out there
  • Java is still NOT a functional programming language

So let’s compare the two methods with a grain of doubt:

As you can clearly see in the snippet above the orElseGet receives a Supplier thus we can safely assume that any expression that’s given to it won’t be executed unless the optional value is actually missing.

However as we can clearly see in the first method we’re just passing a type, hell we need to pass a parameter to a plain old Java method….And what guess what Java does when it sees that..You’ve probably guessed that already, it tries to resolve the parameters so it executes B() to pre-compute the parameter it needs to pass to the orElse method and this will happen wether or not the Optional has a value.

Outro:

Thank you Java 8 for teaching me a really important lesson! Don’t take things for granted and actually study any API you consider to use because it might “hide” the obvious.

Credits:

https://stackoverflow.com/questions/33170109/difference-between-optional-orelse-and-optional-orelseget