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 alternatives 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.