同一条件连续检查更多时间

Mat*_*o_B 1 java if-statement

我必须将操作(数据库查询或计算)的结果分配给返回变量,并在结果无效(null,empty,...)时最终执行另一次操作;但是,这种模式至少会发生两次,对我来说似乎是代码的味道。我应该以任何方式重构它吗?

String result = planA();
if(!isValid(result))
    result = planB();
if(!isValid(result))
    result = planC();
if(!isValid(result))
    result = planD();
return result;
Run Code Online (Sandbox Code Playgroud)

dav*_*xxx 7

您可以将其视为返回第一个有效结果的函数,因为那是您实际上所做的。

实际上,就预期行为而言,您当前的代码可以这样写:

String result = planA();
if(isValid(result))
    return planB();
if(isValid(result))
    return  planC();
if(isValid(result))
    return  planD();
return result;
Run Code Online (Sandbox Code Playgroud)

您可以使用以下函数将其排除:

public String computeResult(Supplier<String>... functions){
    String result = null;
    for (Supplier<String> function : functions){
       result = function.get();
       if (isValid(result)){
            return result;
       }
    }
    return result;    
}
Run Code Online (Sandbox Code Playgroud)

并称之为:

computeResult(this::planA, this::planB, this::planC, this::planD, ()-> this.planE(anyParam));
Run Code Online (Sandbox Code Playgroud)

或者,您可以在函数中用流替换循环:

public String computeResult(Supplier<String>... functions){
    return 
    Arrays.stream(functions)
          .filter(s-> isValid(s.get()))
          .findFirst()
          .orElse(functions.get(function.length-1)); 
          // if no valid return the last result function as in the initial code
}
Run Code Online (Sandbox Code Playgroud)