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.
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.










