Single Responsibility: One Reason to Change

When one class works out the grades, lays out the report card and emails it, three different people's changes all land in the same class and can break each other; the first SOLID principle, single responsibility, says to give each class one reason to change, and this lesson opens with what SOLID is and where it came from.

Apprentice · OOP · Updated

By

After this lesson you can

  • Explain what SOLID is and where it came from: five pieces of design advice, not laws
  • Find a class's reasons to change, and split it so each class has one

Key takeaways

  • SOLID is five pieces of advice for code that's easy to change: Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion.
  • SOLID is advice, not law. Each principle has times when bending it is the better choice.
  • A responsibility is a reason to change: a person or a group whose requests change the code.
  • Single responsibility: give each class one reason to change, so one person's change can't break another's work.

Northside High's report-card app is small and it works: it turns each student's scores into letter grades, lays them out on one line, and emails the line to the student's family. This month three people asked for changes. The district wants a new grading scale. The front office wants a new layout. The school's IT team is moving to a new email system. All three changes land in the same class, and last term a layout change accidentally broke the grades.

This chapter is about five pieces of advice that help with exactly this kind of trouble, and this lesson is the first of them.

Five pieces of advice with a famous name

Around 2000, the programmer and writer Robert C. Martin gathered five principles of object-oriented design that teams had found again and again. A few years later, Michael Feathers noticed that their first letters spelled a word, and the name stuck: SOLID.

A card titled SOLID with five rows, one per letter: S, Single Responsibility, one reason to change; O, Open/Closed, add, don't edit; L, Liskov Substitution, no surprises from a stand-in; I, Interface Segregation, small promises; D, Dependency Inversion, depend on the promise

Letter Principle In plain words
S Single Responsibility one reason to change
O Open/Closed add, don't edit
L Liskov Substitution no surprises from a stand-in
I Interface Segregation small promises
D Dependency Inversion depend on the promise

You'll hear these names in code reviews and job interviews ("this class breaks single responsibility"). They're useful words. But they're advice, not law: each one makes code easier to change in the situations it was written for, and each lesson in this chapter ends with when to bend it.

The symptom: three people, one class

Here is the report card as it is today. Scores of 90 and up are an A, 80 a B, 70 a C, 60 a D, and anything lower an F. The school's email system isn't connected here, so the sending is shown as a printed line:

new ReportCard("Maya", new List<(string Course, int Score)> { ("Math", 93), ("Science", 85), ("English", 71) }).Email();
new ReportCard("Sam", new List<(string Course, int Score)> { ("Math", 78), ("Science", 64), ("English", 88) }).Email();

// Works out the grades, lays out the report card, and emails it.
class ReportCard
{
    private string name;
    private List<(string Course, int Score)> scores;

    public ReportCard(string name, List<(string Course, int Score)> scores)
    {
        this.name = name;
        this.scores = scores;
    }

    public string Letter(int score)
    {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }

    public string Text() => name + ": " + string.Join(", ", scores.Select(s => s.Course + " " + Letter(s.Score)));

    public void Email() => Console.WriteLine("Email to " + name + "'s family: " + Text());
}
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
record Score(String course, int points) {}

// Works out the grades, lays out the report card, and emails it.
class ReportCard {
    private String name;
    private List<Score> scores;

    ReportCard(String name, List<Score> scores) {
        this.name = name;
        this.scores = scores;
    }

    String letter(int score) {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }

    String text() {
        List<String> grades = new ArrayList<>();
        for (Score score : scores) { grades.add(score.course() + " " + letter(score.points())); }
        return name + ": " + String.join(", ", grades);
    }

    void email() {
        IO.println("Email to " + name + "'s family: " + text());
    }
}

void main() {
    new ReportCard("Maya", List.of(new Score("Math", 93), new Score("Science", 85), new Score("English", 71))).email();
    new ReportCard("Sam", List.of(new Score("Math", 78), new Score("Science", 64), new Score("English", 88))).email();
}
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
class ReportCard:
    """Works out the grades, lays out the report card, and emails it."""

    def __init__(self, name, scores):
        self.name = name
        self.scores = scores

    def letter(self, score):
        if score >= 90:
            return "A"
        if score >= 80:
            return "B"
        if score >= 70:
            return "C"
        if score >= 60:
            return "D"
        return "F"

    def text(self):
        grades = [course + " " + self.letter(score) for course, score in self.scores]
        return self.name + ": " + ", ".join(grades)

    def email(self):
        print("Email to " + self.name + "'s family: " + self.text())


ReportCard("Maya", [("Math", 93), ("Science", 85), ("English", 71)]).email()
ReportCard("Sam", [("Math", 78), ("Science", 64), ("English", 88)]).email()
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
// Works out the grades, lays out the report card, and emails it.
class ReportCard {
  constructor(name, scores) {
    this.name = name;
    this.scores = scores;
  }

  letter(score) {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }

  text() {
    return this.name + ": " + this.scores.map(([course, score]) => course + " " + this.letter(score)).join(", ");
  }

  email() {
    console.log("Email to " + this.name + "'s family: " + this.text());
  }
}

new ReportCard("Maya", [["Math", 93], ["Science", 85], ["English", 71]]).email();
new ReportCard("Sam", [["Math", 78], ["Science", 64], ["English", 88]]).email();
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
// Works out the grades, lays out the report card, and emails it.
class ReportCard {
  name: string;
  scores: [string, number][];

  constructor(name: string, scores: [string, number][]) {
    this.name = name;
    this.scores = scores;
  }

  letter(score: number): string {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }

  text(): string {
    return this.name + ": " + this.scores.map(([course, score]) => course + " " + this.letter(score)).join(", ");
  }

  email(): void {
    console.log("Email to " + this.name + "'s family: " + this.text());
  }
}

new ReportCard("Maya", [["Math", 93], ["Science", 85], ["English", 71]]).email();
new ReportCard("Sam", [["Math", 78], ["Science", 64], ["English", 88]]).email();
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B

The class is short and easy to read. The trouble is who it answers to:

  • The district decides the grading scale, so Letter changes when they do.

  • The front office decides the layout, so Text changes when they do.

  • IT decides how messages are sent, so Email changes when they do.

  • The symptom: one class changes for three different people's reasons, and a change for one of them (the layout) can break another's work (the grades), because they share the class's fields and its tests.

  • The cause: three responsibilities packed into one class. That's the third smell from Code Smells: one class with many jobs.

What would you try?

Be careful. Every change gets an extra-careful review. That works until the busy week when it doesn't, and it doesn't stop the three changes from colliding when they're made at the same time.

Split it into three methods with clear names. It already has three methods. They still live in one class, share its fields, and ship together: the email team can't change sending without the grade code being rebuilt and retested too.

Copy the class for each team. Then there are three copies of the grading scale, and the next scale change has to find them all.

What would help is if each person's change landed in a class that belongs to that person's job, and only that job.

The idea: one reason to change

The everyday version is a pocket multi-tool with a dozen tools folded into one handle. It's handy until the blade gets dull: the sharpener can't reach it past the scissors, the screwdriver and the can opener. One tool's upkeep is blocked by all the others.

A pocket multi-tool with a dozen tools folded out around one dull blade, and a knife sharpener that can't reach the blade past the other tools

The first principle, single responsibility, says: give each class one reason to change. A responsibility, here, isn't "a thing the class does"; it's a person or group whose requests change the code. The report card has three, so it becomes three classes, each answering to one of them, plus a few lines that put them together:

Grader grader = new Grader();
ReportCardText layout = new ReportCardText(grader);
EmailSender sender = new EmailSender();
sender.Send("Maya", layout.Text("Maya", new List<(string Course, int Score)> { ("Math", 93), ("Science", 85), ("English", 71) }));
sender.Send("Sam", layout.Text("Sam", new List<(string Course, int Score)> { ("Math", 78), ("Science", 64), ("English", 88) }));

// One reason to change: the district's grading scale.
class Grader
{
    public string Letter(int score)
    {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
}

// One reason to change: the front office's layout.
class ReportCardText
{
    private Grader grader;

    public ReportCardText(Grader grader)
    {
        this.grader = grader;
    }

    public string Text(string name, List<(string Course, int Score)> scores) =>
        name + ": " + string.Join(", ", scores.Select(s => s.Course + " " + grader.Letter(s.Score)));
}

// One reason to change: how IT sends messages.
class EmailSender
{
    public void Send(string name, string message) => Console.WriteLine("Email to " + name + "'s family: " + message);
}
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
record Score(String course, int points) {}

// One reason to change: the district's grading scale.
class Grader {
    String letter(int score) {
        if (score >= 90) { return "A"; }
        if (score >= 80) { return "B"; }
        if (score >= 70) { return "C"; }
        if (score >= 60) { return "D"; }
        return "F";
    }
}

// One reason to change: the front office's layout.
class ReportCardText {
    private Grader grader;

    ReportCardText(Grader grader) {
        this.grader = grader;
    }

    String text(String name, List<Score> scores) {
        List<String> grades = new ArrayList<>();
        for (Score score : scores) { grades.add(score.course() + " " + grader.letter(score.points())); }
        return name + ": " + String.join(", ", grades);
    }
}

// One reason to change: how IT sends messages.
class EmailSender {
    void send(String name, String message) {
        IO.println("Email to " + name + "'s family: " + message);
    }
}

void main() {
    ReportCardText layout = new ReportCardText(new Grader());
    EmailSender sender = new EmailSender();
    sender.send("Maya", layout.text("Maya", List.of(new Score("Math", 93), new Score("Science", 85), new Score("English", 71))));
    sender.send("Sam", layout.text("Sam", List.of(new Score("Math", 78), new Score("Science", 64), new Score("English", 88))));
}
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
class Grader:
    """One reason to change: the district's grading scale."""

    def letter(self, score):
        if score >= 90:
            return "A"
        if score >= 80:
            return "B"
        if score >= 70:
            return "C"
        if score >= 60:
            return "D"
        return "F"


class ReportCardText:
    """One reason to change: the front office's layout."""

    def __init__(self, grader):
        self.grader = grader

    def text(self, name, scores):
        grades = [course + " " + self.grader.letter(score) for course, score in scores]
        return name + ": " + ", ".join(grades)


class EmailSender:
    """One reason to change: how IT sends messages."""

    def send(self, name, message):
        print("Email to " + name + "'s family: " + message)


layout = ReportCardText(Grader())
sender = EmailSender()
sender.send("Maya", layout.text("Maya", [("Math", 93), ("Science", 85), ("English", 71)]))
sender.send("Sam", layout.text("Sam", [("Math", 78), ("Science", 64), ("English", 88)]))
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
// One reason to change: the district's grading scale.
class Grader {
  letter(score) {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }
}

// One reason to change: the front office's layout.
class ReportCardText {
  constructor(grader) {
    this.grader = grader;
  }

  text(name, scores) {
    return name + ": " + scores.map(([course, score]) => course + " " + this.grader.letter(score)).join(", ");
  }
}

// One reason to change: how IT sends messages.
class EmailSender {
  send(name, message) {
    console.log("Email to " + name + "'s family: " + message);
  }
}

const layout = new ReportCardText(new Grader());
const sender = new EmailSender();
sender.send("Maya", layout.text("Maya", [["Math", 93], ["Science", 85], ["English", 71]]));
sender.send("Sam", layout.text("Sam", [["Math", 78], ["Science", 64], ["English", 88]]));
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B
// One reason to change: the district's grading scale.
class Grader {
  letter(score: number): string {
    if (score >= 90) { return "A"; }
    if (score >= 80) { return "B"; }
    if (score >= 70) { return "C"; }
    if (score >= 60) { return "D"; }
    return "F";
  }
}

// One reason to change: the front office's layout.
class ReportCardText {
  grader: Grader;

  constructor(grader: Grader) {
    this.grader = grader;
  }

  text(name: string, scores: [string, number][]): string {
    return name + ": " + scores.map(([course, score]) => course + " " + this.grader.letter(score)).join(", ");
  }
}

// One reason to change: how IT sends messages.
class EmailSender {
  send(name: string, message: string): void {
    console.log("Email to " + name + "'s family: " + message);
  }
}

const layout = new ReportCardText(new Grader());
const sender = new EmailSender();
sender.send("Maya", layout.text("Maya", [["Math", 93], ["Science", 85], ["English", 71]]));
sender.send("Sam", layout.text("Sam", [["Math", 78], ["Science", 64], ["English", 88]]));
Email to Maya's family: Maya: Math A, Science B, English C
Email to Sam's family: Sam: Math C, Science D, English B

Same two emails, word for word. Now the district's new scale is an edit to Grader and nothing else; the office's layout is ReportCardText; IT's new system is EmailSender. Each class has high cohesion (everything in it is about one subject), so a change to one can't reach into the others.

Try it. The office wants the grades in brackets: Maya: Math [A], Science [B], English [C]. Which one class do you change? Make the change and check that nothing else had to move.

When to bend it

  • A small script that one person owns. If you're the district, the office and IT, one class may be the clearest thing to read. Split it when a second person starts changing it.
  • Don't split too fine. A class for every line of code isn't single responsibility; it's a scavenger hunt. Things that always change together, for the same person, belong together.
  • Splitting has a cost: more classes to find, and a few lines that wire them up. It's worth it when the reasons to change are real and different.

Check yourself

2 questions to try on the lesson page.

So what

Ask of every class: who asks for it to change? If the answer is more than one person, it's probably more than one class. SOLID is five such questions; this was the first.

Key terms

Cheat sheets