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).
e.g.
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;
}
Even though Inheritance in DTOs are a bad idea (that IMO should be avoided when possible), they're still generally supported, although most serializers require implementation-specific extensions in order to support it.
4. When to Use It? DTOs come in handy in systems with remote calls, as they help to reduce the number of them. DTOs also help when the domain model is composed of many different objects and the presentation model needs all their data at once, or they can even reduce roundtrip between client and server.
You should use the class approach, the struct approach could even be slower since structs are value types and copies will be made whereever you pass them as function parameters. So for your DTOs stick with the class aproach. Save this answer.
Although DTO is not an outdated pattern, it is often applied needlessly, which might make it appear outdated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With