Home > Enterprise >  Handling Java Optional
Handling Java Optional

Time:05-13

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 other fields like the customer which are optional.

What the best way to handle this optional in here?

CodePudding user response:

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.

CodePudding user response:

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(...);          

}
  •  Tags:  
  • java
  • Related