Why use DTOs (Data Transfer Objects)?
Tags: architecture, webdev
Published: 2020-05-13 23:35:27

---
title: Why use DTOs (Data Transfer Objects)?
published: true
date: 2020-05-13 23:13:03 UTC
tags: Architecture, webdevelopment, webdev
canonical_url: https://codeopinion.com/why-use-dtos-data-transfer-objects/?utm_source=rss&utm_medium=rss&utm_campaign=why-use-dtos-data-transfer-objects
---

![Data Transfer Objects](https://codeopinion.com/wp-content/uploads/2020/05/DataTransferObjects-1024x536.png)

Should you really use DTOs (Data Transfer Objects)? Seem like a lot of work mapping your database entities to another object? Why Bother? The simple answer is coupling.

## Data Transfer Objects

First, what are DTOs? When people refer to Data Transfer Objects, what they mean are objects that represent data structures that generally do not contain any business logic or behavior. If they do contain behavior, it’s generally trivial.

Data Transfer Objects are often used to be serialized by the producer and then deserialized by the consumer. Often times these consumers may live in another process being used by an entirely different language and/or platform.

## YouTube

I’ve recorded a short video explaining this with some sample code. Check out the video and make sure to [subscribe to my YouTube Channel](https://www.youtube.com/channel/UC3RKA4vunFAfrfxiJhPEplw?sub_confirmation=1).

<iframe title="Why use DTOs (Data Transfer Objects)?" width="648" height="365" src="https://www.youtube.com/embed/JJT1xykf1do?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

## Crossing Boundaries

The most common example of this is creating an HTTP API using ASP.NET Core that returns an object from its Controller actions that are ultimately serialized to JSON. The consumer is oftentimes JavaScript that uses those JSON responses in displaying the browser using a Component or SPA Framework.

## Internals

If you’re not using DTOs, then you’re likely exposing internal data structures.

The biggest culprit of this is simple TODO demo applications that expose the database entities directly. Meaning they output a serialized list of TODOs to the javascript frontend. And when you want to create a new record, they often times take the TODO object to insert directly into the database. This is leaking internals.

This is my biggest complaint with simple demo applications are they often don’t implement or follow some practices, because rightly so, they aren’t applicable to a simple TODO application. However, people take the example of a simple TODO and use the same patterns into a much large application.

The problem is when internal data objects are serialized and consumed by a client you either down own or cannot change easily. Or, which happens more often, the application itself gets very large.

## Contracts

The moment you want change internal data objects, you now have to update the clients.

Take this simple example of a Customer that is an internal data structure we use through the system and likely use to persist using an ORM.

View the code on [Gist](https://gist.github.com/dcomartin/a40b8144b0e21e16ef409a17e0cf20da).

If we are serializing this structure and clients are consuming this, if we change this structure, we’re likely going to break out clients.

View the code on [Gist](https://gist.github.com/dcomartin/2a9ffeefd9e7af5dd034ed1f51e448eb).

This change would require a change to all of our clients. We could easily make this change in our own codebase and have all our own usages be correct, but we would be breaking all of our decoupled clients that get a serialized representation.

## Representation

When creating an HTTP API, it’s all about representations. Most often times clients need a rich representation of a resource, not a just serialized version of a database entity. They often times need related data.

Having your API return rich representations means you must do some level of composition to create an object, not just a database entity, that will get serialized. This is where a DTO comes into play.

I actually don’t often use the term DTO, but rather use the word Representation or ViewModel. The purpose is still the same, it’s a data structure that is a contract between the producer and the consumer. That contract should remain stable (through backwards compatibility) or have a versioning strategy.

## Coupling

The reason you want to use DTOs is that you want clients to couple to that contract, not to your internal data structures. This allows you to modify and evolve your internals freely without breaking clients.

## Links

- [Building a Self Descriptive HTTP API in ASP.NET Core](https://codeopinion.com/building-self-descriptive-http-api-asp-net-core/)
- [Object as Resource](https://codeopinion.com/self-descriptive-http-api-in-asp-net-core-object-as-resource/)

[Follow @codeopinion](https://twitter.com/codeopinion?ref_src=twsrc%5Etfw)<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><script>(function() {
	window.mc4wp = window.mc4wp || {
		listeners: [],
		forms: {
			on: function(evt, cb) {
				window.mc4wp.listeners.push(
					{
						event : evt,
						callback: cb
					}
				);
			}
		}
	}
})();
</script><!-- Mailchimp for WordPress v4.7.7 - https://wordpress.org/plugins/mailchimp-for-wp/ --><form id="mc4wp-form-1" method="post" data-id="5348" data-name="Weekly Updates">
<div><div>
	<div>
      <div>      
      </div>
      <div>
        <div>
          <h2>Enjoy this post? Subscribe!</h2>

          <p>Subscribe to our weekly Newsletter and stay tuned.</p>

          <div>
            <span>
              <i></i>
            </span>
            <input type="text" name="EMAIL" placeholder="your@email.com">
          </div>

          <input type="submit" value="Subscribe">

        </div>    
      </div>
      <div>      
      </div>
	</div>
</div></div>
<label style="display: none !important;">Leave this field empty if you're human: <input type="text" name="_mc4wp_honeypot" value="" tabindex="-1" autocomplete="off"></label><input type="hidden" name="_mc4wp_timestamp" value="1589412618"><input type="hidden" name="_mc4wp_form_id" value="5348"><input type="hidden" name="_mc4wp_form_element_id" value="mc4wp-form-1"><div></div>
</form><!-- / Mailchimp for WordPress Plugin -->

The post [Why use DTOs (Data Transfer Objects)?](https://codeopinion.com/why-use-dtos-data-transfer-objects/) appeared first on [CodeOpinion](https://codeopinion.com).