I just finished a vJUG24 session entitled Optional: The Mother of All Bikesheds.
Video: YouTube
Slide deck: PDF
This slide deck has a few minor updates relative to what I presented in the vJUG24 session:
- slides 21-22: clarify problem statement (the before and after code is correct)
- slide 26: mention flatMap() for completeness
- slide 31: add link to Stack Overflow question
- slide 36: clarify reason for not deprecating Optional.get()
- slide 42: new slide describing new methods in Java 9
For convenience, here are the six seven style rules I proposed in the session:
- Never, ever, use null for an Optional variable or return value.
- Never use Optional.get() unless you can prove that the Optional is present.
- Prefer alternative APIs over Optional.isPresent() and Optional.get().
- It’s generally a bad idea to create an Optional for the specific purpose of chaining methods from it to get a value.
- If an Optional chain has a nested Optional chain, or has an intermediate result of Optional, it’s probably too complex.
- Avoid using Optional in fields, method parameters, and collections.On a related note, I thought of another rule after I presented the session:
- Don’t use an Optional to wrap any collection type (List, Set, Map). Instead, use an empty collection to represent the absence of values.
Watching your talk on Optional, I always wondered: Why does Optional not have a method like: orElse(Runnable r). And another nice extension would be, if ifPresent(Consumer consumer) would return this, so I could chain it like:
optional.ifPresent(o -> ….)
.orElse(() -> some other code)
The orElse() method wants to return a value, so instead of a Runnable, there’s an variation that takes a Supplier that is called in order to furnish the return value. It’s Optional.orElseGet(Supplier). For the second item, in Java 9 we’ve added Optional.ifPresentOrElse(Consumer, Runnable). I think that lets you do what you want to do.
[…] deck is available […]