The Plain Picture#
In a restaurant the chef cooks, the waiter serves, the cashier bills. If the chef also served tables and ran the till, a busy night at the till would burn the food.
The Real Name#
Single Responsibility Principle (SRP): a class should have only one reason to change. "Reason to change" usually means one group of people who ask for changes: the maths rules come from teachers, formatting from the product team, storage from the platform team.
Under the Hood#
QuizManager from Part 0 has at least five reasons to change: scoring maths, formatting, storage, notifications, billing. Split it:
record QuizResult(String student, int points, int maxPoints) {}
class ScoreCalculator {
// reason to change: scoring rules
double percentage(QuizResult r) {
return (100.0 * r.points()) / r.maxPoints();
}
}
interface ReportFormatter {
String format(QuizResult r, double pct);
} // reason to change: output format
class TextFormatter implements ReportFormatter {
public String format(QuizResult r, double pct) {
return String.format("%s: %.1f%%", r.student(), pct);
}
}
class CsvFormatter implements ReportFormatter {
public String format(QuizResult r, double pct) {
return r.student() + "," + String.format("%.1f", pct);
}
}
// ... plus a ResultRepository (storage) and a Notifier (Ch 6), each its own classQuizResult r = new QuizResult("Priya", 180, 200);
double pct = new ScoreCalculator().percentage(r);
for (ReportFormatter f : List.of(new TextFormatter(), new CsvFormatter()))
System.out.println(f.format(r, pct));
// Priya: 90.0%
// Priya,90.0The CSV export request now means adding CsvFormatter — no existing class was touched.
How to spot an SRP violation:
the class name contains "Manager", "Helper", "Utils" or "And";
you can't describe what it does in one sentence without "and";
it imports libraries from very different areas (database + email + PDF);
unrelated changes keep landing in the same file.
Gotchas
SRP is not "one method per class". A
ScoreCalculatorwith five scoring methods is fine — they share one reason to change.Over-splitting creates a maze of tiny classes that's hard to follow. Split along real, different reasons to change (Ch 8).
Check yourself
3 questionsState SRP in one sentence.
Show answerHide answer
A class should have only one reason to change.
List the responsibilities in Part 0's QuizManager.
Show answerHide answer
Scoring maths, formatting, storage, notification, billing.
Name two warning signs of an SRP violation.
Show answerHide answer
Any two: a "Manager/Utils/And" name; can't describe it without "and"; imports from unrelated areas; unrelated changes keep hitting it.