agoda-com / agoda-com/standards-c-sharp

Add From method pattern recommendation for mapping

未关闭
#9 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看
主要语言
没有语言数据
星标
22
派生
4
PR 合并指标
30 天内没有已合并 PR

描述

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

```csharp
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

```csharp
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.

贡献指南

打开贡献指南

评估

这个 Issue 还没有评估数据。

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。