When I first learned of the new Java 8 Optional utility class, I considered it... well... optional.
It's meant to help us deal with null pointer checks. But at first I don't see how it makes things any simpler.
I read in the documentation "frequent checks for a null value were necessary to avoid generating an exception. These classes [Optional] provide a better way to handle such situations." (Java, The Complete Reference, Ninth Edition )
I thought that sounded awesome. I looked to the next section eagerly.
How does it keep me from null checks? I asked the book impatiently.
Well the book told me: It doesn't. You still have to ask OptionalisPresent? I didn't understand the power of this. I didn't look beyond the annoyance of a new syntax. We all hate that. Don't we? When our language changes all of a sudden? We get thrown for a loop.
2. Using Optional
I was thrown for a loop. So I set aside that chapter of the book. I went along my merry way.
I didn't know what to do with all these isPresent() and get() calls. At first, I had an inconsistent style. I've settled on a style I like now. My services get the optionals from their repo and unpack them. The controllers get real objects back... always. If the service finds an empty Optional, it throws the 404 itself. It never returns to the controller.
3. Optional Examples
Let's see what that looks like in action: (Note: This is Groovy with Java 8)