One reason to change
After this: Split a sales report that does three jobs into three classes, and say which class each request edits.
On this page · 6 sections · 3 checks
A shop keeps a list of its sales and wants a short report: the total, written as one line of text, and saved under a name. One class can do all three jobs, and the program works. Then three different people ask for three different changes. This lesson shows why that hurts, and the first of five rules that help.
Five rules of thumb
The last four tutorials gave you tools: private fields, parts held in fields, and interfaces. This tutorial gives five rules for using them well. Programmers call the set , after the first letter of each rule.
Each rule is a rule of thumb: advice that is right most of the time, not a law. Each lesson takes one rule, shows a small program before and after it, and ends with when not to bother.
One class, three jobs
class SalesReport: def __init__(self, amounts): self.amounts = amounts self.files = {}
def total(self): return sum(self.amounts)
def format(self): return f"Total sales: {self.total()} from {len(self.amounts)} orders"
def save(self, name): self.files[name] = self.format() return "saved " + name
report = SalesReport([120, 80, 300])print(report.format())print(report.save("report.txt"))Total sales: 500 from 3 orders saved report.txt
import java.util.HashMap;import java.util.List;import java.util.Map;
class SalesReport { private List<Integer> amounts; private Map<String, String> files = new HashMap<>();
SalesReport(List<Integer> amounts) { this.amounts = amounts; }
int total() { int sum = 0; for (int a : amounts) { sum += a; } return sum; }
String format() { return "Total sales: " + total() + " from " + amounts.size() + " orders"; }
String save(String name) { files.put(name, format()); return "saved " + name; }}
public class Main { public static void main(String[] args) { SalesReport report = new SalesReport(List.of(120, 80, 300)); System.out.println(report.format()); System.out.println(report.save("report.txt")); }}Total sales: 500 from 3 orders saved report.txt
SalesReport has three methods:
totaladds up the amounts: 120 + 80 + 300 = 500.formatwrites the lineTotal sales: 500 from 3 orders.savestores that line under a name and returnssaved report.txt. It stores into a dictMap, not a real file, so the program runs anywhere.
Now the requests come in:
- The accountant says refunds must be taken off the total. That changes
total. - The manager wants different words in the line. That changes
format. - The IT team moves reports from files to a database. That changes
save.
Three people, three reasons, one class. Each change means opening the same class, and a mistake made for one request can break the other two jobs. If two programmers work on two of the requests at once, they both edit the same class.
One reason to change
The rule: a class should have one reason to change. In other words, it does one job, and only one kind of request ever makes you edit it. Its name is the , the S of SOLID.
Split the class along its three reasons to change:
- ReportFormatter uses Sales
class Sales: def __init__(self, amounts): self.amounts = amounts
def total(self): return sum(self.amounts)
def count(self): return len(self.amounts)
class ReportFormatter: def format(self, sales): return f"Total sales: {sales.total()} from {sales.count()} orders"
class ReportSaver: def __init__(self): self.files = {}
def save(self, name, text): self.files[name] = text return "saved " + name
sales = Sales([120, 80, 300])text = ReportFormatter().format(sales)print(text)print(ReportSaver().save("report.txt", text))Total sales: 500 from 3 orders saved report.txt
import java.util.HashMap;import java.util.List;import java.util.Map;
class Sales { private List<Integer> amounts;
Sales(List<Integer> amounts) { this.amounts = amounts; }
int total() { int sum = 0; for (int a : amounts) { sum += a; } return sum; }
int count() { return amounts.size(); }}
class ReportFormatter { String format(Sales sales) { return "Total sales: " + sales.total() + " from " + sales.count() + " orders"; }}
class ReportSaver { private Map<String, String> files = new HashMap<>();
String save(String name, String text) { files.put(name, text); return "saved " + name; }}
public class Main { public static void main(String[] args) { Sales sales = new Sales(List.of(120, 80, 300)); String text = new ReportFormatter().format(sales); System.out.println(text); System.out.println(new ReportSaver().save("report.txt", text)); }}Total sales: 500 from 3 orders saved report.txt
Walk through it:
Salesholds the amounts and answers two questions: the total and the count. Refunds would change only this class.ReportFormatterasks aSalesobject for those two numbers and writes the line. A new wording changes only this class.ReportSaverstores any text under a name. It does not read the text. A database would change only this class.
The output is the same two lines as before. The program does the same work; what changed is where each job lives.
Run it
Java does not run here. Read the Java version in the code block above, or paste it into a Java tool on your computer.
Change the words in ReportFormatter and run it again. Sales and ReportSaver stay as they are.
Check yourself
In the design after the split, the manager wants the line to read “Sales: 500 rupees, 3 orders”. Which class do you edit?
The same three classes, with May's sales. What does this print?
class Sales: def __init__(self, amounts): self.amounts = amounts
def total(self): return sum(self.amounts)
def count(self): return len(self.amounts)
class ReportFormatter: def format(self, sales): return f"Total sales: {sales.total()} from {sales.count()} orders"
class ReportSaver: def __init__(self): self.files = {}
def save(self, name, text): self.files[name] = text return "saved " + name
sales = Sales([200, 50, 50, 100])saver = ReportSaver()text = ReportFormatter().format(sales)print(saver.save("may.txt", text))print(text)import java.util.HashMap;import java.util.List;import java.util.Map;
class Sales { private List<Integer> amounts;
Sales(List<Integer> amounts) { this.amounts = amounts; }
int total() { int sum = 0; for (int a : amounts) { sum += a; } return sum; }
int count() { return amounts.size(); }}
class ReportFormatter { String format(Sales sales) { return "Total sales: " + sales.total() + " from " + sales.count() + " orders"; }}
class ReportSaver { private Map<String, String> files = new HashMap<>();
String save(String name, String text) { files.put(name, text); return "saved " + name; }}
public class Main { public static void main(String[] args) { Sales sales = new Sales(List.of(200, 50, 50, 100)); ReportSaver saver = new ReportSaver(); String text = new ReportFormatter().format(sales); System.out.println(saver.save("may.txt", text)); System.out.println(text); }}A cinema's Ticket class works out the price, writes the ticket as text, and emails it to the customer. What does the single responsibility principle say about it?
When not to bother
- Say what SOLID is: five rules of thumb for classes, named by their first letters, to be followed with judgement.
- Count a class's reasons to change by asking who would request each change: the sales report had three.
- Split a class along its reasons to change: Sales adds up, ReportFormatter writes the line, ReportSaver stores it.
- Say which class a request edits after the split, and when a small script does not need splitting.