Search code examples
c#.netn-tier-architecture

How to write Data Transfer Object?


In my N-Tier Architecture I have DTO (AddressResponseDTO) where i have some 20 properties. When presentation layer request(AddressRequestContext) the response for particular search operation to my Business layer, i will send this DTO(AddressResponseDTO) to PL.

But this is not always the case. Address Search request will be changed Sometimes i need to send only 3 properties (lets say City ,Zip and address Count)of it and sometimes it could be 5. So can i still have the same DTO with 20 proerties to reuse all kind of search request.


Solution

  • As the OP states that sometimes only 3 of the properties are used, there can be several solutions:

    • Create a DTO with all the properties, and specifiy special values to show which properties aren't specificed (i.e. use nullables, or special values). This requires lots of checkings in the code.

    • Create a DTO with the 3 properties. Inherit a second DTO from this and add all the remaining properties. Your methods can receive the base class as parameter and check if a base or derived class is received. A simple check like if (myDto is DtoBase) ... will quickly show which properties have been sent with the DTO. (This will work only for increasing number of properties, in a hierarchy of inherited DTOs)

    • If there are more than one possible grouping of properties of interest, you can use a DTO class for each group and:

      • create a class which has this DTO as members. If you don't need them, leave them null. This way you can check each group with a simple if (containerDto.Dto1 != null)
      • define as many DTO parameters as you need for each case.

    I don't like the "special value" way, because it requires more code and it's more error prone. Besides, it makes you (de)serialize more info than neccessary on many occasions.