Single Responsibility Principle in Design Pattern

The Single Responsibility Principle is the first of the five SOLID principles for object-oriented design that makes the classes we write easy to understand and maintain. For this principle, when defining a class, we define it only with a single task, related to a single aspect, of solving a single problem. And then, when working with that class, we simply add or edit the code to solve that task or problem.

For example, to manage students, if we resolve all of the student-related operations in a class as follows:

it is very complicated to maintain this application. Student, as the name suggests, should only manage Student properties such as name, age. The management of new information, updating information about the number of times to attend courses should be managed by another class, when needed we can use this class to get information. The timetable is usually the timetable of a class, so defining the timetable code in the Student class is also unreasonable.

We can rewrite the above class with 3 classes as follows:

As you can see, with the above rewrite, the Student class simply manages the personal information related to the Student.

To manage class attendance, I introduce class AttendanceManagment so that we can add new and get class attendance information of a student based on studentId. Introducing this class makes it easy to extend the application later, for example, now I need to see the attendance status of all students, I can use this class to do that.

Class ClassManagement is used to manage all information related to the class such as timetables, teachers, extracurricular activities, … You can easily add new without ambiguity or confusion, messy.

Always thinking about the Single Responsibility Principle is a good habit to help you write better code!

Leave a Reply

Your email address will not be published. Required fields are marked *