Sitemap
Codimis

Yazılım öğrenmek isteyenlere güncel içerik ve kaynak sağlayarak, mentor desteği eşliğinde iş ve staj bulmalarına yardımcı olan online platformdur. Yazılımcı arayan şirketlere de bu alandaki kişileri detaylı filtreleyerek istenilen nitelikteki adaylara ulaşmalarını sağlar.

Optional Best Practices

Real-world Use Cases

6 min readOct 5, 2023

--

Press enter or click to view image in full size
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ş
Uğur Taş

Written by Uğur Taş

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”

Codimis
Codimis

Published in Codimis

Yazılım öğrenmek isteyenlere güncel içerik ve kaynak sağlayarak, mentor desteği eşliğinde iş ve staj bulmalarına yardımcı olan online platformdur. Yazılımcı arayan şirketlere de bu alandaki kişileri detaylı filtreleyerek istenilen nitelikteki adaylara ulaşmalarını sağlar.