“Optional – the mother of all bikesheds”
Speaker: Stuart Marks
The deck is available online
For more blog posts from JavaOne, see the table of contents
Showed early version of “optional” (stream returning null)
Review of basics
- Two states – present (contains non null reference) or absent
- Don’t say “null optional”. Say “absent” or “empty”
- Optionals are immutable
- equals() and hashCode() work as one would expect – useful for JUnit because can call assertEquals()
New in Java 9
- stream() – stream with 0 or 1 elements
Good code and Best practices
- Never set an Optional variable to null. It should be Optional.empty() as default.
- If method returns Optional, never return a null either.
- Intended for return types where might or might not have a value to return.
- Don’t call get() as could be empty optional
- Use isPresent() and get() as last resort
- Using .map().orElse() chained after stream pipeline gives fluent API calls
- Calling filter() returns original value only if non-empty optional that matches. else returns empty. Using filter() and orElseThrow() is good for validation
- [and more see the deck]
My take: Amazed there is so much to say about Optional! Excellent set of best practices. And excellent point on not calling an optional “null.” I needed to leave early as my session is immediately after this one. And I really wanted to know “what’s with the bikeshed” which is covered last. It’s a nice collection of quotes. So I found the deck and best practices online. There’s also a youtube video linked so you can watch at home.