0

Lets say we have DTO class with 15 properties. Usually DTOs like these are mapped from other objects. But sometimes some DTOs may use values from multiple objects. In these cases, should we “Map” or “Create” an object?

In our project we currently have these scenarios handled by constructors, in some places by static Create methods (a bit inconsistent). We’re doing some refactoring which includes using new MappingService which handles mappings between types. This service supports mapping from multiple source objects. So the question is: should we move constructors creating object from multiple other objects to MappingService or consider them as construction rather than mapping (in which case we may implement some pattern/solution for construction of objects/separately)?

I guess this is more of a terminology question. How do you draw a line of what is mapping and what is construction?

1 Answer 1

0

Typically constructors should only accept dependencies necessary for creating the new object. What you are proposing is to move mapping logic into the constructors. At first glance, this seems like a sensible solution, except the objects you pass in are not dependencies of the current class. This is a simple solution at first, but drawbacks begin to appear over time if data mapping logic becomes more complex. This often results in cascading changes to constructors when mapping a hierarchy of objects.

I've implemented data mapping in constructors as well as "service" objects (although I called them "factories" even if polymorphism wasn't utilized). The DTOs I have the most experience with are view models for the ASP.NET MVC framework. My experience has been mixed.

I liked constructor mapping, because it was fast to write. If the DTOs remained simple, constructor mapping was also easy to maintain and understand. While constructor mapping technically violates the purpose of a constructor, the simplicity of the solution was too hard to resist. When DTOs became complicated to map, I created a "service" or "factory" object to do that mapping. This allowed me to move non-trivial mapping logic out of the constructors when logic became complex. Even then, some of the DTOs still used constructor mapping.

Ultimately I ended up with a mix of utility classes for mapping and logic in constructors. Which technique I used depended on the complexity of what I mapped. It was very subjective. At some point the mapping logic becomes complex enough to move into its own class. Just be aware of the downsides of each technique.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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