Over a million developers have joined DZone.

Better API Design With Java 8 Optional

See how to create better APIs by warning your system of possible null values with Java SE 8's Optional container objects. See them in action in this article.

· Integration Zone

Build APIs from SQL and NoSQL or Salesforce data sources in seconds. Read the Creating REST APIs white paper, brought to you in partnership with CA Technologies.

How did you used to design your API, where the consumer can expect a null from its attributes; probably by marking the getter's signature with "throws NullPointerException"?

Before the introduction of Java 8, there was no mechanism to check whether there is null value expected out of an API, and we had to just rely on “Null Checks”.

Here comes the rescue with the new Java SE 8 java.util.Optional<T>. It helps in designing a better API in which just by reading the signature of a method, you can tell whether to expect an optional value. It also forces you to actively unwrap an Optional to deal with the absence of a value; as a result, you protect your code against unintended null pointer exceptions.

What Is Optional?

Optional is a container object that is used to contain not-null objects. An optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values.

How Does it Work?

Optional

public class Vehicle {
    private Optional<MusicSystem> musicSystem; 
    public Optional<MusicSystem> getMusicSystem() {
        return musicSystem;
    }
    publicvoid setMusicSystem(Optional<MusicSystem> musicSystem) {
        this.musicSystem = musicSystem;
    }
}


The above example depicts a class called Vehicle, which shows that it can have a Music System or not. Just by looking, you can say that it’s optional. Now if you see the method say “getMusicSystem()” above, you can say that you expect an optional music system by calling this method.

Design With a Little Caution

This is a value-based class (like java.time.LocalDateTime); use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of optionals may have unpredictable results and should be avoided.

A program may produce unpredictable results if it attempts to distinguish two references to equal values of a value-based class, whether directly via reference equality or indirectly via an appeal to synchronization, identity hashing, serialization, or any other identity-sensitive mechanism. Use of such identity-sensitive operations on instances of value-based classes may have unpredictable effects and should be avoided.

Conclusion

This post is to highlight the Java 8 Optional utility from the API design perspective. The purpose of Optional is not to replace every single null reference in your codebase, but rather to help design better APIs. The programmer also needs to take little caution because of its “value-based” nature. This class consist of some very useful utility methods like, isPresent(), orElseGet etc. You can have a detailed look of all methods here.

The Integration Zone is brought to you in partnership with CA Technologies.  Use CA Live API Creator to quickly create complete application backends, with secure APIs and robust application logic, in an easy to use interface.

Topics:
java 8 ,programing ,api design ,api best practices ,design ,java

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}