I'm using the DTO pattern for managing HTTP bodies in a Spring Boot REST application. I have seperate DTOs for requests and responses as the response contains additional data. I'm using inheritance for the response DTO as the additional data included is the same for all response objects. The structure is as following (annotations and methods ommited for clearance):
public abstract class BaseResponseDTO {
protected UUID id;
protected Integer version;
protected Date created;
protected Date modified;
}
public class RequestUserDTO {
private String firstName;
private String lastName;
}
public class ResponseUserDTO extends BaseResponseDTO {
private String firstName;
private String lastName;
}
There is obvious code duplication here. It would be ideal for the ResponseUserDTO to extend both BaseResponseDTO and RequestUserDTO which is not allowed.
Other option would be to use composition and have something as follows:
public abstract class BaseResponseDTO {
protected UUID id;
protected Integer version;
protected Date created;
protected Date modified;
}
public class UserDTO {
private String firstName;
private String lastName;
}
public class RequestUserDTO {
private UserDTO payload;
}
public class ResponseUserDTO extends BaseResponseDTO {
private UserDTO payload;
}
The problems I have with this approach are:
- It still does not prevent code duplication
- It forces client to wrap the body in
payload
What can be done about that?