【问题标题】:Do one or both of these methods follow the Single Responsibility Principle?这些方法中的一种或两种是否遵循单一职责原则?
【发布时间】:2014-08-13 13:46:39
【问题描述】:

我有一个School 班级,其中包含学生名单,Student 班级有如下奖项和成绩列表:

public class School
{
    List<Student> Students {get;set;}
}

public class Student
{
    List<Grade> Grades {get;set;}
    List<Award> Awards{get;set;}
}

我有一种复制方法,可以将Student's Awards and/or Grades 从一个School 复制到另一个。您可以选择只处理Student to a new school or the Student and his/her Awards and/or Grades。以下哪一项跟在Single Responsibility Principle 后面,为什么跟在它后面,如果都跟在后面,为什么不跟在后面?第一个示例复制学生并获取布尔值以确定是否应复制 Grades and Awards

CopyStudent(Student student, bool copyGrades, bool copyAwards)
{
   //Copy Student

   if(copyGrades)
   {
      //Copy Grades
   }

   if(copyAwards)
   {
      //Copy Awards
   }
}

以上内容包括CopyStudent 类中GradesAwards 的复制。是遵循SRP 还是更好地将应对等级和奖励分成不同的方法,例如:

CopyGrades(List<Grade> grades)
{
    //Copy grades
}

CopyAwards(List<Award> awards)
{
    //Copy awards
}

所以上面的方法会被CopyStudent方法调用。

【问题讨论】:

  • 复制成绩和复制姓名没有区别,它们都是复制学生的一部分,因此在某种程度上都遵守 SRP。如果它们需要多于几行以保持清晰的概览,那么将它们提取到单独的方法中会更好。
  • @JeroenVannevel - 好的,我最初采用第二种方式,因为它使代码更清晰,对我来说更具可读性,您似乎同意这一点,对吗?
  • 是的,没错。可读性是代码最重要的方面之一,其重要性怎么强调都不为过。

标签: oop solid-principles single-responsibility-principle


【解决方案1】:

正如 Jeroen 在 cmets 中已经提到的那样,分离方法总是一个好主意,所以乍一看,第二种方法似乎更好。

您可能会争辩说,在某些情况下您只是想“复制一个学生”——不多不少。在这些情况下 - to avoid code duplication - 你需要像 CopyStudent() 这样的东西,就像你的第一种方法一样。另一方面,标志copyGradescopyAwards 有点smelly。仍然这两种方法不一定相互矛盾。这个怎么样:

CopyGrades(List<Grade> grades)
{
    //Copy grades
}

CopyAwards(List<Award> awards)
{
    //Copy awards
}

CopyStudent(Student student)
{
   CopyGrades(student.grades)
   CopyAwards(student.awards)
}

总的来说,我发现 SRP 很难掌握。在某些情况下,很难确定是否满足。一些提示和启发:

  • 描述函数/方法/类/模块做什么。这是用它的名字来表示的吗?您是否需要多个句子(由“and”、“or”、“but”连接)?如果第二个答案是“是”,请重新考虑您的设计。
  • A responsibility is a reason to change(罗伯特·C·马丁)
  • Another view 来自“Uncle Bob”,这次强调的是人和设计(当然还有代码)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多