使用行动字典,而不是switch语句 [英] Using Action dictionaries instead of switch statements

查看:136
本文介绍了使用行动字典,而不是switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是回顾我的一些老code的(有一些空闲时间),我注意到一个相当长的switch语句。由于获得新的知识,因为我已经在下面的表格重构吧:

I'm just reviewing some of my old code (have some spare time), and I noticed a rather lengthy switch statement. Due to gaining new knowledge, I have since refactored it in the following form:

private Dictionary<string, Action> createView
    {
        get
        {
            return new Dictionary<string, Action>()
            {
                {"Standard", CreateStudySummaryView},
                {"By Group", CreateStudySummaryByGroupView},
                {"By Group/Time", CreateViewGroupByHour}
            };
        }
    }

你会考虑这种好的做法,还是这只是被superflous和不必要的案件?我希望确保新的技术,我学习,不只是为了它的缘故被聪明,他们实际上增加造福于code。

Would you consider this good practise, or is this simply a case of being superflous and unneccessary? I'm keen to ensure new techniques that I learn, are not being clever just for the sake of it, and that they actually add benefit to the code.

感谢。

推荐答案

龙switch语句是一个典型的不良气味,并始终重构的目标。

Long switch statements are a classic bad smell, and are always a target for refactoring.

标准的步骤来这里演出是替换条件与多态性 。这是在Martin Fowler的书重构(1999年出版的11年前)中列出的步骤之一。

The "standard" step to perform here is Replace Conditional with Polymorphism. This was one of the steps listed in Martin Fowler's book Refactoring (published 11 years ago in 1999).

现在,它是如此容易治疗状物体功能(如用行动),这可能是一样好一个解决方案。

Now that it's so easy to treat functions like objects (eg with Action) this might be just as good a solution.

不,我不认为你是聪明的它的缘故。如果我想在将来添加另一种选择,我可以很容易地看到需要做什么。

And no, I don't think you're being clever for the sake of it. If I wanted to add another option in the future, I can easily see what needs to be done.

这篇关于使用行动字典,而不是switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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