Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which layer should be used for conversion to DTO from Domain Object

Tags:

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?

like image 572
Suleyman Arıkan Avatar asked Dec 14 '17 22:12

Suleyman Arıkan


People also ask

Where DTO should be implemented in a domain layer or in an application service layer?

Define the DTO to the layer where the source of the values comes from. Relative to OP's question: place the DTO in the Application Service Layer. DTO is an output of that layer, it makes sense if you define it there. Don't put your DTO in the Domain Layer.

Should DTO be in service layer?

Not only you could pass DTO objects to Service Layer, but you should pass DTO objects instead of Business Entities to Service Layer. Your service should receive DTOs, map them to business entities and send them to the repository.

What layer should DTOs be?

Popular Answer. Your service layer exposes DTO's. This means that in the service layer you define data contracts as you would like them to be exposed to the outside world.


1 Answers

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)

like image 147
rieckpil Avatar answered Sep 19 '22 11:09

rieckpil