by

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.

1
2
3
4
5
6
7
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:

1
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.

Footnotes

  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.

Write a Comment

Comment

  1. Better :-)

    I introduced Google Guavas Optional on a project, and some people started to use it at the wrong places – like your list example. I think it is important to explain why you should use it. Not only how it works.

  2. Nice example.

    I have also had great success with orElseGet when I want to log something. Like:

    1
    2
    
    String username = "th";
    getFullName(username).orElseGet(() -> {log.info("No user found for " + username); return "No user found";});