Performance: DTO pattern for data transfer
This pattern affects the amount of data sent over the network and the processing time on both client and server during data transfer.
Jump into concepts and practice - no test required
public class UserDTO { private String username; private String email; // getters and setters } @GetMapping("/users/{id}") public UserDTO getUser(@PathVariable Long id) { User user = userRepository.findById(id).orElse(null); if (user == null) return null; UserDTO dto = new UserDTO(); dto.setUsername(user.getUsername()); dto.setEmail(user.getEmail()); return dto; }
public class User { private Long id; private String username; private String password; private String email; private Date createdAt; // getters and setters } @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElse(null); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Sending full entity as JSON | N/A | N/A | High due to large JSON parsing | [X] Bad |
| Sending DTO with minimal fields | N/A | N/A | Low due to smaller JSON parsing | [OK] Good |
DTO (Data Transfer Object) in a Spring Boot application?getUserDTO() method is called?public record UserDTO(String name, int age) {}
public UserDTO getUserDTO() {
UserDTO user = new UserDTO("Alice", 30);
return new UserDTO(user.name(), user.age() + 5);
}public record ProductDTO(String name, double price) {}
public ProductDTO createProduct() {
ProductDTO product = new ProductDTO("Book");
return product;
}public class User {
private String username;
private String password;
private String email;
// getters and setters
}