.netdesign-patternsdomain-driven-designdata-transfer-objects

Complex DTO structure


I've read a lot about DTO's here on SO, in books and articles, but I'm not sure if I get it right.

We're using DTO's in our project so that they're almost just properties of Domain Objects. For that reason, we need to have a complex DTO structure. There're some classes extending one another, compositions, aggregate, etc. .

Question is more general.

Is it right to inherit a dto from another one or to have a reference on a dto in another dto?


Solution

  • Is it right to inherit a DTO from another one

    If they share common properties, then why not?

    have a reference in a DTO to another DTO

    There is definitely nothing wrong with this, consider the following:

    public class UserDto
    {
        public string Id { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public AddressDto Address { get; set; }
    }
    
    public class AddressDto
    {
        public string AddressLine1 { get; set; }
        public string AddressLine2 { get; set; }
        public string City { get; set; }
    }
    

    Remember DTO's are simply dumb objects i.e. they have no behaviour (other than getting/setting their own data). The same rules apply to DTO's as they would for standard classes/objects from an architectural point of view, so there is no reason why you shouldn't be following the same principles if and when you can.