Issue
I have a method that searches a customer in the DB, if found, it returns that customer, otherwise, it creates a new one.
private Customer getProjectCustomer(String customerCode) {
Optional<Customer> customerInDB = customerRepository.findByCode(customerCode);
if (!customerInDB.isPresent()) {
//call to remote service to get the customer from the remote service
Customer newCustomer = new Customer();
..some sets
return customerRepository.save(newCustomer);
}
return customerInDB.get();
}
I have the feeling that this is not the correct way to use the Java Optional, however, I don't really know if there is a better more functional approach
Solution
You may use Optional.orElseGet
private Customer getProjectCustomer(String customerCode) {
return customerRepository.findByCode(customerCode)
.orElseGet(() -> {
Customer newCustomer = new Customer();
// ...
return customerRepository.save(newCustomer);
});
}
Answered By - azro
Answer Checked By - Mary Flores (JavaFixing Volunteer)