Thursday, 14 December 2017

The Dangers of Optional.orElse

Our architect at work explained how to properly use the Optional class, and sometimes it is not easy. I shall explain one of the intricaties in this blog with the aid of Cake, because who doesn't love cake?

Now some people tell me that the cake is a lie1 2. Now, this may or may not be the case. So there may or there may not be cake.

This is basically the definition of the Optional2 class in Java 8.

Optional<Cake> cake;

One of my colleagues is a fan of Eddie Izzard4 5.

Our architect at work presented us the code he encountered of the Optional.orElse. I've changed it a bit by adding more cake.

If you run this program, you'll notice that after you have received a nice cake, you immediately die!

This is due to the fact that the expression in the .orElse is immediately evaluated after the new Cake(). This is very basic Java and what is to be expected.

Unfortunately, we software designers seem to have a blind spot, when it comes to the orElse() method. We automatically compare it to the if-else construction we know and love, and then we assume the behaviour is the same.

It is as if your brain automatically shunts over to the wrong abstraction.

The .orElse() is actually only suitable for constants.

Conclusion

In order to fix the problem, you need to use a lambda. To use a lambda, you need to use a different method of the Optional class, namely .orElseGet().

The code would look as follows:

    cake.orElseGet(this::death);

I had really hoped, that they would have changed the method name to something better. Some notable good examples would have been:

  • "orElseConstant"
  • "orDefault"

References

[1] Know Your Memes - The Cake is a Lie!
http://knowyourmeme.com/memes/the-cake-is-a-lie
[2] Wikipedia - Portal (video game)
https://en.wikipedia.org/wiki/Portal_(video_game)
[3] Oracle Javadoc - Optional
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
[4] Wikipedia - Eddie Izzard
https://en.wikipedia.org/wiki/Eddie_Izzard
[5] Youtube - Eddie izzard-cake or death
https://www.youtube.com/watch?v=BNjcuZ-LiSY

No comments:

Post a Comment