Card 06/ 08

GotchaDifficulty: Intermediate2 min

One Method per Class Is Not Single Responsibility

Splitting until every class has one method scatters one decision across ten files.

Single responsibility is about who asks for changes, so the number of methods in a class tells you nothing about it. Splitting a class until each piece has one method does not satisfy the principle; it usually breaks cohesion instead, scattering one decision across many files. This card shows the over-split design beside the right one, so that you can recognise the mistake.

The mistake is easy to make after a refactoring that worked. Splitting SalesReport into three classes helped, so splitting further feels like more help. Here is what happens when the finance part, the sales total, is split by method rather than by actor.

The finance logic split by method, and kept together

Split by methodLow cohesion

Five classes for one rule:

  • SaleSummer adds the amounts
  • RefundSubtractor removes refunds
  • VatRemover takes off the tax
  • PennyRounder rounds to two places
  • TotalPipeline calls the four in order

Finance changes the rounding rule, and the developer must open five files to understand one calculation.

Split by actorHigh cohesion

One class for one rule:

  • SalesTotal with methods to add amounts, remove refunds, take off tax and round

Finance changes the rounding rule, and every line it might affect is on one screen.

Both designs answer to finance alone, so the left one gains nothing under the principle. It loses a lot. The steps of one calculation change together: a new tax rule may change how refunds are removed, and rounding may need to happen before tax rather than after. On the left, each such change crosses class boundaries, so it touches several files and several tests, which is rigidity created on purpose.

The test is the same one used to split a class: list who asks for changes. If two pieces of code always change at the same time for the same people, they belong together, however many methods they need. If they change for different people, they belong apart, even if each is one line.

Robert C. Martin makes the same correction in his own writing: the principle was never "a function should do one thing". That rule is about functions, and it is a good one. Single responsibility is about the reasons a module changes.