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

4

u/JustHereForTheCh1cks Feb 25 '24

What is the reasoning behind your „a controller method should consist only of one line of code“?

-1

u/ahmedzahran94 Feb 25 '24

Yes that’s my reasoning

4

u/JustHereForTheCh1cks Feb 25 '24

So far it is just a statement. What are the reasons for that statement? -Why- do you think a controller should consist only of one-line-methods?

1

u/ahmedzahran94 Feb 25 '24

Ooh sorry in my opinion controller should only validate request and delegate the business logic to service and just return the response without making any changes in controller just one line of code

5

u/JustHereForTheCh1cks Feb 25 '24 edited Feb 25 '24

And you are correct in the way that the controller should not execute any business logic. It has other responsibilities tho. Validation is just one of those responsibilities. In general, the controller (say, api or representation layer) is responsible for transforming the information it gets from the business layer into a representation that it’s clients understand. That cannot always be done in one line.

The controller might need to set a cookie for its clients. The controller might need to transform the data it gets into a hateoas compliant (say, Hal style) form.

The controller might not be a service api, it could also be a html api that needs to do more that just return the data from the business layer.

The controller might not even be a controller at all, it might be a component that transforms data from the business layer for a event queue.

You won’t be able to fulfill all of these responsibilities in one line of code, hence I question that rule.

The reason why we separate those concerns is, You don’t want any of these responsibilities to leak into your business logic, for example, having a hateoas rest api, you don’t want to return json data enriched with hal uris from your business layer, because that would leak technical code into your business logic, thus making it difficult to change the business logic without changing the technical code of your application and vice versa.

Given that, you should not reduce yourself to simple rules like „my controller is only allowed to consist of one line of code“ because that will lead you to leak technical code from your controller into your business layer.