-1

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

0

1 Answer 1

0

You may use Optional.orElseGet

private Customer getProjectCustomer(String customerCode) {
    return customerRepository.findByCode(customerCode)
            .orElseGet(() -> {
                Customer newCustomer = new Customer();
                // ...
                return customerRepository.save(newCustomer);
            });
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.