简体   繁体   中英

Should DTOs use inheritance or composition

In SOA if a few DTO classes have some fields that are repeated across. Is it better to use Composition or Inheritance so there is not repetition OR just use one DTO class that encapsulates all fields.As my DTO classes grow I see lot of repetitive field names and Sonar report is crying fowl. What is the best approach(or an alternative).

eg

public class DocDto{
    private Long id;
    private String name;
    private String docType
}

public class DocReviewDto{
    private Long id;
    private String name;
    private String status;
    private String comment;
}

The "one DTO class" approach is almost certainly bad. It smells like a God Class. Many pundits excoriate DTOs altogether. You could inherit from some base class, but for value objects it's not really sensible. Same for composition. It makes your code more complicated. When debugging the "DocReview" flow, you'd have to look at two, three, or more DTO classes to understand it with either approach. Bleagh! Also, each DTO is typically in a separate semantic domain: "Doc" is not "DocReview". So the apparent "common" elements are not actually common at all. They just share an implementation type; their meanings are quite different.

When the member type is inherently composite, for example if many domains share the concept of an Identifier , you could make that a type for composition into the DTOs for those domains. In your example, you might have

public class Identifier {
  long id; // should be a 'String', actually
  String name;
}

public class Doc {
  private Identifier identifier;
  private String docType
}

public class DocReview {
  private Identifier identifier;
  private String status;
  private String comment;
}

The key here is that Identifier is semantically equivalent in both domains, so it makes sense to have it as a common type. Otherwise you wouldn't do that.

Sidebar: "Dto" (or "DTO") as a suffix is not good naming, really.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM