Sitemap
Alt.

Alt is a Medium publication by CTRL Magazine. A place for all things tech.

Member-only story

Java Optional: Stop Writing Error-Prone Null Checks

--

Imagine you are building a Spring Boot application that lets customers view their orders.

A request arrives with an order ID. Your service queries the database, retrieves the order, and returns a response.

But what happens when the order does not exist?

A common implementation looks like this:

public Order getOrder(Long id) {
Order order = orderRepository.findById(id);

if (order == null) {
throw new RuntimeException("Order not found");
}

return order;
}

At first glance, this looks reasonable. The problem is that null does not explain why a value is missing, and nothing forces the caller to check it.

Press enter or click to view image in full size

Another developer might write:

Order order = orderService.getOrder(id);
return order.getCustomer().getName();

If the order, customer, or customer name is unexpectedly null, the application can fail with a NullPointerException.

As an application grows, these checks spread across service methods, controllers, repository calls, and data transformations. Some checks get forgotten. Others become deeply nested. The result is code that is harder to reason about and easier to break.

--

--

The Turtle Code
The Turtle Code

Written by The Turtle Code

Backend engineer writing about Java, Spring Boot, System Design, Distributed Systems, APIs, Databases, Docker, and real-world software engineering.

Alt.
Alt.

Published in Alt.

Alt is a Medium publication by CTRL Magazine. A place for all things tech.