U
U
user_of_toster2021-07-04 11:56:29
Software design
user_of_toster, 2021-07-04 11:56:29

Controllers in one line VS smearing business logic in the controller - which is worse?

Controllers in one line:

  1. We comply with SRP - the controller is only engaged in processing requests and transferring control to the business logic.
  2. Easy to make changes when changing protocol (http to websockets, for example)
  3. We smack of an intermediary


Logic right in the controllers:
  1. We violate SRP (?) - the controller is engaged in both processing requests AND executing business logic
  2. When changing the protocol (http to websockets, for example), you will have to move the logic to a separate class
  3. We do not smell like an intermediary


The same analogy can be made with business logic in one or two lines, which all it does is pass the call to the repository. The question is which is worse and why? When to delegate, and when to write immediately on the spot?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-07-04
@user_of_toster

Definitely better to keep the business logic separate.
Separately, not only controllers, but in general from everything, even from the framework (in which case you can painlessly change the framework).
From experience, I can say that if the project is used, developed, it will be necessary to constantly make changes, and it is extremely difficult to do this when the business logic is "smeared" across controllers, even more difficult when requests to the database go directly from the controller, errors are inevitable. There will be many mistakes. And finding errors will not be easy.
It is much easier to cover separately implemented business logic with tests than when it is in controllers.
It is also not uncommon for some actions from the business logic side to be initiated either via HTTP, web sockets, GRPC, via cron, or even called from a background task. And here you will definitely have to take out the business logic from the controller. So it turns out that the logic is "smeared" not only in controllers, but also in other places, then it takes a very long time to deal with all this :)
I like the option when there are models (entities) that simply contain data + a minimum of methods, there is a repository , which only writes / reads data from the database and there are many small services that work with models and repositories + they can also have business logic. These same services are good to call in controllers.
On the other hand, if the project is very small, then it makes sense to save time and not bother much.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question