liveBook · Manning

Cohesive class

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

A class whose members collectively serve one clear primary responsibility.

A cohesive class gives its members one clear primary responsibility. Its purpose is easy to understand and its code is easier to maintain because related state and behavior change together. section 2.3.1

Separate automobile responsibilities

An AutomobileApp that operates, maintains, and cleans a car is not cohesive. Refactor it into Automobile for operation, Garage for maintenance, and CarWash for cleaning. Each class then has one primary reason to change. section 4.2.1

Listing 4.1 (Program 4.1 Automobile-1): AutomobileApp.h (not cohesive)
class AutomobileApp
{
public:
    void accelerate();            #1
    void adjust_headlights();     #1
    void apply_brakes();          #1
    void change_oil();            #1
    void change_tires();          #1
    void check_brakes();          #1
    void check_tires();           #1
    void rotate_tires();          #1
    void shut_off_engine();       #1
    void start_engine();          #1
    void tuneup_engine();         #1
    void turn_left();             #1
    void turn_right();            #1
    void vacuum_car();            #1
    void wash_car();              #1
    void wax_car();               #1

private:
    Brake brakes[4];              #2
    Engine engine;                #2
    Oil engine_oil;               #2
    Direction heading;            #2
    Headlight headlights[4];      #2
    int speed;                    #2
    Soap soap;                    #2
    Tire tires[4];                #2
    Vacuum vacuum_cleaner;        #2
    CarWax wax;                   #2
};

Inspect the mixed-responsibility AutomobileApp interface before comparing it with the cohesive Automobile and Garage design. section 4.2.1

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

How deep it goes
Defines cohesion and demonstrates refactoring responsibilities, stopping short of implementation internals.
Examples
Uses Book and Catalogue, then contrasts AutomobileApp with Automobile, Garage, and CarWash.
What you can do after
Apply the Single Responsibility Principle to split classes with unrelated state and behavior.
How it connects
Connects cohesion with the Single Responsibility Principle, loose coupling, and the Principle of Least Knowledge.

Also explained in

Compare how 2 books explain cohesive class →

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.