2014-03-08

NPE killer in Java8 to prevent NullPointerExceptions

In JDK8 the Optional<T> type monad has been introduced. The purpose of this class is essentially to facilitate the active thinking about the case when null might be assigned to an object causing a NullPointerException when this object will be dereferenced.

Consider this:
public static Optional<Drink> find(String name, List<Drink> drinks) {  
  for(Drink drink : drinks) {
    if(drink.getName().equals(name)) {
    return Optional.of(drink);
    }
  }
  return Optional.empty();
}
List<Drink> drinks = Arrays.asList(new Drink("Beer"), new Drink("Wine"), new Drink("Cocktail"));
Optional<Drink> found = find("Beer", drinks);
if(found.isPresent()) {
  Drink drink = found.get();
  String name = drink.getName();
}