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!
}