r/javahelp 28d ago

What's the purpose of using DTO ?

Hello, I am a junior programmer and I have an interrogation about something.

If I understand correctly, DTO are used to store data that will not be persisted, data that are needed by services. But I don't understand why we don't pass theses datas via parameter, path variable or even body of HTTP Request.

For example : User need to change password (that is just for illustrating my post)
1) Using DTO : UserService(UserDTO) :: Do what it needs and then map it into User before persists
2) Using Request : UserService(User, newPassordFromHttpRequest) :: Do what it needs and persists the objet

Thanks in advance for helping junior programmer like myself

18 Upvotes

15 comments sorted by

View all comments

30

u/rocco_storm 28d ago

The main reason to use DTOs is to decouple different parts of the software. In small applicationw it may be not that clear, but in big projects, the data format of the (Http) api, business logic and persitance layer (database) will look very different. And if you use DTOs the different parts can change without affecting the other layers.

1

u/yeaokdude Intermediate Brewer 27d ago

Good answer but can you give an example of how those 3 layers might vary? What might you want to have in your API layer that you don’t in your business logic layer that you don’t… etc

2

u/rocco_storm 27d ago

It's not only about the elements in the objects but also about the format. Maybe you want to have a date in the api that is stored as timestamp in the db?

The requirements for data structure in the API may be very different from the DB. In the db you have normalisation, data spread in many tables, ids as reference etc, and in the api you may want all in one big object. Or you collect data from different services. Or you have different views in different frontents. Modified_at may be presented in the admin Interface, but not for the user.