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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.huongdankotlin.designpattern.srp class Student { var name: String = "" var age: Int = 0 var timesInClass = HashMap<String, Int>(); fun addTimesInClass(subject: String, times: Int) { timesInClass[subject] = times } fun getTimesInClass(subject: String): Int? { return timesInClass.get(subject) } fun getTimeTable() { // NOP } } |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.huongdankotlin.designpattern.srp class Student { var name: String = "" var age: Int = 0 } class AttendanceManagement { var timesInClass = HashMap<String, HashMap<String, Int>>(); fun addTimesInClass(studentId: String, subject: String, times: Int) { timesInClass.get(studentId)?.put(subject, times) } fun getTimesInClass(studentId: String, subject: String): Int? { return timesInClass.get(studentId)?.get(subject) } } class ClassManagement { fun getTimeTableByClassId() { // NOP } fun getTimeTableByStudentId() { // NOP } } |
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!