Using the Java java.util.Optional
with Lambda Expression can improve readability in the service layer. Let's have a look at the following two snippets:
The first sample is the classical null
check. Find a purchaser orElseThrow
an exception. The java.util.function.Supplier
is implemented as a lambda expression.
public Purchaser findPurchaserByInitials(String initials) {
Optional<Purchaser> purchaser = purchaserRepository.findPurchaserByInitials(initials);
return purchaser.orElseThrow(
() -> new NotFoundException("The purchaser was not found for initials: " + initials));
}
The second sample is about providing a reasonable fallback if no result is present. Use the existing result orElseGet()
an new empty order basket. Again very readable result with a lambda expression.
public OrderBasket findOrCreateOrderBasketFor(String initials) {
Optional<OrderBasket> result = orderBasketService.findOrderBasketByPurchaser(purchaser);
return result.orElseGet(() -> orderBasketService.createEmptyOrderBasket(purchaser));
}
IMHO both snippets improved readability when compared to implementations with pre-Java 8
if-statements.