Friends of OpenJDK Today

Let’s Use Optional to Fix Method Contracts

November 10, 2021

Author(s)

  • Avatar photo
    A N M Bazlur Rahman

    A N M Bazlur Rahman is a Software Engineer with over a decade of specialized experience in Java and related technologies. His expertise has been formally recognized through the prestigious ... Learn more

A method is a contract: when we define one, we put thought into it. We specify parameters with their type and also a return type. When we invoke a method, we expect it to behave according to the contract. If it doesn’t, it’s a violation of the contract.

We have been dealing with such violations all the time. We invoke a method with its proper arguments and we get a return. However, sometimes we end up getting a null, which is, in fact, a clear violation. We shouldn’t accept such a violation. If a method cannot return the value of the specified type, it should mention that in the method signature, the method may or may not be returning the value you are expecting. If we know it from the method signature, we then write our code accordingly.

Now the question is, how do we define such a contract in a method signature? Well, that’s where Optional comes into play. Set your return type as Optional. Optional is a mystery box, a wrapping paper: it may or may not contain the value. When we specify that in a method signature, we assume that the box might be empty. Let’s see an example:

public static Optional<Book> findBookByName(String name) {
  return books.stream()
          .filter(book -> book.title().equalsIgnoreCase(name))
          .findAny();
}

The method above specified Optional as a return type. It may return the book that I’m looking for or may not. I’m aware of this, and I can deal with it when I invoke it. For example:

var bookOpt = findBookByName("Java Programming");
if (bookOpt.isPresent()) {
    var book = bookOpt.get();
    var releasedYear = book.releasedYear();
    System.out.println("Java Programming was published in " + releasedYear);
} else {
    System.out.println("Book was not found");
}

Or we can do the same thing with the functional construct, e.g:

findBookByName("Java Programming")
.map(Book::releasedYear)
.ifPresentOrElse((releasedYear)
        -> System.out.println("Java Programming was published in " + releasedYear),
() -> System.out.println("Book was not found"));

The bottom line is, we should fix our method contract and use optional rather than returning null.

Topics:

Related Articles

View All
  • 7 Functional Programming Techniques in Java: A Primer

    There is a lot of hype around functional programming (FP) and a lot of cool kids are doing it but it is not a silver bullet.

    Like other programming paradigms/styles, functional programming also has its pros and cons and one may prefer one paradigm over the other.

    If you are a Java developer and wants to venture into functional programming, do not worry, you don’t have to learn functional programming oriented languages like Haskell or Clojure(or even Scala or JavaScript though they are not pure functional programming languages) since Java has you covered and this post is for you.

    Read More
    May 11, 2021
  • Avoiding NullPointerException

    The terrible NullPointerException (NPE for short) is the most frequent Java exception occurring in production, according to a 2016 study. In this article we’ll explore the main techniques to fight it: the self-validating model and the Optional wrapper.

    You should consider upgrading your entity model to either reject a null via self-validation or present the nullable field via a getter that returns Optional. The effort of changing the getters of the core entities in your app is considerable, but along the way, you may find many dormant NPEs.

    Read More
    December 22, 2020
  • Introduction to JVM Unified Logging (JEP-158 / JEP-271)

    Unified logging was introduced in JDK 9, and is available for us all, in the JDK 11 LTS. Like other great serviceability feature (jcmd or JFR) this was inspired by JRockit.

    In my opinion the flexibility of this logging system brought a major downside from a user’s perspective in its configuration correctness, and I think in some ways it’s more obscure compared to the previous explicit logging flags.

    Read More
    Avatar photo
    March 01, 2021

Author(s)

  • Avatar photo
    A N M Bazlur Rahman

    A N M Bazlur Rahman is a Software Engineer with over a decade of specialized experience in Java and related technologies. His expertise has been formally recognized through the prestigious ... Learn more

Comments (1)

Your email address will not be published. Required fields are marked *

Highlight your code snippets using [code lang="language name"] shortcode. Just insert your code between opening and closing tag: [code lang="java"] code [/code]. Or specify another language.

Save my name, email, and website in this browser for the next time I comment.

Jan Schäfer

This was proposed by Stephen Colebourne years ago:

https://blog.joda.org/2015/08/java-se-8-optional-pragmatic-approach.html

Subscribe to foojay updates:

https://foojay.io/feed/
Copied to the clipboard