where should I do the conversion: Domain object<->DTO?
Asked Answered
C

3

6

In Domain Layer or Data access layer?

Calvities answered 13/3, 2010 at 12:17 Comment(0)
H
7

The primary motivation for DTOs is to present an interface tailored to another layer (typically, the presentation layer). For example, a data entry screen may need some bits of data from a User object in addition to some bits from an Order, etc. In that case, the Domain to DTO should happen at the layer which the presentation layer invokes, i.e., typically a "service" layer.

There are libraries like Dozer out there which automate the grunt work of converting between domain models and DTOs.

The key take away is DTOs are meant to abstract the data (not business logic) out of richer domain model objects - hence, DTOs should be converted back to domain objects as early as possible (at service layer) so the rest of your application layers may work with richer domain objects (data and business logic)

Hindenburg answered 13/3, 2010 at 20:8 Comment(0)
A
2

I'm not much of a fan of DTOs, but I say don't do it in the data layer. The data layer deals with model objects and their persistence. Why couple it with other layers by bringing DTOs into it? I'd map them somewhere else, probably between the service and ui tiers, just at the point where they cross the boundary between where they're created and where they're used.

Agiotage answered 13/3, 2010 at 12:35 Comment(0)
B
1

Putting this in MVC context, if you have both controllers and services layer you should put it in the controller. This would make a DTO closer to the view layer and allow the service layer to play with domain objects only, avoiding possible confusion with other models.

The DTO itself is actually the MVC model (Explained here: https://stackoverflow.com/a/1058186).

Below is a recommended tutorial that mashes the controller, service layer and DTO concepts together (In java using Spring framework, but the concept is clear for other platforms as well): https://www.baeldung.com/entity-to-and-from-dto-for-a-java-spring-application

Barreto answered 23/3, 2019 at 0:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.