java.util.Optional Addendum

So you thought I was done with the Java 8 posts now, didn’t you? I thought I was, too, but no. As pointed out by Terje in this comment, my java.util.Optional example wasn’t very good1. Let’s treat his comment as code review feedback, and see if we can crack out a better example.

Terje argues that it would be better to use an Optional to clarify that something can be null. Or perhaps nil - non-existent - is a better term for the Optional’s state; as we saw in the previous post, the point of the Optional is that it does not contain null values. Instead, the Optional object is empty and its isPresent() method will return false. Another good point that is raised in the comment is that, even though it might be tempting, it could be bad to use Optional everywhere. Use Optional when something can be null, don’t use Optional if something can’t be null.

With all that in mind, here’s another example where the use of Optional perhaps makes more sense. Imagine a service that returns a user’s full name given a user name. But what happens if there is no user with the given user name? I’ve seen many creative solutions: Throw an exception, return an “I’m afraid I can’t let you do that, Dave”-string or return null. All of these solutions have their own flaws, which we will not get into now. Instead, let’s solve this conundrum by returning an Optional.

public Optional<String> getFullName(String username) {
    if ("th".equals(username)) {
        return Optional.of("Tony Hawk");
    } else {
        return Optional.empty();
    }
}

If the input to getFullName(…) is “th”, then an Optional containing the String “Tony Hawk” is returned. For any other input the method, it returns an empty Optional. Usage of the getFullName(…) method could look something like this:

System.out.println(getFullName("th").orElse("No user found"));

Here, we print full name if it’s contained in the Optional, or the string “No user found” if the returned Optional is empty.

Better? Better.


  1. This is what happens form time to time when I do the old Learning by BloggingTM and I don’t have an editor to turn to. ↩︎


Feedback

Do you have any thoughts you want to share? A question, maybe? Or is something in this post just plainly wrong? Then please send an e-mail to vegard at vegard dot net with your input. You can also use any of the other points of contact listed on the About page.

Caution

It looks like you're using Google's Chrome browser, which records everything you do on the internet. Personally identifiable and sensitive information about you is then sold to the highest bidder, making you a part of surveillance capitalism.

The Contra Chrome comic explains why this is bad, and why you should use another browser.