DEV Community

Discussion on: Do you always need to separate services and controllers?

Collapse
 
emilper profile image
Emil Perhinschi

The main advantage of having the business code separate from the controller is you can automate tests easily, assuming you really separated the business code from the controller and no "web server" or "web request" or "request context" etc. objects leak into the business code.

Think about your very simple "search" example: you want to write a test for the controller, you have to mock the server somehow and that can get painful, intricate, expensive and sometimes even unreliable.

If you can run the code in the "service" as instantiating some plain data objects and passing then to a function you can write tests easily and fast.

You might be mistaking complexity for size: writing services means more code but if all those services are not coupled and exchange only basic data structures or plain objects it will be a lot simpler and easier to work with them. Think about using Legos versus building something with custom pieces of plastic glued together.