DTO
- Data Transfer Object (normally over the network). Some said this is anti pattern
- Helpful when you want to only expose a few properties (not the whole class).
- Mainly for serialisation or parsing
Example
For example, if we have the following class for our domain models:
public class User {
private String id;
private String name;
private String password;
private List<Role> roles;
public User(String name, String password, List<Role> roles) {
this.name = Objects.requireNonNull(name);
this.password = this.encrypt(password);
this.roles = Objects.requireNonNull(roles);
}
// Getters and Setters
String encrypt(String password) {
// encryption logic
}
}
public class Role {
private String id;
private String name;
// Constructors, getters and setters
}
Then the DTO could be as the following:
public class UserDTO {
private String name;
private List<String> roles;
// standard getters and setters
}
Since the DTO is to interact and sent to the API client, we hide the password and only display relevant information.
Note:
- DTO should not contains logic
- DTO should only be created if necessary