× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Can it be null? Save time, confusion, and bugs by using Optional<T> in lieue of nullable types.

Michael Safyan
Mar 27, 2016
<p>Consider the following code:</p> <pre><code class="language-java">public interface UserAccount { // ... EmailAddress getEmail(); // ... }</code></pre> <p>Given the interface above, can we assume that if a user account exists that it always has an email address (i.e., that the email address returned will be non-null)? Or does our code have to handle null address?</p> <p>The <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html">Optional</a> class introduced in Java 8 let's us do away with this guessing game (pre-Java 8, you can use the <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Optional.html">Guava version of Optional</a>). By using this class, we can make it very obvious that an account may not have an email address:</p> <pre><code class="language-java">public interface UserAccount { // ... Optional&lt;EmailAddress&gt; getEmail(); // ... }</code></pre> <p>In code that consistently uses <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#empty--">Optional.empty()</a> rather than null, we can stop guessing and assume that things which are not Optional are, instead, required to be non-null. In addition to using Optional, nullability annotations such as <a href="https://github.com/findbugsproject/findbugs/blob/36154c2ceff3e23784ebe75f1ad4453d975f3285/findbugs/src/java/edu/umd/cs/findbugs/annotations/NonNull.java">@NonNull</a> and <a href="https://github.com/findbugsproject/findbugs/blob/36154c2ceff3e23784ebe75f1ad4453d975f3285/findbugs/src/java/edu/umd/cs/findbugs/annotations/NonNull.java">@CheckForNull</a> can also provide greater clarity regarding whether null is permitted or not.</p>
comments powered by Disqus