Skip to content

Instantly share code, notes, and snippets.

View moxim's full-sized avatar

miw moxim

View GitHub Profile
@durgaswaroop
durgaswaroop / JavaOptionalsReference.md
Last active October 5, 2023 12:00
Java Optional usage and Best practices
  • Optional.empty() - An empty optional
  • Optional.of(t) - returns a present Optional containing t. (t must be non-null)
  • Optional.ofNullable(t) - returns an Optional with t that can be null

Rules

  1. Never return null from a method that's supposed to return an optional. It defeats the purpose of Optional
  2. Never do opt.get() unless you can prove that the optional is present.
  3. Prefer alternatives to using opt.isPresent() followed by opt.get()
  4. It's generally a bad idea to create an Optional for the sole purpose of chaining methods from it to get a value.
  5. If an Optional chain is nested or has an intermediate result of Optional<Optional>, it is probably too complex.