Patterncore
Data transfer object
Also called Data Transfer Object, DTO, Transfer Object, transfer object pattern.
A data transfer object holds all the data for one remote call, so the call can carry it in one message. An assembler copies the data between it and the domain objects.
- Family
- architectural
- Intent
- An object that carries data between processes in order to reduce the number of method calls.
Intent
A data transfer object (DTO) is "An object that carries data between processes in order to reduce the number of method calls."1 It holds all the data that one remote call sends or returns, and it has no domain behavior. It is the usual partner of a Remote facade.12
Problem
A remote interface must be coarse-grained, because each remote call is expensive. So each call must carry more data. Fowler: "One way to do this is to use lots of parameters. However, this is often awkward to program".1 A method in Java can also return only one value.1
The server cannot simply send its domain objects. They are often a graph of objects with references, which the client cannot use from another process. They hold data that must stay on the server, such as a password hash or a cost price. And if the client depends on the form of the domain objects, each change to them breaks the client.
Solution
"The solution is to create a Data Transfer Object that can hold all the data for the call. It needs to be serializable to go across the connection. Usually an assembler is used on the server side to transfer data between the DTO and any domain objects."1
The parts are:
- The DTO. A plain object with fields for the data of one call. It has no behavior, except perhaps the code that serializes it. Its shape follows the needs of the call, not the shape of the domain objects.
- The serialization. The DTO knows how to change itself into text or bytes for the wire and back. Fowler notes that this is a second benefit: "another advantage is to encapsulate the serialization mechanism for transferring data over the wire."1
- The assembler. On the server, it reads the domain objects to fill a DTO, and it uses a DTO from the client to update the domain objects. The domain objects and the DTOs do not know each other.
server client
domain objects --assembler--> DTO --wire--> DTO (a copy)
(Customer, (only the data reads and changes
Order, Line) <--assembler-- for this call) <--wire-- its copy
In the following program, the product on the server has a cost price. The assembler copies only the name and the price into the DTO, and the DTO goes over the wire as JSON.
import json
from dataclasses import asdict, dataclass
class Product: # a domain object, with data that stays on the server
def __init__(self, name, price, cost_price):
self.name, self.price, self.cost_price = name, price, cost_price
@dataclass
class ProductDTO: # only the data for this call, in a form that can be serialized
name: str
price: int
def assemble(product): # the assembler, on the server
return ProductDTO(product.name, product.price)
wire = json.dumps(asdict(assemble(Product("lamp", 2500, 1400))))
received = ProductDTO(**json.loads(wire))
print(received)
ProductDTO(name='lamp', price=2500)
Example
Each example file has a customer on the server, with an email, a password hash and two orders, and each line of an order has a cost price. CustomerDTO holds only the name, the email, and the number and the total of each order. The assembler fills the DTO from the customer, and later updates the customer from a DTO that the client sends back; it copies back only the name and the email. The program shows that the password hash is not on the wire, that a change on the client changes only the copy, and that the server changes only when the client sends the DTO back.
import json
from dataclasses import asdict, dataclass, field
def cents(n):
return f"{n // 100}.{n % 100:02d}"
# Domain objects on the server. Some data must never leave the server.
class Line:
def __init__(self, item, qty, price, cost_price):
self.item, self.qty, self.price, self.cost_price = item, qty, price, cost_price
class Order:
def __init__(self, number, lines):
self.number, self.lines = number, lines
def total(self):
return sum(l.qty * l.price for l in self.lines)
class Customer:
def __init__(self, name, email, password_hash, orders):
self.name, self.email, self.password_hash, self.orders = name, email, password_hash, orders
# Data transfer objects: only data, shaped for one remote call, and able to serialize themselves.
@dataclass
class OrderSummaryDTO:
number: int
total: int
@dataclass
class CustomerDTO:
name: str
email: str
orders: list = field(default_factory=list)
def to_wire(self):
return json.dumps(asdict(self))
@staticmethod
def from_wire(text):
d = json.loads(text)
return CustomerDTO(d["name"], d["email"], [OrderSummaryDTO(**o) for o in d["orders"]])
# The assembler moves the data between the domain objects and the DTOs, on the server.
class CustomerAssembler:
@staticmethod
def to_dto(customer):
return CustomerDTO(customer.name, customer.email, [OrderSummaryDTO(o.number, o.total()) for o in customer.orders])
@staticmethod
def update_from(dto, customer):
customer.name, customer.email = dto.name, dto.email # the orders are read only
ann = Customer("Ann", "ann@example.com", "pbkdf2:9f86d081", [
Order(7, [Line("lamp", 2, 2500, 1400), Line("desk", 1, 7500, 5100), Line("pen", 4, 500, 90)]),
Order(8, [Line("chair", 1, 4000, 2600)]),
])
# Server: one call returns all the data that the screen needs.
wire = CustomerAssembler.to_dto(ann).to_wire()
print("password hash on the wire:", "yes" if ann.password_hash in wire else "no")
# Client: it reads the DTO, and changes its own copy.
dto = CustomerDTO.from_wire(wire)
print(f"client: {dto.name} <{dto.email}>, {len(dto.orders)} orders")
for o in dto.orders:
print(f" order {o.number}: {cents(o.total)}")
dto.email = "ann@example.org"
print("server after a change on the client:", ann.email)
# Client sends the DTO back; the assembler updates the domain object.
CustomerAssembler.update_from(CustomerDTO.from_wire(dto.to_wire()), ann)
print("server after the update call:", ann.email)
password hash on the wire: no
client: Ann <ann@example.com>, 2 orders
order 7: 145.00
order 8: 40.00
server after a change on the client: ann@example.com
server after the update call: ann@example.org
- Verdict: idiom. The DTOs are dataclasses, so they have fields, a constructor and an equality test, and no behavior of their own.
to_wireandfrom_wirekeep the serialization in one place, withjsonanddataclasses.asdict. - The assembler copies only the fields that the client needs. The password hash and the cost prices stay on the server, and
update_fromcopies back only the fields that a client may change.
import java.util.ArrayList;
import java.util.List;
public class Main {
static String cents(long n) {
return String.format("%d.%02d", n / 100, n % 100);
}
// Domain objects on the server. Some data must never leave the server.
record Line(String item, int qty, long price, long costPrice) {}
record Order(int number, List<Line> lines) {
long total() { return lines.stream().mapToLong(l -> l.qty() * l.price()).sum(); }
}
static class Customer {
String name, email;
final String passwordHash;
final List<Order> orders;
Customer(String name, String email, String passwordHash, List<Order> orders) {
this.name = name;
this.email = email;
this.passwordHash = passwordHash;
this.orders = orders;
}
}
// Data transfer objects: only data, shaped for one remote call, and able to serialize themselves.
record OrderSummaryDTO(int number, long total) {}
static class CustomerDTO {
String name, email;
final List<OrderSummaryDTO> orders;
CustomerDTO(String name, String email, List<OrderSummaryDTO> orders) {
this.name = name;
this.email = email;
this.orders = orders;
}
// One value on each line: the name, the email, and then one line for each order.
String toWire() {
StringBuilder b = new StringBuilder(name + "\n" + email + "\n");
for (OrderSummaryDTO o : orders) b.append(o.number()).append(' ').append(o.total()).append('\n');
return b.toString();
}
static CustomerDTO fromWire(String text) {
String[] lines = text.split("\n");
List<OrderSummaryDTO> orders = new ArrayList<>();
for (int i = 2; i < lines.length; i++) {
String[] p = lines[i].split(" ");
orders.add(new OrderSummaryDTO(Integer.parseInt(p[0]), Long.parseLong(p[1])));
}
return new CustomerDTO(lines[0], lines[1], orders);
}
}
// The assembler moves the data between the domain objects and the DTOs, on the server.
static class CustomerAssembler {
static CustomerDTO toDTO(Customer c) {
List<OrderSummaryDTO> orders = c.orders.stream().map(o -> new OrderSummaryDTO(o.number(), o.total())).toList();
return new CustomerDTO(c.name, c.email, orders);
}
static void updateFrom(CustomerDTO dto, Customer c) {
c.name = dto.name; // the orders are read only
c.email = dto.email;
}
}
public static void main(String[] args) {
Customer ann = new Customer("Ann", "ann@example.com", "pbkdf2:9f86d081", List.of(
new Order(7, List.of(new Line("lamp", 2, 2500, 1400), new Line("desk", 1, 7500, 5100),
new Line("pen", 4, 500, 90))),
new Order(8, List.of(new Line("chair", 1, 4000, 2600)))));
// Server: one call returns all the data that the screen needs.
String wire = CustomerAssembler.toDTO(ann).toWire();
System.out.println("password hash on the wire: " + (wire.contains(ann.passwordHash) ? "yes" : "no"));
// Client: it reads the DTO, and changes its own copy.
CustomerDTO dto = CustomerDTO.fromWire(wire);
System.out.println("client: " + dto.name + " <" + dto.email + ">, " + dto.orders.size() + " orders");
for (OrderSummaryDTO o : dto.orders) System.out.println(" order " + o.number() + ": " + cents(o.total()));
dto.email = "ann@example.org";
System.out.println("server after a change on the client: " + ann.email);
// Client sends the DTO back; the assembler updates the domain object.
CustomerAssembler.updateFrom(CustomerDTO.fromWire(dto.toWire()), ann);
System.out.println("server after the update call: " + ann.email);
}
}
password hash on the wire: no
client: Ann <ann@example.com>, 2 orders
order 7: 145.00
order 8: 40.00
server after a change on the client: ann@example.com
server after the update call: ann@example.org
- Verdict: idiom.
OrderSummaryDTOis a record.CustomerDTOis a class, because the client changes its email. In a real application, a library such as Jackson would serialize the DTOs to JSON. Here,toWirewrites one value on each line, so the example needs only the standard library, and a name or an email that has a line break would break this simple format. - The Core J2EE patterns call this pattern the Transfer Object.
const cents = (n) => `${Math.floor(n / 100)}.${String(n % 100).padStart(2, "0")}`;
// Domain objects on the server. Some data must never leave the server.
class Line {
constructor(item, qty, price, costPrice) { Object.assign(this, { item, qty, price, costPrice }); }
}
class Order {
constructor(number, lines) { this.number = number; this.lines = lines; }
total() { return this.lines.reduce((s, l) => s + l.qty * l.price, 0); }
}
class Customer {
constructor(name, email, passwordHash, orders) { Object.assign(this, { name, email, passwordHash, orders }); }
}
// Data transfer objects: only data, shaped for one remote call, and able to serialize themselves.
class CustomerDTO {
constructor(name, email, orders) { this.name = name; this.email = email; this.orders = orders; }
toWire() { return JSON.stringify(this); }
static fromWire(text) {
const d = JSON.parse(text);
return new CustomerDTO(d.name, d.email, d.orders.map((o) => ({ number: o.number, total: o.total })));
}
}
// The assembler moves the data between the domain objects and the DTOs, on the server.
const CustomerAssembler = {
toDTO(customer) {
return new CustomerDTO(customer.name, customer.email, customer.orders.map((o) => ({ number: o.number, total: o.total() })));
},
updateFrom(dto, customer) {
customer.name = dto.name; // the orders are read only
customer.email = dto.email;
},
};
const ann = new Customer("Ann", "ann@example.com", "pbkdf2:9f86d081", [
new Order(7, [new Line("lamp", 2, 2500, 1400), new Line("desk", 1, 7500, 5100), new Line("pen", 4, 500, 90)]),
new Order(8, [new Line("chair", 1, 4000, 2600)]),
]);
// Server: one call returns all the data that the screen needs.
const wire = CustomerAssembler.toDTO(ann).toWire();
console.log("password hash on the wire:", wire.includes(ann.passwordHash) ? "yes" : "no");
// Client: it reads the DTO, and changes its own copy.
const dto = CustomerDTO.fromWire(wire);
console.log(`client: ${dto.name} <${dto.email}>, ${dto.orders.length} orders`);
for (const o of dto.orders) console.log(` order ${o.number}: ${cents(o.total)}`);
dto.email = "ann@example.org";
console.log("server after a change on the client:", ann.email);
// Client sends the DTO back; the assembler updates the domain object.
CustomerAssembler.updateFrom(CustomerDTO.fromWire(dto.toWire()), ann);
console.log("server after the update call:", ann.email);
password hash on the wire: no
client: Ann <ann@example.com>, 2 orders
order 7: 145.00
order 8: 40.00
server after a change on the client: ann@example.com
server after the update call: ann@example.org
- Verdict: idiom.
JSON.stringifyserializes the own fields of the DTO, so the DTO must hold only the data for the wire. If the server passed theCustomerobject itself,JSON.stringifywould send thepasswordHashfield too. fromWirebuilds new objects from the parsed data, so the client never gets a reference to an object on the server.
package main
import (
"encoding/json"
"fmt"
"strings"
)
func cents(n int) string { return fmt.Sprintf("%d.%02d", n/100, n%100) }
// Domain objects on the server. Some data must never leave the server.
type Line struct {
item string
qty, price, costPrice int
}
type Order struct {
number int
lines []Line
}
func (o Order) Total() int {
t := 0
for _, l := range o.lines {
t += l.qty * l.price
}
return t
}
type Customer struct {
name, email, passwordHash string
orders []Order
}
// OrderSummaryDTO and CustomerDTO are the data transfer objects: only data,
// shaped for one remote call. The struct tags give their form on the wire.
type OrderSummaryDTO struct {
Number int `json:"number"`
Total int `json:"total"`
}
type CustomerDTO struct {
Name string `json:"name"`
Email string `json:"email"`
Orders []OrderSummaryDTO `json:"orders"`
}
func (d CustomerDTO) ToWire() string {
b, _ := json.Marshal(d)
return string(b)
}
func FromWire(text string) CustomerDTO {
var d CustomerDTO
_ = json.Unmarshal([]byte(text), &d)
return d
}
// The assembler moves the data between the domain objects and the DTOs, on the server.
func ToDTO(c *Customer) CustomerDTO {
d := CustomerDTO{Name: c.name, Email: c.email}
for _, o := range c.orders {
d.Orders = append(d.Orders, OrderSummaryDTO{o.number, o.Total()})
}
return d
}
func UpdateFrom(d CustomerDTO, c *Customer) {
c.name, c.email = d.Name, d.Email // the orders are read only
}
func main() {
ann := &Customer{"Ann", "ann@example.com", "pbkdf2:9f86d081", []Order{
{7, []Line{{"lamp", 2, 2500, 1400}, {"desk", 1, 7500, 5100}, {"pen", 4, 500, 90}}},
{8, []Line{{"chair", 1, 4000, 2600}}},
}}
// Server: one call returns all the data that the screen needs.
wire := ToDTO(ann).ToWire()
leak := "no"
if strings.Contains(wire, ann.passwordHash) {
leak = "yes"
}
fmt.Println("password hash on the wire:", leak)
// Client: it reads the DTO, and changes its own copy.
dto := FromWire(wire)
fmt.Printf("client: %s <%s>, %d orders\n", dto.Name, dto.Email, len(dto.Orders))
for _, o := range dto.Orders {
fmt.Printf(" order %d: %s\n", o.Number, cents(o.Total))
}
dto.Email = "ann@example.org"
fmt.Println("server after a change on the client:", ann.email)
// Client sends the DTO back; the assembler updates the domain object.
UpdateFrom(FromWire(dto.ToWire()), ann)
fmt.Println("server after the update call:", ann.email)
}
password hash on the wire: no
client: Ann <ann@example.com>, 2 orders
order 7: 145.00
order 8: 40.00
server after a change on the client: ann@example.com
server after the update call: ann@example.org
- Verdict: idiom. The DTOs are structs with exported fields and
jsonstruct tags, andencoding/jsonserializes them. The domain structs have only fields that are not exported, sojson.Marshalof aCustomerwould give{}, and the password hash could not leak. ToDTOandUpdateFromare the assembler.UpdateFromcopies only the name and the email.
fn cents(n: i64) -> String {
format!("{}.{:02}", n / 100, n % 100)
}
// Domain objects on the server. Some data must never leave the server.
#[allow(dead_code)]
struct Line {
item: &'static str,
qty: i64,
price: i64,
cost_price: i64,
}
struct Order {
number: u32,
lines: Vec<Line>,
}
impl Order {
fn total(&self) -> i64 {
self.lines.iter().map(|l| l.qty * l.price).sum()
}
}
struct Customer {
name: String,
email: String,
password_hash: String,
orders: Vec<Order>,
}
// Data transfer objects: only data, shaped for one remote call, and able to serialize themselves.
struct OrderSummaryDto {
number: u32,
total: i64,
}
struct CustomerDto {
name: String,
email: String,
orders: Vec<OrderSummaryDto>,
}
impl CustomerDto {
// One value on each line: the name, the email, and then one line for each order.
fn to_wire(&self) -> String {
let mut s = format!("{}\n{}\n", self.name, self.email);
for o in &self.orders {
s.push_str(&format!("{} {}\n", o.number, o.total));
}
s
}
fn from_wire(text: &str) -> CustomerDto {
let mut lines = text.lines();
let name = lines.next().unwrap_or("").to_string();
let email = lines.next().unwrap_or("").to_string();
let orders = lines
.filter_map(|l| {
let (n, t) = l.split_once(' ')?;
Some(OrderSummaryDto { number: n.parse().ok()?, total: t.parse().ok()? })
})
.collect();
CustomerDto { name, email, orders }
}
}
// The assembler moves the data between the domain objects and the DTOs, on the server.
fn to_dto(c: &Customer) -> CustomerDto {
CustomerDto {
name: c.name.clone(),
email: c.email.clone(),
orders: c.orders.iter().map(|o| OrderSummaryDto { number: o.number, total: o.total() }).collect(),
}
}
fn update_from(dto: CustomerDto, c: &mut Customer) {
c.name = dto.name; // the orders are read only
c.email = dto.email;
}
fn main() {
let mut ann = Customer {
name: "Ann".to_string(),
email: "ann@example.com".to_string(),
password_hash: "pbkdf2:9f86d081".to_string(),
orders: vec![
Order {
number: 7,
lines: vec![
Line { item: "lamp", qty: 2, price: 2500, cost_price: 1400 },
Line { item: "desk", qty: 1, price: 7500, cost_price: 5100 },
Line { item: "pen", qty: 4, price: 500, cost_price: 90 },
],
},
Order { number: 8, lines: vec![Line { item: "chair", qty: 1, price: 4000, cost_price: 2600 }] },
],
};
// Server: one call returns all the data that the screen needs.
let wire = to_dto(&ann).to_wire();
println!("password hash on the wire: {}", if wire.contains(&ann.password_hash) { "yes" } else { "no" });
// Client: it reads the DTO, and changes its own copy.
let mut dto = CustomerDto::from_wire(&wire);
println!("client: {} <{}>, {} orders", dto.name, dto.email, dto.orders.len());
for o in &dto.orders {
println!(" order {}: {}", o.number, cents(o.total));
}
dto.email = "ann@example.org".to_string();
println!("server after a change on the client: {}", ann.email);
// Client sends the DTO back; the assembler updates the domain object.
update_from(CustomerDto::from_wire(&dto.to_wire()), &mut ann);
println!("server after the update call: {}", ann.email);
}
password hash on the wire: no
client: Ann <ann@example.com>, 2 orders
order 7: 145.00
order 8: 40.00
server after a change on the client: ann@example.com
server after the update call: ann@example.org
- Verdict: idiom. The DTOs are plain structs. In a real application, the
serdecrate would derive the serialization, but it is a library and not part of the standard library, soto_wirewrites one value on each line, and a name or an email that has a line break would break this simple format. update_fromtakes the DTO by value, so it moves the strings into the domain object and does not copy them.
Consequences
Benefits.
- One call for all the data. The Core J2EE patterns: "A single method call is used to send and retrieve the Transfer Object." After that, "all calls to the Transfer Object instance are local calls instead of remote method invocations."3
- Control of what leaves the server. The DTO has only the fields that the client must see. Microsoft gives as a reason to use DTOs: "Hide particular properties that clients are not supposed to view."4
- A stable contract. The DTO is the shape of the data on the wire. The domain objects can change while the DTO stays the same, and the assembler takes up the difference.
- One place for the serialization. The DTOs "keep this logic out of the rest of the code and also provide a clear point to change serialization should you wish."1
Liabilities.
Without a DTO, the domain object leaks. In the following program, the server serializes the customer object itself. All its fields go over the wire, the password hash too.
This code runs but gives a wrong answer on purpose.
import json
class Customer:
def __init__(self, name, email, password_hash):
self.name, self.email, self.password_hash = name, email, password_hash
ann = Customer("Ann", "ann@example.com", "pbkdf2:9f86d081")
# Wrong: the server sends the domain object itself, with all its fields.
wire = json.dumps(vars(ann))
received = json.loads(wire)
print("fields sent:", ", ".join(received))
print("password hash on the wire:", received["password_hash"])
fields sent: name, email, password_hash
password hash on the wire: pbkdf2:9f86d081
Put only the fields that the client needs into a DTO, and let an assembler fill it.
The mapping is work. Each DTO needs an assembler, and the code that copies the data grows with each screen. Randy Stafford, quoted by Fowler, says of this cost: "It's significant, and it's painful - perhaps second only to the cost and pain of object-relational mapping".5 Libraries can do the copy: Microsoft names "a library like AutoMapper that handles the conversion automatically."4
Two models to keep in step. A change to the data that a screen shows needs a change to the DTO, the assembler and the client.
When not to use it
Inside one process. "DTOs are called Data Transfer Objects because their whole purpose is to shift data in expensive remote calls."5 In a local context, Fowler writes, "they are actually harmful both because a coarse-grained API is more difficult to use and because you have to do all the work moving data from your domain or data source layer into the DTOs."5
Only to guard the clients of a local service layer. Some people use DTOs in a local Service layer API so that its clients do not depend on the Domain model. Fowler: "While that may be handy, I don't think it's worth the cost of all of that data mapping."5
Variants and related patterns
Presentation DTO. Fowler names one local use that is worth the cost: "One case where it is useful to use something like a DTO is when you have a significant mismatch between the model in your presentation layer and the underlying domain model."5
Messages between isolated parts. When an application has areas with one thread each, the areas can "use a message queue with DTOs as messages to transfer the information."5
Transfer Object. The Core J2EE patterns give the same pattern for Enterprise JavaBeans: "Use a Transfer Object to encapsulate the business data."3 Fowler notes that the Java community first used the term value object for this pattern, which caused confusion with a Value object, and later changed to the name Transfer Object.1
Related patterns. A Remote facade takes and returns DTOs. The assembler is a kind of mapper, like the Data Mapper between objects and tables. The DTO is a unit of Serialization.
Known uses
- Enterprise JavaBeans applications, where an enterprise bean "can construct the Transfer Object, populate it with its attribute values, and pass it by value to the client."3
- ASP.NET Web API, where the tutorial adds
BookDtoandBookDetailDtoclasses and changes the controller to return them, because "A DTO is an object that defines how the data will be sent over the network."4 - The request and response types of HTTP and RPC APIs in general, which are DTOs for the calls of a Remote facade.
References
- Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Data Transfer Object, pattern summary and the note of 2013-08-11
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 15, Distribution Patterns, Data Transfer Object
- Core J2EE Patterns, Transfer Object, Problem and Solution
- Microsoft, ASP.NET Web API 2 with Entity Framework, Create Data Transfer Objects (DTOs), the whole page
- Martin Fowler, Local DTO, 21 October 2004, the whole post
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag HNJB56 Edit this page History Report an error Markdown