Single Responsibility: one reason to change
A Student knows its own marks. A ReportPrinter only knows how to print. Each has one job.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Single Responsibility means a class has one job and one reason to change. Student owns a student’s own data and can work out its own average. ReportPrinter’s only job is turning that into text on screen. If we ever print to a file instead of the console, only ReportPrinter changes — Student is untouched.
Code
var asha = new Student { Name = "Asha", Marks = new List<int> { 80, 90, 70 } };
new ReportPrinter().Print(asha);
class Student {
public string Name;
public List<int> Marks;
public double Average() =>
Marks.Average();
}
class ReportPrinter {
public void Print(Student student) {
Console.WriteLine($"{student.Name}: {student.Average()}");
}
}class Student {
String name;
List<Integer> marks;
double average() {
return marks.stream().mapToInt(Integer::intValue).average().orElse(0); }
}
class ReportPrinter {
void print(Student student) {
System.out.println(student.name + ": " + student.average());
}
}
public class Main {
public static void main(String[] args) {
Student asha = new Student(); asha.name = "Asha"; asha.marks = List.of(80, 90, 70);
new ReportPrinter().print(asha);
}
}struct Student {
string name;
vector<int> marks;
double average() const {
double sum = 0; for (int m : marks) sum += m;
return sum / marks.size();
}
};
class ReportPrinter {
public:
void print(const Student& student) {
cout << student.name << ": " << student.average() << "\n";
}
};
int main() {
Student asha{"Asha", {80, 90, 70}};
ReportPrinter().print(asha);
}class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def average(self):
return sum(self.marks) / len(self.marks)
class ReportPrinter:
def print(self, student):
print(f"{student.name}: {student.average()}")
asha = Student("Asha", [80, 90, 70])
ReportPrinter().print(asha)Tips
- Ask: "which kind of change would make this class change?" Student changes when what we track about a student changes. ReportPrinter changes when how we display it changes. Those are different reasons, so they are different classes.
- This is not about keeping classes tiny. It is about not mixing two unrelated reasons to change into one class.
In the .NET library
If Student also had a Print() method that formatted console output, a change to the print format would force you to touch the same class that stores marks — two unrelated reasons to change, tangled together.