Optional Containers in Java (Java 8+)
The Null Problem, AKA The Billion Dollar Mistake

• NullPointerException

  • final var shouldntBeNull = null;
  • final var gonnaBlowUp = shouldntBeNull.getFirst().getSecond();

• Null checks everywhere

  • var wontBlowUp = null;
  • if(null != shouldntBeNull && null != shouldntBeNull.getFirst() && null != shouldntBeNull.getFirst().getSecond()) {
  • wontBlowUp = shouldntBeNull.getFirst().getSecond();
The Null Problem, AKA The Billion Dollar Mistake

• NullPointerException

  • final var shouldntBeNull = null;
  • final var gonnaBlowUp = shouldntBeNull.getFirst().getSecond();

• Null checks everywhere

  • var wontBlowUp = null;
  • if(null != shouldntBeNull && null != shouldntBeNull.getFirst() && null != shouldntBeNull.getFirst().getSecond()) {
  • wontBlowUp = shouldntBeNull.getFirst().getSecond();
Now What About Optional?

• Java 8 introduced a container class inspired by Haskell Maybe and Scala Option[T] 

• Optional<Clazz> will hold an object of type Clazz, or it will just be an empty container if that object is null

 
Simple Optional Processing

• Optional.of()

  • Wraps an object into an Optional container

• Optional.ofNullable()

  • Allows for processing of objects that can be null
  • Also allows for handling null payloads in different ways (more on this later)

• Optional.empty()

  • Initialize an Optional container with nobody
 
Optional Request Parameters

• Works seamlessly with any HTML input that is not required:

 @RequestMapping(value = "/combined", method = RequestMethod.GET)

  public String getCombinedThing(

      @RequestParam(value = "thing1", required = true) String thing1,

      @RequestParam(value = "thing2", required = false) Optional<String> thing2) {


    final var response = thing1.concat(thing2.orElse(" but not thing 2"));

    return response;

  }

 
Optional Containers in Java (Java 8+)