A class should have just one reason to change.
Every class in our code should be responsible for just a single part of the application. By following this principle we reduce the complexity of our code.
If a class is responsible of multiple parts of our app, it will have to be changed frequently. Therefore, changing one part of the class increases the risk of breaking other parts of itself. The solution is to divide it into multiple classes, each one with one responsibility.
In the following bad example we can see how the Student
class has two responsibilities: managing the student data and the course data.
class Student {
id: number;
name: string;
courseId: number;
courseName: string;
courseSubjects: string[];
// constructor
getCourseSubjects(): string {
return this.courseSubjects.join(", ");
}
}
Following the Single Responsibility Principle we can improve this by moving the course data to its own class.
class Student {
id: number;
name: string;
course: Course;
// constructor
}
class Course {
id: number;
name: string;
subjects: string[];
// constructor
getCourseSubjects(): string {
return this.subjects.join(", ");
}
}
Top comments (4)
I didn't mean that your objection is extreme, I'll quote a paragraph from the book "Dive into Design Patterns" by Alexander Sheets which better explains what I meant:
You are right that juniors could misunderstand this principle with my example. Thank you for your suggestion, I will update the post to avoid confusion.
I would instead keep it and add a brief explanation of why even that code break SRP. As a newbie it was helpfull to read through comment but not everyone may do it.
Thank you for your comment Luke. I will go through the content that you shared in the comment. Your point of view sounds very interesting. I rarely use classes in my daily work but it's the first time I see someone against them.
Yes, it's totally posible not to use classes. In this series of posts that I'm going to be doing my goal is to explain SOLID principles with examples in TypeScript for people who could be interested.
Thanks for the comment Tamas. You're totally right, in the example we are just applying SRP to the Student class. We could continue applying SRP to the Course class.
It's important to have in mind that principles should give you guidance. They should not be applied to the extreme without evaluating first if it makes sense.