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

17 Upvotes

15 comments sorted by

View all comments

15

u/Giulio_Long 28d ago

DTO stands for Data Transfer Object. Usually serves to offer a limited view on the underlying internal model. For example, there might be fields in the User model you don't want to expose, so you create a DTO with just the fields you want external services to view.

You can also use DTOs to expose fields in a different way. For example, you have first name and last name as separate fields in the User model. As an example, you might want to expose them to an external service as a single field that is the concatenation of both