'Handling the Optional which doesn't expected to be empty
I have the following method
private Invoice createInvoice(SomeParameter someParameter) {
Invoice invoice = new Invoice();
Optional<Customer> customer = customerRepository.findByCode(someParameter.getCustomerCode());
invoice.Customer(resource.get());
return this.createInvoice(...);
}
I am looking up the customer that will be assigned to the invoice. There is no chance that the customer code in the parameter does not exist in the DB.
In any case, I know that it's a bad practice to directly call the get()
method on an optional, but still I don't want to check if the value is present, that looks like some boilerplate code. There are other fields like the customer which are optional.
Is there a better way to handle the optional here?
Solution 1:[1]
private Invoice createInvoice(SomeParameter someParameter) {
Invoice invoice = new Invoice();
Optional<Customer> customer = customerRepository.findByCode(someParameter.getCustomerCode());
//1.invoice.Customer(resource.orElse(null));
//2.resource.ifPresent(res->invoice.Customer(res));
//3.invoice.Customer(resource.orElseThrow(()->new Exception("xxx")));
return this.createInvoice(...);
}
Whatever you want
Solution 2:[2]
There is no chance that the customer code in the parameter does not exist in the DB.
If you are sure that result is present in the optional object you've obtained, then instead of get()
you should call orElseThrow()
which does the same - retrieves the value (if present), but contrary to get()
it shows your intention to throw NoSuchElementException
explicitly if optional object doesn't contains a result.
This method has an overloaded version which expects a supplier of type Throwable
and allows providing the desired type of exception for the case of empty optional.
Solution 3:[3]
If you don't want to handle optional then don't return it from the repository method, just return the Customer
entity. You could also annotate your repository method with @Nullable
if necessary.
interface CustomerRepository extends Repository<Customer, Long> {
Customer findByCode(...);
// or
@Nullable
Customer findByCode(...);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vince |
Solution 2 | |
Solution 3 |