Search code examples
c#-4.0c#-3.0domain-driven-designextension-methodsdto

DTO mapper using C# Extension Methods


Is it a good idea to define the members of a DTO mapper (which is most of the times a static class) as extension methods?

Then instead of writting:

Affiliate bo = Mapper.FromDataTransferObject(dto);

We may write:

Affiliate bo = dto.FromDataTransferObject();

FromDataTransferObject is an extension method defined below:

public static Affiliate FromDataTransferObject(this AffiliateDto dto) {

if (dto == null) {
    return null;
}

var bo = new Affiliate() {
    Id           = dto.Id,
    AccountAlias = dto.AccountAlias,
    Balance      = dto.Balance
    // ...
};

return bo; 

}


Solution

  • Naming issues aside, there's nothing fundamentally wrong with it, and it allows for good SOC in terms of where the code lies while still providing a good API.

    That said, you should consider renaming your function. Typically, functions are named from the perspective of the target (in this case, your DTO), not from the perspective of the result. In your case, I would name it ToAffiliate or ToBusinessObject (if you want to have a consistent name across your DTO's) instead of FromDataTransferObject.