Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of a Data Transfer Object (DTO)?

Tags:

oop

Why should I use DTOs/Domain objects when I can just put all business classes in a class library, use them in the business logic, then also pass those same business objects on to boundary classes?

UPDATE: All are great points, thanks for the help. A follow up question:

Where do you typically place these DTOs? Alongside the Domain objects i.e. in the same namespace?

namespace MedSched.Medical
{
    public class MedicalGroup
    {
        //...
    }

    public class MedicalGroupDTO
    {
        //...
    }
}
like image 665
Aaron Avatar asked Apr 08 '09 00:04

Aaron


1 Answers

  • The DTO's provide an abstraction layer for your domain model. You can therefore change the model and not break the contract you have for your service clients. This is akin to a common practice in database design where views and procedures become the abstraction layer for the underlying data model.
  • Serialization - you may over expose data and send bloated messages over the wire. This may be mitigated by using serialization attributes, but you may still have extra information.
  • Implicit vs. Explicit Contracts - by exposing domain objects you leave it up to the client to interpret their usage since they do not have the full model at their disposal. You will often make updates to domain objects implicitly based on the presence or removal of associations, or blindly accept all changes. DTOs explicitly express the usage of the service and the desired operation.
  • Disconnected Scenarios - having explicit messages or DTOs would make it easier for you to implement messaging and messaging patterns such as Message Broker, etc.
  • DDD - pure DDD demands that domain objects are externally immutable, and therefore you must offload this to another object, typically a DTO.
like image 161
Adam Fyles Avatar answered Sep 25 '22 14:09

Adam Fyles