Chapter 8: The Single Responsibility Principle

Tom DeMarco and Meilir Page-Jones called it cohesion in their work, which they defined as the functional relatedness of the elements of a module. We modify that meaning a bit and relate cohesion to the forces that cause a module, or a class, to change.

The Single Responsibility Principle
A class should have only one reason to change.

Why is it important to separate the responsibilities into separate classes? The reason is that each responsibility is an axis of change. When the requirements change, that change will manifest through a change in responsibility among the classes. If a class assumes more than one responsibility, that class will have more than one reason to change.

If a class has more than one responsibility, the responsibilities become coupled. Changes to one responsibility may impair or inhibit the class’s ability to meet the others. This kind of coupling leads to fragile designs that break in unexpected ways when changed.

Defining a Responsibility

In the context of the SRP, we define a responsibility to be a reason for change. If you can think of more than one motive for changing a class, that class has more than one responsibility. This is sometimes difficult to see. We are accustomed to thinking of responsibility in groups.

Should the responsibilities be separated? If the application is not changing in ways that cause the coupled responsibilities to change at different times, there is no need to separate them. Indeed, separating them would smell of needless complexity.

There is a corollary here. An axis of change is an axis of change only if the changes occur. It is wise not to apply SRP – or any other principle, for that matter – if there is no symptom.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: