agthumoe
agthumoe

Reputation: 119

Spring Validation: Multiple DTOs vs single DTO with multiple validators

I need a user management service for my spring-boot project. I generally understand the use of DTO (Data transfer object) in spring. But when I'm thinking to design the service, I use multiple DTOs for just one "User" model, such as UserDTO, RegisterUserDTO, UpdateUserDTO, ManagedUserDTO.. UserDTO is like a readonly data (output data with username, email, name) which is used to display user information. But RegisterUserDTO is like an input data (with password, confirmPassword to create a password for new user) which is used for user registration form. UpdateUserDTO is for Admin, since admin can be able to assign Authorities, enable or disable user.

Another reason might be because of validation, so that different hibernate annotation validator can be applied on different DTOs.

Am I doing right with using a lot of DTOs? Should it be like one DTO by using multiple spring validators for validation?

Is there any other options to simplify it?

Upvotes: 5

Views: 2581

Answers (1)

Bunti
Bunti

Reputation: 1760

In my opinion having multiple DTOs is valid and leads to much cleaner logic.

  1. Having different DTOs allows exposing different and relevant information for the same User object in different circumstances
  2. You don't have to deal with one "big class" in validation because validation logic is different in different scenarios. If everything is in one class you'll have a hard time, specially in validation because some fields should not necessarily be validated in a given context. On the other hand this could cause to expose values that should not be exposed if not careful, for ex. password etc.
  3. Allows to use inheritance whenever possible. For example as you mentioned UserDTO contains general information pertaining to any user and RegisterUserDTO can inherit UserDTO without having to repeat the properties of UserDTO and validation annotations.

In addition to this you can also use Spring's conversion service to do the conversion for you between different DTOs and this conversion is totally decoupled from the core business logic. I see this not as an advantage but conversion service makes it less painful whenever there are many DTOs like this.

Upvotes: 6

Related Questions