Sahil Mulla
Sahil Mulla

Reputation: 63

Why we need to write business logic in separate service layer instead of writing in controller itself?

Whats the use of creating different layer i.e. Service layer for business logic implementation instead of implementing that business logic in Controller itself

Upvotes: 0

Views: 3877

Answers (2)

Dennis Flagg
Dennis Flagg

Reputation: 664

It depends on your architecture. If you're using some of the Domain Driven Design principles, there would be little if any logic in the controllers/api. The controllers would be used to coordinate/ manage the communication between the domain services (i.e. AccountService), repositories (i.e. AccountRepo), and or infrastructure services (i.e. EmailService). All logic would be in the models and services. Some advantages are... 1. Unit testable code 2. The code better models the business problem (controllers mean nothing to the business problem) 3. Controllers don't become a place to jam a lot of business logic into and result into a tangled mess 4. And more...

Of course this all depends on whether maintainability is a priority

Upvotes: 4

Anunay
Anunay

Reputation: 1893

It is because of Separation of concerns. In Controller which is primarily interested in handling incoming http request and responding back to that request. We are worried about things related to handling stuff related to a given communication channel.

You can expose an rest api as well soap api or you may have various formats int which you would want to share the data. Biz logic as such does not care about how you are communicating this data to end users. So you take it out and keep in one common place that only deals with biz logic while the controller class just calls this. You can then have a rest controller and soap controller answering request via same piece of biz logic code.

What you do in controller is validate the request call the service and handle exception in way you want it to be exposed to the caller.

Upvotes: 5

Related Questions