Clean Architecture - Where does mapping of DTO to business model should happen?

Nameless picture Nameless · Jun 18, 2018 · Viewed 10.3k times · Source

I have a DTO that's managed by a Repository and in the end I want to map this DTO to a different type of object that's used by the Presentation layer.

Should the mapping happen in the Repository or in the domain layer? ( Use case/ Interactor)

Answer

Pace picture Pace · Jun 27, 2018

I think the term DTO is a little too vague to answer this question. It really depends on what the purpose of the transformation is.

For example, let's assume we have some kind of system that has a Book object in its entities (in the domain layer). The book object returned by the repositories may have a field named pendingDelete because we delete books in a background task in batches. This field is needed by the domain layer but not externally and so, in the use case layer, we transform the book object into another object (maybe by casting to an interface or maybe creating a whole new object) that does not have this field. This meets the definition of a DTO in my brain and this mapping would happen in the domain layer.

Alternatively, lets now consider that we need to transform that object into a different object that has been decorated with various annotations/metadata that instruct how to serialize the object into XML or JSON. This also meets the definition of a DTO but this mapping would happen outside of the domain layer.

In the first example, we are using the DTO to control the interface to our inner layers and so we do that mapping in the inner layers. In the second example we are using the DTO to control the interface to our outer layers and so we do that mapping in the outer layers.