Home » Creating More Intuitive Java APIs With Optional

Creating More Intuitive Java APIs With Optional

selective focus photography of a cup of black coffee

Creating intuitive APIs is a very important skill for you to reduce the chances of bugs and make your software more maintainable. When you don’t create intuitive APIs, your code becomes error prone and the developers (including you) may misuse an API.

Let’s see an example of a non-intuitive API.

Example of non-intuitive API

NOTE: I’m not saying that this is a bad-designed API. This is an old API that was built when Java didn’t have features and resources to create more intuitive APIs.

You probably know the java.util.Map interface. Would you be able to tell, without reading the javadoc, if the following method can return null?

V get(Object key)

And if it can, what does it mean? Does it mean that the specified key was not found on the Map? Or does it mean that the mapped value to that key is null?

As you can see, it’s hard to tell what a null value means in this case.

If you want to read the javadoc, you can do it here.

Making Your API More Intuitive With Optional

To create intuitive APIs, you need to reduce possibilities, eliminate ambiguity, and make things obvious. And one way of doing that is using Optional when null is a valid return value.

For example, instead of doing the following:

public String getNullableValue() {
    if (someCondition()) {
        return "ok";
    } else {
        return null;
    }
}

You could do:

public Optional<String> getNullableValue() {
    if (someCondition()) {
        return Optional.of("ok");
    } else {
        return Optional.empty();
    }
}

That way you let explicit to the caller that the method can return a null value. The caller doesn’t even need to read the javadoc.

Also, the compiler forces the caller to handle the null value when it tries to assign it to a String variable. That wouldn’t happen if the method could return null. So, the caller could forget to check if the returned value is or isn’t null.

String value = getNullableValue().orElse("default value");

So, besides making your API more intuitive, Optional also makes the code less error prone.

Conclusion

Optional is a great feature that helps us to write intuitive APIs and maintainable software.

If you’re asking yourself about performance degradation when using Optional, I wrote an article about it. You can find it here.

If you want to go further on Optional, you can check this article that contains more details and good practices on how to use it, or feel free to ask me any questions.

Leave a Reply

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