需要有关理解 SRP 的建议,提供方法和类的示例

问题描述 投票:0回答:0
  1. 这是一种从项目文件夹中提供 .csv 文件列表的方法
    public static List<string> GetListOfTables()
     {
         var tables = new List<string>();
    
         do
         {
             tables = Directory
                     .GetFiles(".", "*.csv")
                     .Select(file => Path.GetFileName(file))
                     .ToList();
    
             if (tables.Count == 0)
             {
                 Output.Invoke("\nNo .csv files are found, " +
                 "please put a table csv file in the program folder " +
                 "and press <Enter> to continue");
    
                 while (Console.ReadKey(true).Key != ConsoleKey.Enter) { }
             }
         }
         while (tables.Count == 0);
    
         return tables;
     }

在这里,除了获取文件名外,我还添加了对空文件夹的内置验证。 这是内联 SRP 还是方法重载,最好创建一个单独的验证方法,然后将其链接到主方法中?我相信既然以后没有理由改变验证逻辑,我可以保留它,因为它不会破坏 SRP(?)。

  1. 有一个主要目的是将 .csv 文件解析为对象列表的类。
static class CsvParser
        {
            public static List<string> GetListOfTables() { }

            // The user is making a choice from the list of tables 
            // via a method outside of this class. 
   
            public static List<List<object>> GetTable(string tableName) { }
        }

既然这个类的主要目的是实际解析,那么收集文件列表的方法不会破坏 SRP 吗?同时,将已经很小的实用程序类分成两个类在这里感觉有点矫枉过正,而且获取不太可能更改的文件列表的逻辑(?)。

虽然我是一个完全的初学者,但我希望早日对此有一个清晰的认识,不要从一开始就养成坏习惯。

c# single-responsibility-principle
© www.soinside.com 2019 - 2024. All rights reserved.