Optionals in Java


In Java, optionals (introduced in Java 1.8) are not strictly needed. In fact, you can write code that uses optionals that is as verbose or even more verbose than without them.

Without optionals

Integer i = null;

// Just do a usual null check 
// before calling a method or property on the object
if(i != null) {
    System.out.println(i.toString());
} else {
    i = 1;
    System.out.println(i.toString());
}

With optionals

Optional<Integer> o = Optional.ofNullable(null);

// This is similar to a null check
if(o.isPresent()) {
    System.out.println(o.get().toString());
} else {
    o = Optional.ofNullable(1);
    System.out.println(o.get().toString());
}

In my view, optionals were not optimally implemented in Java because of this and because we have both of and ofNullable to create optionals. I don’t see why we need of, which raises an exception if the object is null. Clearly, if we want to use optionals, we know that they may be null (or empty), so we would just need ofNullable, which doesn’t raise an exception if the argument is null!

So, given these bad design decisions, why would people even use optionals?

I see only 2 main advantages of optionals

  1. We can use the method orElse to get default values (instead of using isPresent combined with get). The example above would be equivalent

     Optional<Integer> opt = Optional.ofNullable(null);
     System.out.println(opt.orElse(1).toString());
    
  2. They encourage you to think of the absence of values.

    • However, null pointer exceptions were already infamous in Java and people should already be forced to do null checks.

There are other methods in Optional that people may occasionally find useful, but in many cases maybe not. So, I think it’s more a matter of taste or convention whether you use optionals or not. In other words, Java optionals may be optional 1. I may change opinion the more I use Java and optionals, so I may update this post accordingly.

  1. In Rust, I like optionals because Rust programs are written with optionals everywhere and they seem natural.