Is it bad to create different classes for a REST request and a response?

I work in the Spring boot project, as in my project at the moment, for almost every API I have request and response classes.

For example:

@RequestMapping(value = "/notice", method = RequestMethod.POST)
public AddNoticeResponse addNotice(@Valid @RequestBody AddNoticeRequest){
    Notice notice = ... // creating new notice from AddNoticeRequest
    noticeRepository.save(notice);
    AddNoticeResponse response = ... // creating new response instance from Notice
    return response;
} 

The request and response class is as follows:

@Data
@AllArgsConstructor
public class AddNoticeRequest{
    private String subject;
    private String message;
    private Long timeToLive;
}
// Ommiting some annotations for brevity
public class AddNoticeResponse{
    private String subject;
    private String message;
    private Long timeToLive;
    private Date createTime;
    private String creator;
} 

I have two problems.

  • Creating too many classes and their names several times caused me nuts.
  • Some requests and answers have common fields.

For example: there are two types Notice: Emailand Notification:

public class Email {
    private String subject;
    private String message;
    private String receiver;
}

So, should you use an inner class that extends the general class or just puts all the fields in one class? What's better?

public class AddNoticeRequest {

    private String subject;
    private String message;

    class Email extends AddNoticeRequest{
        private String receiver;
    }
}
public class AddNoticeRequest{
    private String subject;
    private String message;
    private Long timeToLive;
    private String receiver;
}

Then, when the client completes the request to add a notification Email, will some fields be empty?

+4
3

DTO . , , .

, DTO persistence API REST. :

+6

req/resp.

-, Jackson, , -.

-.

+1

JSON . , , JSON.

0
source

Source: https://habr.com/ru/post/1625815/


All Articles