September 2019
Intermediate to advanced
816 pages
18h 47m
English
Let's assume that we have the following simple method:
public static Optional<Cart> fetchCart(long userId) { // the shopping cart of the given "userId" can be null Cart cart = ...; return Optional.ofNullable(cart);}
Now, we want to write a method named cartIsEmpty() that calls the fetchCart() method and returns a flag that is true if the fetched cart is empty. Before JDK 11, we could implement this method based on Optional.isPresent(), as follows:
// Avoid (after JDK 11)public static boolean cartIsEmpty(long id) { Optional<Cart> cart = fetchCart(id); return !cart.isPresent();}
This solution works fine but is not very expressive. We check for emptiness via presence, and we have to negate ...