Search code examples
jvmdesign-patternsdto

When does an object qualify as a DTO?


DTO (Data Transfer Objects) are objects used to transfer information between multiple subsystems of an application, often separated by either a network or a process boundary. This is my understanding.

However, from Java perspective, do the subsystems/modules have to be on different JVM instances for the objects they use between them to qualify as DTOs? (I believe that a significant demarcation in architecture in terms of modularity and functionality between the subsystems would be sufficient.) What say?

Also, considering the objects exchanged by multiple modules in the SAME layer/tier of an architecture, don't these objects qualify as DTOs? Is a tier separation mandatory?

Thanks in advance.

Regards,

Nagendra U M


Solution

  • Because transferring objects between tiers requires some kind of serialization it is considered a DTO. Transferring objects between layers is generally done through the use of domain entities thus not requiring serialization.

    So your DTOs generally do not have behavior only properties to hold data.

    A little note: DTOs are often mistaken for anemic objects when you have entities with no behavior, only data. Or poltergeist objects when objects are only used to transport data in and out of methods or classes and then disappear.

    As an example sometimes your data persistence mechanism requires you to implement or inherit interfaces or classes that you do not want to couple into your domain layer, so you create objects that inherit or implement the interface/class and transfer data to those classes for persistence.

    class Person{
    public string Name {get;set;}
    public int Age {get;set;}
    
    public void Validate(){}
    public void DoSomething(){}
    }
    
    
    
    public class PersonDTO : TableServiceContext
    {
    public const string ContactTableName = "PersonTable"
    
    public string Name {get;set;}
    public int Age {get;set;}
    
    }
    

    And you would generaly have a class to assemble and disassemble these objects.