Reputation: 1808
You know that for an API project there are many patterns to retrieve and serve data to client. Controller <-> Service <-> Dao
pattern is one of the these patterns.
Is it good to return any type of object from service layer or service layer return objects must be related entity?
For example, we have User
, UserService
, UserDao
.
Should UserService return types be User or any type of object is suitable?
Having logical operations in service layer force me to use other objects as return type.
What is the best practice for that case?
Upvotes: 8
Views: 2940
Reputation: 8656
I've found that I need 3 types of objects to keep things manageable (I'm still in a battle trying to come up with a decent naming strategy). It's sometimes beneficial to have:
Upvotes: 3
Reputation: 3564
The widely accepted practise involve the service to have all business logic in it and return the Data Transfer Object(DTO)/ Business Object like User in your case. The Service may call DAO, any other datasources to fetch the entities, and a mapper/converter util can be used to convert the entities to DTO objects.
The DTO objects returned from Service can be embedded in a ResponseEntity(In the case of Spring MVC) and returned from the controller.
This makes your application into 3 separated layers like web, service, dataaccess. This supports design principles like Separation of Concerns, Single Responsibility. This also makes your unit testing and code management easier.
Upvotes: 2