samedi 8 janvier 2022

Which layer should decide to display the next view in Spring MVC?

I am building an application using the Spring MVC framework and there is an architectural issue that I cannot clearly resolve. My problem is that I don't fully understand which part (layer) of the application should be responsible for the control flow (by flow control I mean the display of successive views - pages).

Controllers in Spring MVC are some kind of adapter between the view and the application. Services, on the other hand, are implemented based on business logic.

Suppose we have a controller that supports a certain endpoint:

@GetMapping("/goToPageBasedOnLogic")
public ModelAndView passParametersWithModelAndView() {

    ModelAndView modelAndView = null; 
   
    // business logic calculates some stuff...
    if(fooService.bar()) { 
       modelAndView = new ModelAndView("viewPageHello");
       modelAndView.addObject("message", "hello");
    }
    else {
       modelAndView = new ModelAndView("viewPageGoodbye");
       modelAndView.addObject("message", "goodbye");
    }

    return modelAndView;
}

In the above example, the controller decides which view to display based on the result of the fooService, thus managing the flow of control. If there were many conditions, it could lead to ugly code in controller.

Let's consider the next example:

@GetMapping("/goToPageBasedOnLogic")
public ModelAndView passParametersWithModelAndView() {

    ModelAndView modelAndView = null; 
    
    session.fooBarResult = fooService.bar(); // logic calculates some stuff and saves in session
    State newState = stateMachine.sendEvent(PAGE_FINISHED_JOB); 
   
    if(newState == State.PAGE_HELLO) { 
       modelAndView = new ModelAndView("viewPageHello");
       modelAndView.addObject("message", "hello");
    }
    else {
       modelAndView = new ModelAndView("viewPageGoodbye");
       modelAndView.addObject("message", "goodbye");
    }

    return modelAndView;
}

In this example, the decision which view to display is made in terms of services and business logic. The state machine receives the event and then based on the session and the encoded conditions, it makes a decision to select the next view. Then the controller, based on the new state, prepares the correct view and returns it. The controller knows nothing about the control flow logic.

Which solution for deciding whether to display the next view (page) is better? Are there other more interesting solutions?

Aucun commentaire:

Enregistrer un commentaire