Optionals To Avoid Null

With the introduction of Optionals, people thought they could get rid of nullpointer exceptions, simply use optionals everywhere where there will be no more null. We know that this is of course not true, since an optional can be null itself and it can be empty which could lead to a NPE itself when used incorrectly. But Optionals due help in communicating a message and help to avoid certain errors. In this blog post I will first give my opinion of the cases where optionals are good to be used followed by some scenario’s where I have used optionals to avoid null.

A first case where I tend to use optionals is when you have a default value in case the original value is null. Doing so not only is more compact, easier to mentally navigate, it also allows you to define the value as final, which leads to a more simple path since you don’t have to worry about the value having changed. This case can however also be handled by a ternary operator.

// Without optionals
String x = foo;
if (x == null) {
  x = "default";
}
// With optionals
final String x = Optiona.ofNullable(foo).orElse("default");

// Ternary operator
final String x = foo != null ? foo : "default";

Another scenario where I will use an optional is when you have conditional logic. This can either be do something if the value is present, or throw an exception if the value is not present. Both cases are very nicely handled when using optionals and they avoid the extra if check.

// Without optionals:
if (foo == null) {
  return;
}

// Without optionals
if (foo == null) {
  throw new Exception();
}
// With optionals:
Optional.ofNullable(foo).ifPresent(...);



// With optionals
Optional.ofNullable(foo)
  .orElseThrow(Exception::new)

I am not a fan of using optionals for every single scenario of where a can be null. I have seen some weird code that just doens’t make any sense (as in the code snippet below). I only explicitly wrap a nullable object in an optional if it makes the flow clearer or improves the readability of the code.

if (Optional.ofNullable(foo).isPresent()) {
  ...
}

This means that I still do use null in my code, but as I mentioned in an earlier blog post, I tend to limit it to ‘internal’ usage. In the end optionals don’t help you to avoid null, but they can will avoid explicit null checks. The goal should however not be to eliminate all explicit null checks, as that will lead to the absurd code mentioned in the snippet above, the goal should be to make the code more readable and sometimes doing a simple null check fits the best.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.