Adam Esterline a twisted journey through my mind


A class named Optional was introduced in Java 8. This is not the first time I have seen Optional. Guava has Optional. Scala has Option. Haskell has Maybe.

When/How should Optional be used?

This week I started thinking that Optional in Java should be used everywhere a null could possibly be returned or passed in as a parameter. Using Optional in all of these places might be controversial in some circles, but I think it does provide value. Using Optional clearly communicates to the next developers that a null is a possiblity and we should account for it. The following code really drives me crazy.

public Integer foo(String a, int b) {
  if(a == null) return null;

  return a.length + b;

The above code doesn’t seem too bad. Why would this bug me? I always wonder can a really be null or was the developer just being defensive? I see lots of code where the developer was just being defensive and the value of a can never be null. In this case, not only do we have an extra check to make sure a isn’t null, but the caller is also forced to check for a null return value. The complexity of the “defensive” coding just keeps compounding. I want to assume that if the method I am working on doesn’t take or return an Optional then I don’t have to worry about the value being null.

I am going to start chasing down code like if(a == null) return null; to determine if a can really be null. If a can be null, then I am going to change the code to look like the following.

public Optional<Integer> foo(Optional<String> a, int b) {
  return -> as.length + b);

I am just starting this practice, so in a month or so I’ll provide a follow up. After a couple of months, I’ll have enough experience with Optional to know if it was worth the effort.