Reputation: 553
We are creating rest api's with Spring Boot. We have three layers in our project(Repository, Service and Controller).
Lets say I have GetUser api in my controller that return UserDTO
object.
@GetMapping
public UserDTO getUser() {
return userService.getUser();
}
Whether userService.getUser()
returns UserDTO
object or it returns User
object and it is converted to UserDTO
object in the controller? Which one is better way?
Shortly, domain object to DTO object conversion, should be done in service layer or controller layer?
Upvotes: 43
Views: 28416
Reputation: 503
Don't make your application/domain layer depend on infrastructure layer. As UserDTO in this case represents what goes to the "wire" this should definitely not be part of application/domain service.
Controller is responsible for adapting infra to application.
Upvotes: -1
Reputation: 224
Here is what I do in general:
My service layer takes dto as an argument. I do the conversion at the service layer, because I might need to apply some business logic when converting.
But my service layer always returns entity. And I do the conversion at the controller level. This makes my service is clean and independent of the consumer. It may happen that my service might be consumed by another service and need entity not the dto.
In summary:
Dto —> Entity (Service layer)
Entity —> Dto (Controller layer)
Upvotes: 3
Reputation: 340
In my experience, the conversion should be on the Controller layer. This gives an advantage that able to reuse other service methods with the return object is the origin.
This point may be important sometimes because the DTO object often reduce fields from the origin object. Therefore, we need more code to get these reduced fields, making our code ugly and duplicated.
I know that it would be moving logic to the controller layer, but it is a tradeoff.
Upvotes: 8
Reputation: 12677
It depends on application needs and architecture. Idea is to keep dto conversion at edge. It is generally prefer to have dto and domain conversion at the controller level. If you want to keep services/business logic independent of consumer, then it is always better to have at api level. This becomes more clear if your service has been consumed by more than one consumer.
Upvotes: 17
Reputation: 12021
I think there is no "better way" for converting your domain objects to your DTO objects, it's a matter of taste. In my projects I convert the domain objects to the DTO in the service layer as part of my "business logic". So you reduce the accessability of your domain objects only to your service layer. Furthermore I want to reduce the "logic" inside my controllers as they are part of the application layer.
PS: If you are looking for several ways to convert your domain objects to your DTOs have look at one of my latest Stackoverflow questions (How to properly convert domain entities to DTOs while considering scalability & testability)
Upvotes: 25