What would be a class of services in an MVC Java project?

0

Could you tell me the difference between classes in the "control" package in an MVC project and service classes?

    
asked by anonymous 10.11.2018 / 12:15

1 answer

2

Citing Spring MVC as an example I like to separate the MVC project into Model, View, Control and Service. The reason is that in my projects I do not really like to leave business rules directly on the Controller. Then I delegate this to the Service. Example:

@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView cadastrar(@Valid Cerveja cerveja, BindingResult result, Model model, RedirectAttributes attributes) {

    if (result.hasErrors()) {
        return novo(cerveja);
    }

    /* Eu poderia deixar dezenas de linhas relativas as regras de negócio 
       de como salvar uma cerveja aqui. */
    cadastroCervejaService.salvar(cerveja);
    attributes.addFlashAttribute("mensagem", "Cerveja salva com sucesso!");

    return new ModelAndView("redirect:/cervejas/novo");
}

In this code, the Controller basically only receives data from the View and returns validation errors (if any). If it has no errors, it triggers the Service to save the record and returns a success message.

The point here is that every business rule saving a Beer object could be inside the Controller, but the Controller would receive, save, and return data. What if there were too many business rules? It would make the code very polluted so I transferred all the business rules pertaining to saving a Beer to the CadastroCervejaService . So the Controller just calls.

In my opinion, it's more of a taste decision, I prefer it that way because of organization.

    
10.11.2018 / 13:28