r/SpringBoot • • Feb 25 '24

Map dto in controller

Hi my manager tell me that best practice is to map the returned dto from service layer in controller not in service Would any one agree with this ? My knowledge is the controller just one line and just delegate the logic to service layer and just return the response entity

23 Upvotes

35 comments sorted by

View all comments

12

u/BackpackerSimon Feb 25 '24

Because you might need to use a service in another service. Then you are mixing domain objects. Dtos are the external contract so in my work are the controllers problem to convert to/ from the entity objects

4

u/WaferIndependent7601 Feb 25 '24

Other services should not know about entities. Only dtos

1

u/BackpackerSimon Feb 25 '24

What do you do if the controller needs to return less data? Transform it again? The controller is the boundary

1

u/WaferIndependent7601 Feb 25 '24

Create another method and return the dto with the needed data

1

u/BackpackerSimon Feb 25 '24

In my experience, adding stuff like this might be ‘book correct’ or useful in massive code bases, but until it is required it is just more boilerplate to get passed for the answers.

I am currently removing mapstruct in favour of a single method on the dto to convert to and from the entity. Slightly more code for me to write, but 2 less hops when I need to debug the code (which happens a lot more) so it is easier to keep the flow in your head