Chapter 1: New Language Features

Explain Unexpected Empty Optional

class CandyService {

  private SupplyRepository supplyRepository;

  void updateBarcode(String id, String newBarcode) {
    var supply = supplyRepository.findById(id).orElseThrow();
    supply.setBarcode(newBarcode);
    supplyRepository.save(supply);
  }
}
  • since Java 10 there's orElseThrows() without a parameter
  • according to docs preferred over get() (which basically does the same)
  • exception doesn't say which id wasn't found
class CandyService {

  private SupplyRepository supplyRepository;

  void updateBarcode(String id, String newBarcode) {
    var supply = supplyRepository.findById(id)
        .orElseThrow(() -> new NoSuchElementException("Unknown " + id));
    supply.setBarcode(newBarcode);
    supplyRepository.save(supply);
  }
}
  • exception now says which id wasn't found
  • works with Optional out of the box (since Java 8)