0

I have a block of code where I call methodTwo if methodOne returns null. If methodTwo returns null, I call methodThree

Optional<Workflow> optionalWorkflow = remoteWorkflowProvider.getWorkflow(request);

if (!optionalWorkflow.isPresent()) {
  log.info("Cannot find workflow using remoteWorkflowProvider");
  optionalWorkflow = featureBasedWorkflowProvider.getWorkflow(request);
}

if (!optionalWorkflow.isPresent()) {
  log.info("Cannot find workflow using featureBasedWorkflowProvider");
  optionalWorkflow = legacyWorkflowProvider.getWorkflow(request);
}

Is there a better way of doing this?

zeke00757
  • 31
  • 2
  • You could put together a list of providers, and then loop through them and break if `optionalWorkflow.isPresent()` – WOUNDEDStevenJones Mar 26 '19 at 19:34
  • 1
    [`first().or(() -> second()).or(() -> third())`](https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#or-java.util.function.Supplier-) – Michael Mar 26 '19 at 19:34
  • @Michael admirable choice not answering considering the current trend. I'd offer you a coffee. – LppEdd Mar 26 '19 at 19:50

1 Answers1

-1

Optional has some really powerful tools that don't rely on if-then-else flows. Look up the Optional.orElse function for instance to clean up your code a bit:

optionalWorkflow.orElse(featureBasedWorkflowProvider.getWorkflow(request))

You can also use orElseGet to return a lambda which gives you more functionality:

optionalWorkflow.orElseGet((value) -> {
   log.info("Cannot find workflow using remoteWorkflowProvider");
   return featureBasedWorkflowProvider.getWorkflow(request));
});
Yserbius
  • 1,375
  • 12
  • 18