Optional Best Practices

Real-world Use Cases

Uğur Taş
Codimis

--

Java Optional Best Practices

Java introduced a game-changer with the advent of Java 8, the Optional class. Optional was designed to address a long-standing problem: handling of potentially null values. In this article, we will explore the best practices and bad practices of Java Optional to help you to understand when and how to use Optional

If you don’t have a medium membership, you can use this link to reach the article without a paywall.

Best Practices

Use Optional.empty()

If your business requirements force you to return null, use optional as a return type. When a method might not have a meaningful result, consider returning an Optional . Let’s explore it with an example. If you want to retrieve your user data with the id field, there is a chance that the id value does not belong to any of the stored users. Hence, you can return a null user object. In that case, Optional is the best candidate as a return type.

public User findUserById(int id) {
// this method can return null
}

--

--

Uğur Taş
Codimis

A software developer with a high passion for learning, improving skills, and sharing knowledge. My motto is “fail million times if you take lessons every time”