Member-only story

Why Bother With Optional? 🤔

Hey, this method might not have a value — handle it! : From Optional

Sivaram Rasathurai
Javarevisited
Published in
3 min readFeb 15, 2025

If you are blocked by a medium paywall, you can read it here. But If you want to appreciate my work, please clap 👏👏 and response your feedback 💬.

Photo by Kelly Sikkema on Unsplash

Use Optional for No More Surprise

// Before: A null bomb 💣
public User findUser(String id) {
return userCache.get(id); // Could return null... surprise!
}

// After: use of Optional
public Optional<User> findUser(String id) {
return Optional.ofNullable(userCache.get(id));
}

everyone know findUser might not find anything. No more surprise!

The Golden Rules of Optional 🏆

1. Return Types Only, Please! 🚫

Use Optional only for method returns.

  • Please don’t put it in class fields (it’s not serializable!).
  • Please don’t pass it as a method parameter (like wearing a raincoat indoors 🌂).
public void processData(Optional<String> data) { 
// Now the caller has to wrap values. Annoying!
}

Used it only in return
public Optional<String> fetchData() {
// Clean and clear!
}

2. Getters ≠ Optional’s BFF ❌

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Javarevisited
Javarevisited

Published in Javarevisited

A humble place to learn Java and Programming better.

Responses (4)

Write a response

1. Caller should use Optional as well. There should be no potentially nullable variables in the code unless this is strictly necessary.
2. This suggestion contradicts the #1
6. Instead of manual filtering, you can use Optional::stream:
var names =…

Great article! 👍 It explains Optional clearly and highlights common mistakes. I like the focus on avoiding overuse—Optional should improve readability, not complicate things.

Thank you for the article!

About the advice on getters. I get that this matches with the mainstream opinion but I'm not sure this is always the best solution. Having to call separate hasValue method seems quite error prone and not any simpler.