Card 01/ 08

ConceptDifficulty: Beginner2 min

Single Responsibility: One Reason to Change

A class should answer to one group of people, not do one tiny thing.

The single responsibility principle says that a class should have one reason to change. Robert C. Martin later sharpened the wording: a module should be responsible to one, and only one, actor. An actor is a group of people who ask for changes, such as the finance team or the marketing team. This card explains what that means and why the popular version, "a class should do one thing", leads people astray.

Here is the problem it solves. A shop has a SalesReport class that adds up the day's sales, formats them as text, and saves the result. On Monday the finance team asks for totals to be rounded differently. The same afternoon the marketing team's new report layout comes out with the wrong figures, because the formatting code called the total method that finance had just changed. Two teams, one class, and a change for one of them broke the other.

The class has three reasons to change, one per actor:

Three actors asking for changes to one class

The principle asks you to split the class so that each actor's requests land in a different place. Then a rounding change for finance cannot reach the layout code, because the layout code lives in a class finance never edits.

Notice what the principle does not ask. It does not count methods. A SalesTotal class with five methods that all serve finance has one responsibility. A class with a single method run() that calculates, formats and saves has three. "Do one thing" sounds right but sends people counting the wrong thing.

A Swiss Army knife shows the problem. It is one tool with many jobs, and sharpening the blade means sending the whole knife away, scissors and all. The analogy has a limit: a knife's tools do not share parts, while a class's methods share its fields and call each other, which is exactly how a change for one actor reaches another.

← → move through sections and cards