我有一段代码,如果methodOne返回null,我将在其中调用methodTwo。如果methodTwo返回null,则调用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);
}
有更好的方法吗?
答案 0 :(得分:-1)
Optional
有一些非常强大的工具,它们不依赖if-then-else
流程。例如,查看Optional.orElse
函数来清理代码:
optionalWorkflow.orElse(featureBasedWorkflowProvider.getWorkflow(request))
您还可以使用orElseGet
返回一个lambda,它为您提供更多功能:
optionalWorkflow.orElseGet((value) -> {
log.info("Cannot find workflow using remoteWorkflowProvider");
return featureBasedWorkflowProvider.getWorkflow(request));
});