optional usages of production resources creates problem of selection.Give reason
Answers
Answer:
So, how to useOptionalthe way it was intended? Typically, we learn to use things by learning how to not use them, and, somehow, this is the approach here as well. So, let's tackle this topic via 26 items. This is a suite of items that try to addressOptionalin your code through an elegant and painless approach.
Item 1: Never Assign Null to an Optional Variable
Avoid:
// AVOID
public Optional<Cart> fetchCart() {
Optional<Cart> emptyCart = null;
...
}
Prefer:
// PREFER
public Optional<Cart> fetchCart() {
Optional<Cart> emptyCart = Optional.empty();
...
}
PreferOptional.empty()to initialize anOptionalinstead of anullvalue.Optionalis just a container/box and it is pointless to initialize it withnull.
Item 2: Ensure That an Optional Has a Value Before Calling Optional.get()
If, for any reason, you decide thatOptional.get()will make your day, then don't forget that you must prove that theOptionalvalue is present before this call. Typically, you will do it by adding a check (condition) based on theOptional.isPresent()method. The isPresent()-get()pair has a bad reputation (check further items for alternatives), but if this is your chosen path, then don't forget about theisPresent()part. Nevertheless, keep in mind thatOptional.get()is prone to be deprecated at some point.
Avoid:
// AVOID
Optional<Cart> cart = ... ; // this is prone to be empty
...
// if "cart"is empty then this code will throw a java.util.NoSuchElementException
Cart myCart = cart.get();
Prefer:
// PREFER
if (cart.isPresent()) {
Cart myCart = cart.get();
... // do something with "myCart"
} else {
... // do something that doesn't call cart.get()
}
Item 3: When No Value Is Present, Set/Return an Already-Constructed Default Object Via the Optional.orElse() Method
Using theOptional.orElse()method represents an elegant alternative to theisPresent()-get()pair for setting/returning a value. The important thing here is that the parameter oforElse()is evaluated even when having a non-emptyOptional. This means that it will be evaluated even if it will not be used, which is a performance penalty. In this context, useorElse()only when the parameter (the default object) is already constructed. In other situations, rely on item 4.
Avoid:
// AVOID
public static final String USER_STATUS = "UNKNOWN";
...
public String findUserStatus(long id) {
Optional<String> status = ... ; // prone to return an empty Optional
if (status.isPresent()) {
return status.get();
} else {
return USER_STATUS;
}
}
Prefer:
// PREFER
public static final String USER_STATUS = "UNKNOWN";
...
public String findUserStatus(long id) {
Optional<String> status = ... ; // prone to return an empty Optional
return status.orElse(USER_STATUS);
}