Reputation: 647
I'm working in a Spring Boot project, as my implement at the moment, almost for each 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 classes look like:
@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.
For example: There's two kind of Notice
: Email
and Notification
:
public class Email {
private String subject;
private String message;
private String receiver;
}
So, should I use an inner class that extends the common class or just put all the fields into one class? Which is 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 performs a request to add an Email
notice, will some fields be null?
Upvotes: 17
Views: 12611
Reputation: 130887
Using tailored DTOs for request and response will give you more flexibility in the long run. Actually, nothing prevents you from using inheritance and inner classes, but I would just avoid it.
I already answered a similar question here, highlighting the benefits of using DTOs over persistence entities in REST APIs. Below you'll find a few benefits of this approach:
@XmlTransient
and @JsonIgnore
to avoid the serialization of some attributes.@ApiModel
and @ApiModelProperty
annotations to document your API models without messing your persistence entities;Upvotes: 25
Reputation: 355
I will suggest you to use JSON format instead of creating class and returning its instance every time. But still if you need a class hierarchy you can create a class and put a variable which will store JSON.
Upvotes: 0
Reputation: 738
Don't subclass the req/resp objects.
Use an auto de/serialiser like Jackson in your frame work to convert message payloads into business object.
However, you will still end up with a large number of business objects.
Upvotes: 1