0

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:

  1. It still does not prevent code duplication
  2. It forces client to wrap the body in payload

What can be done about that?

mac501
  • 37
  • 5

1 Answers1

0

I think you could replace both your ResponseUserDTO and RequestUserDTO with UserDTO and extend BaseResponseDTO on it, when you send a request body using UserDTO the code won't care if you send it along with the BaseResponseDTO or not (since I didn't see any validation here), so if you not gonna use those in your request function it will be just fine

public abstract class BaseResponseDTO {
      protected UUID id;
      protected Integer version;
      protected Date created;
      protected Date modified;
}
public class UserDTO extends BaseResponseDTO {
      private String firstName;
      private String lastName;
}
Tan Sang
  • 320
  • 2
  • 10
  • Thank you for your effort! The end goal is to have validation at some point. Honestly there isn't a better reason for me to use seperate DTOs other than me just trying to learn best practices. This approach is just avoiding the problem I'm afraid – mac501 Oct 28 '22 at 12:47