Today I was having a conversation with one of the developers on my team (btw, this guy is going to be a rock star) and I made that statement to him that I thought we had some noisy code. The context around this conversation was with our usage of AutoMapper (which I love so DO NOT take this as a slight against the tool) and how by default using AutoMapper exposes too much noise and I do not like it.
When I made this statement to him he was not 100% sure what I meant, so in place of having a one-off conversation with him I thought I would try to explain my thoughts to the world (hey, that is the point of blogging after all, right).
When using AutoMapper to map objects from one type to another in your code you need to implement something like below:
var someMappedDto = Mapper.Map<SomeModel, SomeDto>(someModelInstance);
If you look at the code there is a bit of noise here in my opinion. So what do I mean by noise? I consider anything in my code that gets in my way or does not provide me direct feedback as noise.
In the line above I consider the following noise:
- Mapper.Map – I do not like this because having Mapper.Map sprinkled all over my code base just means that my code has too much knowledge of the actually mapping library we use, this is noise. Hey, it was for this basic concept that the Common Service Locator was created to help prevent
- Having to provide both the source type AND the destination type – The source type should be able to be derived from the source object instance (in cases where you do not want to use the mapper for some child type of the source type). I concede that you do need to provide the destination type other wise we would have no clue what you want in the end
- Having to provide the source type instance in the constructor.
In order to reduce the noise, and make for cleaner code I would like to see something like
var someMappedDto = someModelInstance.Map<SomeDto>();
In my humble opinion the code above is cleaner and more concise. The code above has less noise to distract me from my coding efforts. In particular the code above addresses my 3 issues in regards to the noise
- Now I am abstracting my mapping library of choice (AutoMapper) away into an extension method some place, thus giving me a clean abstraction layer
- I do not need to provide the source data type as it can be inferred from the instance itself (yes, only in the case where the actual type being used is the type I want)
- No need to provide the type to be mapped from (well not directly)
To me noise free code is clean, concise and easy to read.
Till next time,
02-25-2010 7:16 PM