Optional and complete method

53 Views Asked by At

How to work correctly with Optional if I need to complete a method (with some actions, log for example) in case of an empty Optional? Otherwise, get the object from Optional and continue working

I found similar problem https://stackoverflow.com/a/55393419/1460643 But there return is used in lambda

My code,

...
    var productOptional = productVersionMongoService.findById(crmProductId)
        .map(ProductVersion::getProductId)
        .flatMap(productMongoService::findById);
    Product product;
    if (productOptional.isEmpty()) {
      log.warn(...);
      return Collections.emptySet();
    } else {
      product = productOptional.get();
    }
...

So my question is, is it possible to refactor it to make the code more attractive?

1

There are 1 best solutions below

1
tgdavies On

I would write it like this, although it isn't completely clear from your question what gets returned in the case that a Product is found.:

Collection<Product> find(String crmProductId) {
        var productOptional = productVersionMongoService.findById(crmProductId)
                                       .map(ProductVersion::getProductId)
                                       .flatMap(productMongoService::findById);
        return productOptional.map(p -> {
            // ...
            return Collections.singleton(p);
        }).orElseGet(() -> {
            log.warn();
            return Collections.emptySet();
        });
    }