February 27, 2010 .NET, AutoMapper, Clean Code
February 27, 2010 .NET, AutoMapper, Clean Code
If you haven’t read my previous article on AutoMapper, please read it first.
I just read an article on the noisiness which could be introduced with AutoMapper.
My Mapping Code is Noisy
Accordingly to that article my code:
CustomerViewItem customerViewItem = Mapper.Map<Customer, CustomerViewItem>(customer);
is noisy code.
Why?
In few words that is because I’m coupled to the specific mapping engine and because I’m providing too much unneeded information on about how to map my objects.
Take a look on that line once again: we used Customer , but we already have customer, so we can know its type.
What to do to make it not so noisy?
In that article, that I pointed, there is proposition to change my code to:
CustomerViewItem customerViewItem = customer.Map<CustomerViewItem>();
So, I’ve got interested to apply it to my previous AutoMapper article’s code. As you already caught Map is just extension method for my Customer class.
Here it is:
Everything becomes simple if you are trying it.
Markdown | Result |
---|---|
*text* | text |
**text** | text |
***text*** | text |
`code` | code |
~~~ more code ~~~~ |
more code |
[Link](https://www.example.com) | Link |
* Listitem |
|
> Quote | Quote |
Andriy,
That code works well, but only in context of a customer.
Try this — http://pastie.org/845137
Follow the link for a nice code paste
Yes, this works just fine:
public static TDest Map(this object customer)
{
return (TDest)Mapper.Map(customer, customer.GetType(), typeof(TDest));
}
But in this case I'll get method Map for any object like here:
object anyObject = new object();
anyObject.Map();
I don't see instance of any object to be brilliant to have Map method.