liveBook · Manning

Single responsibility principle

As explained in Object-Oriented Software Design in C++

A design principle stating that a class should have one major responsibility.

The Single Responsibility Principle says a class should be cohesive and have only one primary responsibility. Clear responsibilities make classes easier to understand, use, and maintain. section 2.3.1

Apply the principle by:

  • Separating stored data from collection management: Book stores attributes, while Catalogue adds books and searches them. section 2.3.1
  • Questioning classes that combine unrelated operations; an automobile class covering driving, maintenance, and cleaning is overly complex. section 1.4.2
  • Balancing useful separation against unnecessary class proliferation, since good design can add flexibility but also create complexity. section 1.4.2

Book catalogue

A Book holds title, last name, and first name. Catalogue owns the book list, adds books, and finds matches, including searches with empty fields as don't-cares. Test data demonstrates exact matches, partial matches, and no matches. section 2.3.1

Listing 1.3 (Program 1.2 Changes): Automobile.h (poorly designed)
class AutomobileApp
{
public:
    void accelerate();
    void adjust_headlights();
    void apply_brakes();
    void change_oil();
    void change_tires();
    void check_brakes();
    void check_tires();
    void rotate_tires();
    void shut_off_engine();
    void start_engine();
    void tuneup_engine();
    void turn_left();
    void turn_right();
    void vacuum_car();
    void wash_car();
    void wax_car();
 
private:
    Brake brakes[4];
    Engine engine;
    Oil engine_oil;
    Direction heading;
    Headlight headlights[4];
    int speed;
    Soap soap;
    Tire tires[4];
    Vacuum vacuum_cleaner;
    CarWax wax;
};

Inspect the poorly designed AutomobileApp listing to see how unrelated behaviors and state accumulate in one class. section 1.4.2

How Object-Oriented Software Design in C++ covers it

How deep it goes
Defines cohesion and demonstrates it with Book and Catalogue, while cautioning against unnecessary class proliferation.
Examples
Uses an overloaded automobile class and a tested Book–Catalogue search application.
What you can do after
Build cohesive C++ classes, separate responsibilities, and test their behavior through small application iterations.
How it connects
Connects cohesion with delegation, encapsulating variation, loose coupling, and the Open-Closed Principle.

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 Object-Oriented Software Design in C++. The section links point to the parts of the book it draws on.