How to Write Better Code with Java 8’s Optional

Optional is one of the most exciting features added in Java Programming Language. This well-designed API lets the application developers design APIs without worrying much about the Null Pointer Exception.

Somnath Musib
The Startup

--

Image Courtesy: Unsplash by bruce mars

Optional is one of the many exciting features introduced in Java 8. Anyone programming in Java is surely aware of the pain of the never-ending null checks and the infamous NullPointerException. Although it is perfectly fine to assume that this class is introduced to provide some degree of relief from excessive null checks and NullPointerExceptions, the actual semantics is slightly different.

Optional let the API developers indicate that the return type of a method could legitimately be null. This wrapper class indicates that the return type could either contain an object or could be null.

The need for Optional

Before diving into the usage of Optional, let us understand what issue it promises to resolve. In any Java application, it is a common pattern to use method chaining to de-reference object properties. This often leads to the NullPointerException whenever there is a null object reference.

String countryCode =…

--

--

Somnath Musib
The Startup

Software Developer, Cloud Architect | Author "Spring Boot In Practice" . Find more at https://musibs.github.io