2

Hi I am very new to using DTOs, and I am starting to understand it slowly, but there are still some missing puzzles for me.

I understand the use of DTOs in the way of decoupling the persistence data model from the data model (representation) offered to the consumers. Also, that the aim beneath DTOs is to gather in a single response as much info as necessary for clients to save calls to the server.

What I am having a hard time with is understanding what is the best situation to use DTO's compared to use of an entity?

To make it more clear when do I use an entity and when a DTO?

For example when I am trying to save new user in database should I use a DTO or an entity?

For retrieving data from a database and communicating with a frontend, will I make use of DTOs?

4

3 Answers 3

8

Also, that the aim beneath DTO's is to gather in a single response as much info as necessary for clients to save calls to the server.

That's not the aim of a DTO. It's a side effect that you can more easily achieve when already using DTOs. But using DTOs and bundling data are two different design decisions that should each be made for their own reasons.

What I am having a hard time with is understanding what is the best situation to use DTO's compared to use of entity?

In essence, an "entity" is just shorthand for "the DTO between the data store and our persistence logic". It's a DTO just like any other DTO, meant to be used for data transfer between two specific points.

Depending on the two layers that are passing data to one another, these DTOs tend to get a contextual nickname:

        ┌───────────┐    ┌──────┐    ┌───┐
DB  ─┬─►│Persistence│◄─┬─┤Domain├─┬─►│Web├─┬─►  END USER
     │  └───────────┘  │ └──────┘ │  └───┘ │
     │                 │          │        │
 "Entity"           "Domain  "Business   "Model"
                     Object"    Object"

On a technical level, all of these intermediary objects are DTOs. We just give them different names so it's easier to talk about them and understand what someone means when they say "entity", without forcing them to have to say "the DTO between the database and the persistence layer".

This also inherently explains why/when to use an "entity" specifically. Entities are used as a means of communication between the database and the persistence logic. If you're passing data between different layers, then it shouldn't be handled by an entity.

Very important note Your specific architecture will change what layers you have and what the DTOs are commonly called. I used a DDD example which relies on an ORM here, but you might be using a different architecture altogether, which would mean you need to adapt the names accordingly.

For example, if you don't use an ORM and write SQL queries manually, then you might refer to the Persistence->Domain DTO as the "entity", since you don't actually have a DTO class between DB->Persistence.

For example when I am trying to save new user in database should I use DTO or entity?

It's a staged process.

  1. The web controller receives a model, maps it to a business object, and passes it to the domain.
  2. The domain receives the business object, translates it into a domain object, and performs the operation. At some point, this means passing (some of) the data to the persistence layer.
  3. The persistence layer receives the domain object, maps it to an entity, and sends that entity on to the database.
  4. (Commonly hidden step: your ORM maps your entity to a SQL command and sends that to the database)

For retrieving data from database and communicating with frontend in that case only use of DTO's?

This is the same staged process, albeit in the opposite order.

Hoewever, there may be contextual differences. For example, if your retrieved data doesn't retrieve full entities (i.e. table rows), but instead is more of a "report" of very specific data columns (maybe even some calculated columns), then this object returned from the DB is generally not even called an "entity".

"Entity" generally refers to the class that represents a full table row.

2
  • That is IMHO a good summary - maybe we should add a link from the "entity" and "dto" tag descriptions to this answer. Though in ER modeling, the term entity has AFAIK a more specific meaning.
    – Doc Brown
    Apr 12, 2021 at 11:25
  • @DocBrown: Yeah the more specific contextual meanings made it hard to write this answer without strongly contradicting one of those. I guess that's always the challenge with colloquialisms like these, informal usage is often very predominant but also the least rigorously defined.
    – Flater
    Apr 12, 2021 at 11:30
0

I tend to think of them like this:

An entity is part of a larger graph of related objects and fully represents that particular object. E.g., OrderLineItem could be an entity containing information specific to the order line item (both as it exists in the class and the database table).

A DTO is more geared toward reading non-entity information. For example, you might have a query that returns some reportable data regarding aggregate information across various line items, regardless of the order. The data structure returned by the query would be the DTO.

I like to take some hints from the Command/Query Responsibility Segregation concept (CQRS). The general idea being that issuing commands tends to utilize a graph of dependent pieces of information (e.g., place an Order and write these OrderLineItems, etc. Where a query often results in a dedicated data structure specific to what's being displayed: e.g., run an order status summary for X client. This query doesn't necessarily fit well in the full entity graph (it could, but is often horribly inefficient).

With that in mind, entities would be more related to your full graph/commands (e.g., transactional data operations), where DTOs would be more geared toward specific data structures designed with query performance in mind (being that ORMs are notoriously horrible at complex data calculations through an entity graph).

Technically, there may not be any difference between an entity and DTO (as Flater points out), but conceptually and in practice, this division has worked well for me.

0

Both objects are implemented similarly. In Java, for example, both objects are encoded as "bean"s which consist of fields, accessors and mutators with very little, if any, behavior. In code we prefer to work with objects instead of database rows or Json.

DTOs are used to transfer data, hence the name. They encode the public representation of data. This is typically the data you see in a service call specification. DTOs must be easy to serialize and deserialize to transfer data over a network. They also allow us to separate our internal representation of data from the representation of the data we expose to our clients.

An entity is a back-end object that represents the data stored in a database. The entity mirrors the data representation. In this case we might not want to separate our data representation from our users because our users are the authors of the code.

2
  • Why the downvote? This answer is correct.
    – John Douma
    Apr 12, 2021 at 20:54
  • Gave this an upvote - this line could be better: "An entity is a back-end object that represents the data stored in a database" It inherently 'couples' things unnecessarily and will lead engineers into toxic thought patterns, specifically the database row 'is the business object' - the data in the database is better thought of as stuff that could power/hydrate. Decoupling the 'database row' from the 'business object' a bit more frees the minds of developers to implement better decisions organically. Feb 25, 2023 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.