你会如何​​重构这个有条件的使用多态? [英] How would you refactor this conditional to use polymorphism?

查看:170
本文介绍了你会如何​​重构这个有条件的使用多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看完谷歌干净code视频在YouTube上(见链接,第一篇文章)有关从code删除如果语句,并使用多态代替。

I just finished watching the Google clean code video on YouTube (see link, first article) about removing if statements from your code and using polymorphism instead.

在观看录像后,我看了一下,我是写在观看视频前,一些code,发现一些地方,我可以用这个方法,在同一种逻辑被实现很多次的主要场所。所以一个例子:

After watching the video I had a look at some code that I was writing before watching the video and noticed some places where I could use this method, mainly places where the same kind of logic was implemented many times. So a example:

我有一些code这样的。

I have some code like this.

public int Number
{
    get
    {
        string returnValue;
        if (this.internalTableNumber == null)
             returnValue = this.RunTableInfoCommand(internalTableName,
                                                    TableInfoEnum.TAB_INFO_NUM);
        else
             returnValue = this.RunTableInfoCommand(internalTableNumber.Value,
                                                    TableInfoEnum.TAB_INFO_NUM);
        return Convert.ToInt32(returnValue);
    }
}

什么RunTableInfoCommand所做的是不是真的很重要,但更主要的是,我有很多属性完全相同的如果 statments改变是TableInfoEnum的嘛。

What RunTableInfoCommand does isn't really important,but the main thing is that I have many properties with exactly the same if statments the only thing that changes is the TableInfoEnum.

我在想,如果有人可以帮助我重构这使得它仍做同样的事情,但没有任何如果语句?

I was wondering if someone could help me refactor this so that it still does the same thing but without any if statements?

推荐答案

看到其中的一些(技术上是正确的)反应变量,只是摆脱了如果语句不应该是你唯一的目标后,就在谨慎注意这里,我们的目标应该可以使你的code扩展性,可维护性和简单的,如果这意味着摆脱if语句,伟大的,但它不应该在自己的一个目标。

Just a cautionary note here after seeing some of these (technically correct) reponses, just getting rid of an If statement should not be your sole aim, the aim should be to make your code extensible, maintainable and simple, if that means getting rid of an if statement, great, but it shouldn't be an aim in an of itself.

在code样,你给了,并没有更多地了解你的应用程序,并假设你不会延长太多过去的测试空值,我觉得是如果(或者甚至是三元)是更维护的解决方案是完全坦诚。

In the code sample you have given, and without knowing more about your app, and assuming you are not going to extend much past testing for a null value, I think an If (or perhaps even a ternary) is the more maintainable solution to be perfectly frank.

这篇关于你会如何​​重构这个有条件的使用多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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