如何重构这个有多个if/else语句的方法

Ant*_*ony 4 java refactoring

我有一种感觉,这个if/else应该被重构,但我不确定我能做什么,或者我是否应该让它像它一样......

private String someReportUrl(HttpServletRequest request, HttpServletResponse response) {
    String url;
    if (isBackToReportsSummary(request)) {
        url = SUMMARY_PAGE;
        getReportsSummary(request, response);
    } else if (isComingFromPageA(request)) {
        url = getTabUrl(request, REPORT_URL_FOR_PAGE_A);
    }
    else {
        url = "/standAlone/reportUrl.jsp";
    }
    return url;
}
Run Code Online (Sandbox Code Playgroud)

基本上我有一个报告摘要页面,其中列出了三到四份报告.首先,如果条件是用户想要返回该页面,则第二个条件是用户选择此特定报告时的情况,第三个条件是用户选择此报告作为独立报告(而不是摘要页面) .

wal*_*.ar 6

首先来看看Design Pattern Command.它应该重构if/else责任,使其更有条理,更易于维护.然后您的代码应如下所示:

class ExampleServlet  {

  private HashMap commandMap = new HashMap();

  public ExampleServlet() {
    commandMap.put("create", new ActionTypeCreate());
    commandMap.put("replace", new ActionTypeReplace());
    commandMap.put("update", new ActionTypeUpdate());
    commandMap.put("delete", new ActionTypeDelete());
  } //endconstructor
} //endclass: ExampleServlet

private void performTask(String action) {
    ActionType cmd = (ActionType)commandMap.get(action);
    cmd.execute();
} //endmethod: performTask
Run Code Online (Sandbox Code Playgroud)

在这里你可以收集更多的命令模式知识


Dan*_*her 5

如果您绝对想要更改它,您可以初始化url为默认返回,只有在满足以下两个条件之一时才更改它:

private String someReportUrl(HttpServletRequest request, HttpServletResponse response) {
    String url = "/standAlone/reportUrl.jsp";
    if (isBackToReportsSummary(request)) {
        url = SUMMARY_PAGE;
        getReportsSummary(request, response);
    } else if (isComingFromPageA(request)) {
        url = getTabUrl(request, REPORT_URL_FOR_PAGE_A);
    }
    return url;
}
Run Code Online (Sandbox Code Playgroud)

但实际上,它很好.


Håv*_*hus 5

这种“基于守卫”的风格怎么样?它通常使方法更容易从上到下阅读。

private String someReportUrl(HttpServletRequest request, HttpServletResponse response) {
    if (isBackToReportsSummary(request)) {
        getReportsSummary(request, response);
        return SUMMARY_PAGE;
    } 
    if (isComingFromPageA(request)) {
        return getTabUrl(request, REPORT_URL_FOR_PAGE_A);
    }
    return "/standAlone/reportUrl.jsp";
}
Run Code Online (Sandbox Code Playgroud)

  • +1 我认为这是最好的方法 - 很清楚并消除了不必要的局部变量。 (2认同)