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
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 💬.
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 everynull
needs wrapping. Sometimesnull
is okay (like in private methods).Chaining until it hurts:
optional.map(...).flatMap(...).filter(...)
gets unreadable fast. Break it into steps!Assuming
Optional
replacesnull
: Nope.Optional
is for return types to signal absence.null
still exists, but now you’ll see it less.
Optional
is 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! 🚀