You're reading for free via Sivaram Rasathurai's Friend Link. Become a member to access the best of Medium.

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 ❌

Returning Optional from getters is like giving with a wrapped box. 🎁

Just return the raw value and let them check null if needed.

// Don’t do this:
public Optional<String> getPhone() {
return Optional.ofNullable(phone);
}

// Do this instead:
public String getPhone() { return phone; }
public boolean hasPhone() { return phone!= null; } // Simple!

3. Create Optional Like a Pro 🛠️

  • Optional.of(value): When you’re 100% sure it’s not null. (Warning: NullPointerException if you’re wrong! 🚨)
  • Optional.ofNullable(value): When it might be null. Your safe choice.
  • Optional.empty(): For explicitly saying, Nothing here!
// Trust me, "name" is not null here!
Optional<String> nameOpt = Optional.of(name);

// Playing it safe with user input
Optional<String> inputOpt = Optional.ofNullable(request.getParameter("email"));

4. Handle Absence Gracefully 🕺

Don’t just call get() blindly! Use these instead:

ifPresent(): Do something if the value exists.”

userOpt.ifPresent(user -> call(user.getPhone()));

orElse(): Give me this default if empty.

String username = userOpt.orElse("Guest");

orElseThrow(): Crash if missing! 💥

User user = userOpt.orElseThrow(() -> new UserNotFoundException());

5. Collections Don’t Need Optional 🗑️

An empty list is already empty! Wrapping it in Optional is like putting a box inside another box. 📦📦

// 😖 Don’t:
Optional<List<String>> items = Optional.ofNullable(getItems());

// 😍 Do:
List<String> items = getItems() != null ? getItems() : Collections.emptyList();

6. Streams + Optional = Messy Code 🌪️

You’ll see this a lot:

// 🌀 Spaghetti code alert!
Stream<Optional<String>> data = ...
List<String> names = data.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());

Instead, filter nulls early:

Stream<String> data= ...
List<String> names = data.filter(Objects::nonNull).toList(); // Clean! ✨

Common Traps I Fell Into 🕳️

Overusing Optional everywhere: Not every null needs wrapping. Sometimes null is okay (like in private methods).

Chaining until it hurts: optional.map(...).flatMap(...).filter(...) gets unreadable fast. Break it into steps!

Assuming Optional replaces null: Nope. Optional is for return types to signal absence. null still exists, but now you’ll see it less.

Optionalis like salt: a little makes the dish super delicious, too much kills it.

Use it to make your code’s intent crystal clear, not to chase “fancy” design.

remember—

readable code is king. 👑

Next time you think to useOptional,

ask: Does this make the code easier to understand, or am I just showing off?

😉 Happy coding! 🚀

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.