liveBook · Manning

Single responsibility principle

As explained in Unit Testing Principles, Practices, and Patterns

The Single Responsibility Principle states that a class or module should have one responsibility and one reason to change.

The Single Responsibility Principle assigns each class one responsibility and one reason to change. In practice, separate business logic from orchestration and communications. section 11.8 section 7.1

Apply the principle by:

  • Splitting a class when mocking a concrete dependency requires preserving part of its functionality. section 11.8
  • Moving domain logic into one class and communication with out-of-process dependencies into another. section 11.8
  • Keeping complex, important code narrow while allowing orchestration code to coordinate many collaborators. section 7.1

Refactoring an overcomplicated class

Extract business logic from a class that also coordinates difficult dependencies. Leave a humble object to orchestrate, and test the extracted logic without those dependencies. section 7.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Explains responsibility separation through dependency examples, Humble Objects, and code depth versus width, without prescribing exhaustive design rules.
Examples
Uses concrete-class mocking, difficult dependencies, extracted logic, functional cores, domain layers, controllers, and presenters as examples.
What it assumes
Assumes familiarity with classes, collaborators, unit testing, and architectural separation; teaches responsibility through refactoring examples.
What you can do after
Refactor mixed classes into focused domain logic and simpler orchestration components that are easier to test.
How it connects
Connects to unit testing, black-box testing, hexagonal architecture, functional architecture, Humble Object, MVC, MVP, and Domain-Driven Design.

Also explained in

Compare how 7 books explain single responsibility principle →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.