使用隐式/显式转换运算符是否违反单一职责模式以支持 DRY? [英] Does using Implicit / Explicit conversion operators violate Single Responsibility Pattern in favor of DRY?

查看:29
本文介绍了使用隐式/显式转换运算符是否违反单一职责模式以支持 DRY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在这两个类之间进行转换,并希望保持 DRY 但不违反单一职责模式...

I need to convert between these two classes, and want to maintain DRY but not violate the Single Responsibility Pattern...

public class Person
{
    public string Name {get;set;}
    public int ID {get;set;}
}

public class PersonEntity : TableServiceEntity
{
    public string Name {get;set;}
    public int ID {get;set;}

    // Code to set PartitionKey
    // Code to set RowKey
}

更多信息

我的 ASP.NET MVC 应用程序中有一些模型对象.由于我使用的是 Azure 存储,因此需要经常在 ViewModel 对象和 AzureTableEntity 之间进行转换.

I have some Model objects in my ASP.NET MVC application. Since I'm working with Azure storage I see the need to convert to and from the ViewModel object and the AzureTableEntity quite often.

我通常在我的控制器中完成这种从左到右的变量赋值.

I've normally done this left-hand-right-hand assignment of variables in my controller.

第一季度

除了隐式/显式转换,这段代码应该在控制器(x)还是datacontext(y)中?

Aside from implicit/explicit conversion, should this code be in the controller(x) or the datacontext(y)?

Person <--> View <--> Controller.ConverPersonHere(x?) <--> StorageContext.ConvertPersonHere(y?) <--> AzurePersonTableEntity

第二季度

我应该进行隐式转换还是显式转换?

Should I do an implicit or explicit conversion?

第三季度

哪个对象应该包含转换代码?

What object should contain the conversion code?

更新

我也在此项目中实施 WCF,但不确定这将如何影响您的推荐.另请参阅 这个问题.

I'm also implementing WCF in this project and am not sure how this will affect your recommendation . Please also see this question.

推荐答案

Q1:控制器.

问题 2:手动转换或借助 AutoMapper 等映射工具进行转换.

Q2: Convert manually or with the help of a mapping tool such as AutoMapper.

Q3:我会将这个代码放在转换器或映射器类中,如下所示.请注意,IConverter 在所有转换器之间共享,而 IPersonConverter 只是存在以便您的控制器和服务定位器可以使用它.

Q3: I would put the code for this in a converter or mapper class like the following. Note that IConverter is shared among all converters, and IPersonConverter just exists so your controllers and service locators can use it.

public interface IConverter<TModel, TViewModel>
{
    TViewModel MapToView(TModel source);
}

public interface IPersonConverter : IConverter<PersonEntity, Person>
{
}

public class PersonConverter : IPersonConverter
{
    #region IPersonConverter

    public Person MapToView(PersonEntity source)
    {
        return new Person
                   {
                       ID = source.ID,
                       Name = source.Name
                   };

        //or use an AutoMapper implementation
    }

    #endregion
}

这篇关于使用隐式/显式转换运算符是否违反单一职责模式以支持 DRY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆