Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to refactor this method which has multiple if/else statements

I have a feeling that this if/else should be refactored out but I'm unsure of what I can do, or whether I should just let it be as it is...

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;
}

Basically I have a reports summary page which lists three to four reports. First if condition is when the user wants to go back to that page, second condition is for when user has selected this particular report, and the third condition is for when the user selects this report as a stand alone report (not from summary page).

like image 220
Anthony Avatar asked Jul 28 '12 15:07

Anthony


2 Answers

First take a look at the Design Pattern Command. It should refactor the if/else's responsability, making it more organized and much more maintainable. And then you code should look like this:

Example

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

HERE You can gather more knowledge in command pattern

like image 110
waldyr.ar Avatar answered Oct 04 '22 03:10

waldyr.ar


If you absolutely want to change it, you could initialise url to the default return and only change it if one of the two conditions is met:

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;
}

But really, it's fine as is.

like image 26
Daniel Fischer Avatar answered Oct 04 '22 03:10

Daniel Fischer