Tag Archives: java stream

Why You Should Use Java 8: NullPointerException Free Object Access Using Optional

If you haven’t you should read Tired of Null Pointer Exceptions? Consider Using Java SE 8’s Optional.

How many times does object traversal code like this frightens you?

String city = personRepository.getByUsername("bob").getAddress().getCity();

Yes it’s a looming NullPointerException bound to happen. Remember Murphy’s Law? Anything that can go wrong, will go wrong.

Here’s how we all used to make it safer in Java 7 <

  String city;
  Person person = personRepository.getByUsername("bob");
  if (person != null) {
    Address address = person.getAddress();
    if (address != null) {
      city = address.getCity();
      if (city == null) {
        city = "Unknown";
      }
    }
  }

whatifmeme

Java 8 lambda to the rescue:

String city = personRepository
                  .findByUsername("bob")
                  .flatMap(Person::getAddress)
                  .flatMap(Address::getCity)
                  .orElse("Unknown")
;

How does this work? flatMap and orElse are methods of Optional interface. In plain english flatMap(Person::getAddress) reads: apply the function getAddress belonging to the class Person and give me whatever return value getAddress has.

Of course we have to wrap the types used to store the values in the object with Option:

public class PersonRepository {
  public Option findByUsername(String username) {
    ...
  }
}

public class Person {
  private Option
address; public Option
getAddress() { return this.address; } } public class Address { private Option city; public Option getCity() { return this.city; } }

No way! I don’t want to have to wrap all my property types with Optional / I’m using a 3rd part library and cannot refactor the types

Not a problem you can wrap them when you traverse the object:

String city = Optional.ofNullable(personRepository.findByUsername("bob"))
                .map(Person::getAddress)
                .map(Address::getCity)
                .orElse("Unknown");
;

Optional.ofNullable will create an Optional object with values that may be null. map is similar to flatMap except this one says: apply function X to this Optional and give me another Optional with whatever X’s return type.

One more reason to convince your boss / architect / team lead to upgrade your code into Java 8 :-). Enjoy.