In my previous article, you can see that I am quite fond of Optional class. Probably many of you agree with me that it is very useful and provides a lot of options. As of now, it consists of approx. 500 lines of code and 20 methods with a public access level (including hashCode, equals, toString, and Javadocs) with various possibilities.

Today, I will show you what this API evolution looks like through the subsequent Java releases and what were the reasons for its introduction to Java. I hope that it will give you some more knowledge about Optional class itself, help to convince your coworkers to start using it instead of a simple null check or even to decide which Java version to use in your company or private project.

Let’s start with a simple question.

Why Does Optional Even Exist in Java Today?

Here, the reason is pretty simple. In many modern-day programming languages there is a feature (or a bug, depending on what you think) called “the billion-dollar mistake” or a null pointer reference if you prefer. In the case of Java, it allows NullPointerException to occur.

The NPE is one of the most common if not the most common runtime exception. It tends to appear in the most unexpected and unwanted places of our codebase causing a great deal of trouble to us and our customers. Until Java 8, the only way to deal with them was to use “if ladder”, responsible for checking if the object is not null, what could make our code look like the following sample.

1
private String getAssignManagerName(Task task) {
2
    if (task != null) {
3
        Team team = task.getAssignTeam();
4
        if (team != null) {
5
            Manager manager = team.getManager();
6
            if (manager != null) {
7
                return manager.getName();
8
            }
9
        }
10
    }
11
    throw new UnableToGetManagerNameException("Unable to get assign manager name");
12
}

#java #opinion #tutorial #api #optional #evolution

Java Optional API Evolution
1.20 GEEK