standards-c-sharp
standards-c-sharp copied to clipboard
Add From method pattern recommendation for mapping
This technique is mensioned in a few of the articles but never officially documented.
Not sure if this is standards or style though. Maybe it belongs in a different section all together.
What we discussed was we looking at mapping as a concept, having mapping classes or services to map class A to B doesn't lend itself to be very discoverable, and we see times when mapper classes are written multiple times because of this.
Also mappers in general should be pure, so base on our other recommendation about using static for pure methods, we started using a static method called From, in target classes for mapping.
For example
public class A
{
}
public class B
{
public static From(A a)
{
// mapping logic here
}
}
What this would look like getting used is something like this
B.From(new A())
- Having the mapping logic in the model itself allows for good discoverability, when you look at the model you see what other model it depends on
- if the methods is pure is should be static
- the code reads like a sentence to describe what's being done "B from A", making it fluent
- Can be used with multiple classes in the From method
Where it is not good is when your mapping is not pure, you don't want to be passing services into the from method.
It's included implicitly under Service design; see the examples section for details.
I'm not sure if this is still the preferred way. Using extension methods solely would force implementers to use pure methods. In addition, when using extension methods, you don't have any mapping clutter in the models. This might harm discoverability, but only for those not familiar with this structure.
Furthermore, having mapping logic bound to a specific domain close together, let's say in a single extention class with several mappings, is far more beneficial. Better overview and visibility in regards to relationships, easy to reuse/review mapping test cases.