394

In MVC are the model classes DTO? If not, what are the differences and do we need both?

A-Tech
  • 806
  • 6
  • 22
Yaron Naveh
  • 23,560
  • 32
  • 103
  • 158

12 Answers12

404

A Data Transfer Object is an object that is used to encapsulate data, and send it from one subsystem of an application to another.

DTOs are most commonly used by the Services layer in an N-Tier application to transfer data between itself and the UI layer. The main benefit here is that it reduces the amount of data that needs to be sent across the wire in distributed applications. They also make great models in the MVC pattern.

Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than four or five parameters.

When using the DTO pattern, you would also make use of DTO assemblers. The assemblers are used to create DTOs from Domain Objects, and vice versa.

The conversion from Domain Object to DTO and back again can be a costly process. If you're not creating a distributed application, you probably won't see any great benefits from the pattern, as Martin Fowler explains here.

2240
  • 1,547
  • 2
  • 12
  • 30
Benny Hallett
  • 7,327
  • 4
  • 26
  • 26
  • 9
    "DTO make great models in the MVC pattern" - but shouldn't a model contain all data of the object and DTO be optimized with part of the data? If I have model A and I need to pass it to two subsystems will there be A_DTO_1 and A_DTO_2 with the relevant fields of each? "DTOs can be to encapsulate parameters for method calls" --> So every class that wraps parameters is DTO even if this is not distributed system? Are't models in MVC the domain object? – Yaron Naveh Jun 30 '09 at 21:10
  • 2
    In answer to your first question, I don't think were talking about the same thing. The model in MVC doesn't necessarily need to be a class from your Domain Model. Having said that, it well could be. Using the DTO strips out all of the unnecessary stuff. Just depends on the architecture you're going for. I'm not sure exactly how to answer your second question. Whether its across the wire or not, it's still an object that encapsualtes a bunch of data to be transferred between (sub)systems, so I'd argue it's a DTO. – Benny Hallett Jul 06 '09 at 07:49
  • 33
    "Another use for DTOs can be to encapsulate parameters for method calls. This can be useful if a method takes more than 4 or 5 parameters." This is actually an anti-pattern called a Poltergeist or Gypsy Wagon class. If your method needs 4 arguments then give it 4, don't create a class just to move an object into method or a class. – Wix Dec 10 '10 at 15:11
  • 5
    @Wix, good point. I'd argue however that this is ok if it's semantically correct (say if you pass a settings class with properties rather than the properties themselves as values). What you shouldn't do is throw in all the arguments for the sake of passing a single object, since they may very well be unrelated and cause nightmares untangling later on. – Aram Kocharyan Sep 21 '12 at 03:03
  • 4
    DTOs should not be used to encapsulate parameters for methods calls (which would make them LocalDTOs), they were introduced in the context of remote interfaces: http://martinfowler.com/bliki/LocalDTO.html – Rui Oct 01 '13 at 15:29
  • 3
    @Wix a [poltergeist](https://sourcemaking.com/antipatterns/poltergeists) is nearly the opposite of a parameter object (or DTO). A poltergeist is stateless while a parameter object or DTO is nothing but state. – jaco0646 Mar 01 '20 at 22:41
  • and DTO will be helpful in DDD. with flutter – Amit Singh Mar 31 '21 at 03:03
47

The definition for DTO can be found on Martin Fowler's site. DTOs are used to transfer parameters to methods and as return types. A lot of people use those in the UI, but others inflate domain objects from them.

blu
  • 12,905
  • 20
  • 70
  • 106
43

A DTO is a dumb object - it just holds properties and has getters and setters, but no other logic of any significance (other than maybe a compare() or equals() implementation).

Typically model classes in MVC (assuming .net MVC here) are DTOs, or collections/aggregates of DTOs

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177
  • 5
    What you are describing is a LocalDTO: http://martinfowler.com/bliki/LocalDTO.html – Rui Oct 01 '13 at 15:30
  • 4
    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. In this case it makes sense to make presentation specific facade/gateway that maps from the domain model and presents an interface that's convenient for the presentation. – 王奕然 Aug 14 '15 at 03:21
26

In general Value Objects should be Immutable. Like Integer or String objects in Java. We can use them for transferring data between software layers. If the software layers or services running in different remote nodes like in a microservices environment or in a legacy Java Enterprise App. We must make almost exact copies of two classes. This is the where we met DTOs.

|-----------|                                                   |--------------|
| SERVICE 1 |--> Credentials DTO >--------> Credentials DTO >-- | AUTH SERVICE |
|-----------|                                                   |--------------|

In legacy Java Enterprise Systems DTOs can have various EJB stuff in it.

I do not know this is a best practice or not but I personally use Value Objects in my Spring MVC/Boot Projects like this:

        |------------|         |------------------|                             |------------|
-> Form |            | -> Form |                  | -> Entity                   |            |
        | Controller |         | Service / Facade |                             | Repository |
<- View |            | <- View |                  | <- Entity / Projection View |            |
        |------------|         |------------------|                             |------------|

Controller layer doesn't know what are the entities are. It communicates with Form and View Value Objects. Form Objects has JSR 303 Validation annotations (for instance @NotNull) and View Value Objects have Jackson Annotations for custom serialization. (for instance @JsonIgnore)

Service layer communicates with repository layer via using Entity Objects. Entity objects have JPA/Hibernate/Spring Data annotations on it. Every layer communicates with only the lower layer. The inter-layer communication is prohibited because of circular/cyclic dependency.

User Service ----> XX CANNOT CALL XX ----> Order Service

Some ORM Frameworks have the ability of projection via using additional interfaces or classes. So repositories can return View objects directly. There for you do not need an additional transformation.

For instance this is our User entity:

@Entity
public final class User {
    private String id;
    private String firstname;
    private String lastname;
    private String phone;
    private String fax;
    private String address;
    // Accessors ...
}

But you should return a Paginated list of users that just include id, firstname, lastname. Then you can create a View Value Object for ORM projection.

public final class UserListItemView {
    private String id;
    private String firstname;
    private String lastname;
    // Accessors ...
}

You can easily get the paginated result from repository layer. Thanks to spring you can also use just interfaces for projections.

List<UserListItemView> find(Pageable pageable);

Don't worry for other conversion operations BeanUtils.copy method works just fine.

Fırat Küçük
  • 5,613
  • 2
  • 50
  • 53
20
  1. To me the best answer to the question what is a DTO is that DTO's are simple objects that should not contain any business logic or methods implementation that would require testing.
  2. Normally your model (using the MVC pattern) are intelligent models, and they can contain a lot of/some methods that do some different operations for that model specifically (not business logic, this should be at the controllers). However, when you transfer data (eg. calling a REST (GET/POST/whatever) endpoint from somewhere, or consuming a webservice using SOA, etc...) you do not want to transmit the big sized object with code that is not necessary for the endpoint, will consume data, and slow down the transfer.
SSD
  • 1,373
  • 2
  • 13
  • 20
Thiago Burgos
  • 947
  • 2
  • 13
  • 17
11

All credits goes to Rick-Andreson

Production apps typically limit the data that's input and returned using a subset of the model. There are multiple reasons behind this and security is a major one. The subset of a model is usually referred to as a Data Transfer Object (DTO), input model, or view model.

A DTO may be used to P.H.O.F.F:

  • Prevent over-posting.
  • Hide properties that clients are not supposed to view.
  • Omit some properties in order to reduce payload size.
  • Flatten object graphs that contain nested objects.
  • Flattened object graphs can be more convenient for clients.

Practical implementation of a DTO approach, by Rick-Andreson on Microsoft Web APIs best tutorials and practices using C# and ASP .Net Core 5:

Ali.Ghodrat
  • 3,348
  • 3
  • 31
  • 31
10

With MVC data transfer objects are often used to map domain models to simpler objects that will ultimately get displayed by the view.

From Wikipedia:

Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.

Liam
  • 27,717
  • 28
  • 128
  • 190
Dan
  • 17,375
  • 3
  • 36
  • 39
  • 4
    A value object is not a [DTO](https://en.wikipedia.org/wiki/Data_transfer_object). – coderpc Jan 22 '19 at 21:40
  • According to [Martin Fowler](https://martinfowler.com/eaaCatalog/dataTransferObject.html), "Many people in the Sun community use the term "Value Object" for this pattern." – therealrodk May 16 '22 at 19:32
7

The principle behind Data Transfer Object is to create new Data Objects that only include the necessary properties you need for a specific data transaction.

Benefits include:

Make data transfer more secure Reduce transfer size if you remove all unnecessary data.

Read More: https://www.codenerd.co.za/what-is-data-transfer-objects

MrG
  • 81
  • 1
  • 2
4

Some programmers use DTO to distinguish their final object data that is going to be passed through an API. So, it is basically a payload object to an endpoint. Like, you could name your contact form values object that you pass to the server as contactFormDto or contactFromPayload, then you or any other programmer know what you have in that object is final shape of the data, that is going to travel through network.

2

I would explain DTO to my kid as

My son, Data Transfer Object (aka DTO) **is used to encapsulate data we send from one endpoint to another. Use DTO to define interfaces for input and output for endpoints in your system

In this context think of a system as a collection of endpoints. And endpoints can be anything between (mobile app, web app, backend API) that talk with each other.

sultanmyrza
  • 4,551
  • 1
  • 30
  • 24
1

Data transfer object (DTO) describes “an object that carries data between processes” (Wikipedia) or an “object that is used to encapsulate data, and send it from one subsystem of an application to another” (Stack Overflow answer).

mostafa kazemi
  • 514
  • 6
  • 7
1

DefN

A DTO is a hardcoded data model. It only solves the problem of modeling a data record handled by a hardcoded production process, where all fields are known at compile-time and therefore accessed via strongly typed properties.

In contrast, a dynamic model or "property bag" solves the problem of modeling a data record when the production process is created at runtime.

The Cvar

A DTO can be modeled with fields or properties, but someone invented a very useful data container called the Cvar. It is a reference to a value. When a DTO is modeled with what I call reference properties, modules can be configured to share heap memory and thereby collaboratively work on it. This completely eliminates parameter passing and O2O communication from your code. In other words, DTOs having reference properties allow code to achieve zero coupling.

    class Cvar { ... }

    class Cvar<T> : Cvar
    {
        public T Value { get; set; }
    }

    class MyDTO
    {
        public Cvar<int> X { get; set; }
        public Cvar<int> Y { get; set; }
        public Cvar<string> mutableString { get; set; } // >;)
    }

Source: http://www.powersemantics.com/

Dynamic DTOs are a necessary component for dynamic software. To instantiate a dynamic process, one compiler step is to bind each machine in the script to the reference properties the script defines. A dynamic DTO is built by adding the Cvars to a collection.

    // a dynamic DTO
    class CvarRegistry : Dictionary<string, Cvar> { }

Contentions

Note: because Wix labeled the use of DTOs for organizing parameters as an "anti-pattern", I will give an authoritative opinion.

    return View(model);  // MVC disagrees

My collaborative architecture replaces design patterns. Refer to my web articles.

Parameters provide immediate control of a stack frame machine. If you use continuous control and therefore do not need immediate control, your modules do not need parameters. My architecture has none. In-process configuration of machines (methods) adds complexity but also value (performance) when the parameters are value types. However, reference type parameters make the consumer cause cache misses to get the values off the heap anyway -- therefore, just configure the consumer with reference properties. Fact from mechanical engineering: reliance on parameters is a kind of preoptimization, because processing (making components) itself is waste. Refer to my W article for more information. http://www.powersemantics.com/w.html.

Fowler and company might realize the benefits of DTOs outside of distributed architecture if they had ever known any other architecture. Programmers only know distributed systems. Integrated collaborative systems (aka production aka manufacturing) are something I had to claim as my own architecture, because I am the first to write code this way.

Some consider the DTO an anemic domain model, meaning it lacks functionality, but this assumes an object must own the data it interacts with. This conceptual model then forces you to deliver the data between objects, which is the model for distributed processing. However on a manufacturing line, each step can access the end product and change it without owning or controlling it. That's the difference between distributed and integrated processing. Manufacturing separates the product from operations and logistics.

There's nothing inherently wrong with modeling processing as a bunch of useless office workers who e-mail work to one another without keeping an e-mail trail, except for all the extra work and headache it creates in handling logistics and return problems. A properly modeled distributed process attaches a document (active routing) to the product describing what operations it came from and will go to. The active routing is a copy of the process source routing, which is written before the process begins. In the event of a defect or other emergency change, the active routing is modified to include the operation steps it will be sent to. This then accounts for all the labor which went into production.

RBJ
  • 128
  • 6