Home > Back-end >  Proper way to create and return a DTO from a controller?
Proper way to create and return a DTO from a controller?

Time:06-24

First of all, the question may sound broad, but let me be specific.

Through past questions, I understood the role and usage of the DTO in my own way.

But after seeing a lot of code that I wrote my way, I still have my doubts.

First, I'll show you the code I've actually implemented now.

public ResponseEntity<UserDashBoardRes.UserInfoListRes> findUserInfoList(){
return ResponseEntity.status(200).body(new UserDashBoardRes.UserInfoListRes(userDashBoardService.findUserInfoList()));
}

I didn't want to create every DTO as a separate class file, so I implemented it as an inner class.

As a result the response object

ResponseEntity<UserDashBoardRes.UserInfoListRes>

It seems that something is difficult to recognize at first glance.

Then, in order to use the DTO, we need to create a DTO object.

So, by listing the new constructor, DTO name, and its parameters, it seems difficult to recognize at a glance again this time.

new UserDashBoardRes.UserInfoListRes(userDashBoardService.findUserInfoList())

But I can't think of a way to properly create and return a DTO other than this way.

Am I wrong? Is there a more appropriate way?

CodePudding user response:

A data transfer object (DTO) is a model class which packages data to be transferred between system components. From that perspective, technically, it can be an inner class. There is truly nothing 'right' or 'wrong' here, it depends on your design choices for your application.

However, all DTOs as an inner classes is slightly unusual design choice. In general the DTOs are kept in their package as separate classes and used. One advantage is the clear separation of concern. In your case, it is somewhat difficult to determine that the 'UserInfoListRes' is a DTO by glancing through the code base. To mitigate that you could document the class and have some naming convention for all the DTO classes.

  • Related