249. Returning a boolean if the Optional class is empty

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 the isPresent() result.

Since JDK 11, the Optional class has been enriched with a new method named isEmpty(). As its name suggests, this is a flag method that returns true if the tested Optional class is empty. So, we can increase the expressiveness of our solution as follows:

// Prefer (after JDK 11)
public static boolean cartIsEmpty(long id) {
Optional<Cart> cart = fetchCart(id);

return cart.isEmpty();
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.53