Sitemap

Member-only story

How to never null check again in your Java code

Mendes
2 min readJan 27, 2024

First of all, what even is the problem will null checking?

This article perfectly explains why you should avoid null checking.

In short: It adds noise to your code, it makes code less readable and violates SRP(S).

But how do we replace null checking?

In java we have a very simple solution: The optional data type.

Whenever you are retrieving something from your database, you need to make sure it actually exists, otherwise you might face what all developers eventually face, the NullPointerException. So, how do we use the Optional type?

Well that’s simple, every time we try and get something from our database, we make sure that it returns an Optional<DesiredType> object. Here is an example:

Here we have a repo that has a List<UserExample>, and a method where it returns a User if a user with the requested id exists:

@Data
@Builder
@AllArgsConstructor
public class UserExample {
private int id;
private String name;
}
@Repository
@AllArgsConstructor
@Data
public class ExampleRepoImpl implements ExampleRepo {
ArrayList<UserExample> listOfExamples;

public…
Mendes
Mendes

Written by Mendes

Software Engineering student living in the Netherlands

Responses (4)