Published on

[SOLID] Single responsibility Principle

Authors
  • avatar
    Name
    Khánh
    Twitter

When we use:

Statement

A module should be responsible to one, and only one, actor.
Mỗi class nên giữ một trách nhiệm duy nhất và chỉ một.

Each class should have single responsibility and a reason to change.

Example:

In this case, the Student class has too many methods to handle. The code may still work fine, but if you expand this Student class, it will become bloated. Not to mention, if you add other classes like Person, Teacher, etc., this will have to be repeated in many places and will be difficult to maintain.

public class Student {
  public string Name { get; set;}
  public int Age { get; set;}
  
  // Format method
  public string GetStudentInfoText() {
    return "Name: " + Name + ". Age: " + Age;
  }
  public string GetStudentInfoHTML() {
    return "<span>" + Name + " " + Age + "</span>";
  }
  public string GetStudentInfoJson() {
    return Json.Serialize(this);
  }
  // Save to the database
  public void SaveToDatabase() {
    dbContext.Save(this);
  }
  public void SaveToFile() {
    Files.Save(this, "fileName.txt");
  }
}

To address this issue by apply SRP. We can split out smaller classes (Formatter, Store) to specialize the functionality for each class. This makes it easier to extend and maintain the code.

// Student only has the information of the students
public class Student {
  public string Name { get; set;}
  public int Age { get; set;}
}

// Formatter student information
public class Formatter {
  public string FormatStudentText(Student std) {
    return "Name: " + std.Name + ". Age: " + std.Age;
  }
  public string FormatStudentHtml(Student std) {
    return "<span>" + std.Name + " " + std.Age + "</span>";
  }
  public string FormatStudentJson(Student std) {
    return Json.Serialize(std);
  }
}

// This class purposes to store the data
public class Store {
  public void SaveToDatabase(Student std) {
    dbContext.Save(std);
  }
  public void SaveToFile(Student std) {
    Files.Save(std, "fileName.txt");
  }
}

Conclusion

In essence, this is just a guideline, not an absolute, unchangeable rule. There are still many areas that need to be dissected of this principle

References