What Is A Data Transfer Object?

As programmers, we inevitably come across the term Data Transfer Object (DTO). Sometimes they are also called a Data Structure or Model. The Model term is a bit imprecise as Domain Entities, which we will encounter tomorrow, are also models.

Why do we need DTOs? How do they differ from Domain Entities? I’ll look to answer these questions today and tomorrow.

So, what are DTOs?

Data Containers

DTOs hold data—and that’s all they do. They possess no or only very little behaviour. Consequently, DTOs should have few methods. 

No Encapsulation

DTOs are objects lacking Encapsulation. They do not protect their data—they grant clients full access to their data. Clients can read and alter the data inside a DTO—they are promiscuous.

Getters and Setters

In statically typed languages like C#, we implement DTOs as collections of declared setter and getter properties. In JavaScript and other dynamically typed languages, our job is even easier—we can set an object’s properties on the fly.

Let’s look at two DTO examples, one in C# and one in JavaScript:

C# Example: 

DTO Declaration:

  public class Customer
  {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public string FullName => $"{FirstName} {LastName}";
     public int Age { get; set; }
     // ...
  }

DTO Instantiation:

  var fred= new Customer
  {
     FirstName = "Fred",
     LastName = "Flintstone",
     Age = 38
  };

JavaScript Example: 

DTO Instantiation:

  const barney = {
     firstName: "Barney",
     lastName: "Rubble",
     fullName : function() {
        return this.firstName + " " + this.lastName;
     },
     age: 35,
  };

 

Purpose & Use

We need DTOs to move data around between services and application layers. For example, a request for data will return from the database with populated DTOs. These then get mapped onto other models before they enter the business logic. They are appropriate containers for receiving deserialised data coming from a remote service.

Conclusion

Data Transfer Objects are bags of data shunted between the different parts of a software application. They contain little or no logic and are not particularly interesting. However, we often need them in our programs. On the other hand, DTOs are not so good as the objects holding our business rules and other logic. We’ll encounter a better alternative for that purpose tomorrow.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply