Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with two-way mapping?

Tags:

c#

automapper

I've been using AutoMapper for a few months now with success but now I've hit a bit of a stumbling block. What I need (or think I need) is for 2 way mapping. This is for when I load an item from the database to play on the screen (domain object -> view model) and when the users make changes to said item and map it back to my domain object (view model -> domain object).

I understand that I could simply create a mapping in my profile to handle the two-way mapping but I was reading here that two-way mapping are unnecessary. Many people indicate that doing so is a response to not fixing the bigger issue (what ever that may be).

I'm just wondering why is this a code smell?

like image 924
Nosila Avatar asked Jan 19 '12 14:01

Nosila


1 Answers

When I was a junior dev, I worked on a large project which basically did what you are describing. We didn't use automapper, but we created viewmodels which encapsulated domain objects which basically meant that you got your changes from the view directly to the domain objects. Just persist your changes and presto they are where you want them to be (in the database). That application should have released four years ago, but they are still struggling.

Why is this a smell? Well you are losing track of any intent as to why you are changing stuff. And intent is something that is really really important as your application grows and becomes more complex. Its difficult to enforce new rules into you domain because it is difficult to see exactly which operations are valid to perform on your domain. If you make your domain model auto-mappable, its also very anemic.

As Jimmy points out, you want to model your domain after the requirements of your domain, not to the requirements of automapper. If automapper were to work directly on your model you would have to make adjustments like making property-setters public, although that might not be a good idea from a domain-modeling perspective.

I think the bigger issue is that a domain model which can be automapped directly from viewmodels does not convey intent, nor encapsulation in a satisfying manner. If you are creating a small app, then active record/dataset style architecture might not be a bad thing, but if the solution is larged scaled or complex you have bigger issues than mapping from viewmodel to domain.

In the current application I am working on, we use automapper to map from domain to dto's and from dto's to viewmodels. When something is to be persisted we translate the operation on the viewmodels into explicit commands which are executed against the domain. I've would never ever recommend a three layered architecture in any large scale app (thin or thick client).

like image 74
Marius Avatar answered Oct 28 '22 20:10

Marius