Using Optional in Java

During a recent code review I came across this scenario:

Code in review

if (input.getValue() != null) {
   return Arrays.asList(value);
}  else {
   return input.getValues().stream().map(this::parseValues).collect(Collectors.toList())
}

And I suggested (in a compassionate way :grin: ) that we use Optional to treat the null value, so my suggestion was something like:

return Optional.ofNullable(input.getValue()).map(Arrays::asList)
       .orElseGet(input.getValues().stream().map(this::parseValues).collect(Collectors.toList()));

And I thought I was being very clever.

But then I realised it’s harder to understand the logic in this version. At least the if is a clear intent.
So I read up some more on Optional.
The Optional container allows us to perform logic including chaining map, flatMap, filter etc based on a value that may or may not be present. But this is not the real intention of Optional.

Optional is mainly used to represent attributes in an object that may be null or a method in an API that could return a null.

Consider a Person.
Everyone has a name, an age and a gender but may not have a car so we could define a class as follows:

class Person {
   private String name;
   private int age;
   private boolean female;
   private Optional<Car> car;
}

From this declaration it’s obvious that not everyone has a car and so the caller would then treat the car attribute appropriately.

My take away is the following:

Optional is not a replacement for occurrences if (x != null)

Any heavy users of Optional around?
Tips and/or suggestions would be very much appreciated.

1 Like