【问题标题】:Refactoring switch statement for Data to different types of data将 Data 的 switch 语句重构为不同类型的数据
【发布时间】:2010-11-28 23:32:00
【问题描述】:

我的任务是重构一个写得不好的 switch 语句(它会使圈复杂度飙升)。简而言之,有一个类可以解析文件以获取各种值。

class foo
{
    //a sampling of the fields.  Each have their appropriate property
    private string _name;
    private short _location;
    private int _lineNumber;
    private List<string> _siblings;

    internal foo (StreamReader reader)
    {
        _siblings = new List<string>()
        while (!reader.EndofFile)
        {
            switch (reader.ReadLine())
            {
               case "Name":
                  _name = reader.ReadLine();
                  break;
               case "Location":
                  _location = short.Parse(reader.ReadLine());
                  break;
               case "Line Number":
                  _lineNumber = int.Parse(reader.ReadLine());
                  break;
               case "Brother":
               case "Sister":
                  _siblings.Add(reader.ReadLine());
                  break;
               //etc
            }
        }
    }
    //Other methods and such
}

我已经阅读了该主题,虽然似乎有很多帮助,但似乎都指向策略设计模式,(我相信)这会过度解决我的问题。在我的项目中,有多个这样的类,其中一些有超过 25 个案例陈述(所以对那些能够提出接口或抽象类的想法的人表示敬意)

我曾考虑过使用John Sonmez 所描述的Dictionary&lt;String, TValue&gt;,但是TValue 会是什么?

任何帮助将不胜感激。

【问题讨论】:

    标签: c# dictionary refactoring switch-statement


    【解决方案1】:

    首先,reader.ReadLine() 真的不是这里switch 语句的一部分,所以我建议您只需两两阅读行并传递给另一个类来处理。 (第一行似乎定义了它是什么,第二行具有价值)。

    您的处理程序将包含该操作。如果您不想使用 Strategy - 这很简单,也许您应该使用 - 将 Dictionary 的值设置为 delegates 每个实施策略:

     Dictionary<string, Action<string>> dic = new Dictionary<string, Action<string>>();
     dic.Add("Father", ((x)=> // somthing);
     dic.Add("Brother", ((x)=> // somthing);
     dic.Add("Sister", ((x)=> // somthing);
    

    【讨论】:

    • 我想你可能误解了我的意思。如果策略是最好的方法,那么我一定会使用它!
    • 这个实现无论如何都是策略,但工厂是作为字典实现的。
    • 来自 wiki:“编程语言的基本要求是能够在数据结构中存储对某些代码的引用并检索它。”这就是我在这里所做的。
    • 很有意思的图案,我喜欢!
    • 好的,非常感谢!在我将此标记为答案之前,是否会有任何可以想象的性能影响?
    【解决方案2】:

    两个选项。

    如果存在从该行读取的数据与属性名称匹配的约定,您可以按照约定通过反射填充该属性。或者,您可以在属性上使用与您将从文件中读取的预期值相对应的属性。

    希望能帮助或至少为您指明正确的方向:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 2016-06-05
      • 2022-10-18
      相关资源
      最近更新 更多