Chapter 76. The Single Responsibility Principle

ONE OF THE MOST FOUNDATIONAL PRINCIPLES OF GOOD DESIGN IS:
Gather together those things that change for the same reason, and separate those things that change for different reasons.
This principle is often known as the single responsibility principle, or SRP. In short, it says that a subsystem, module, class, or even a function, should not have more than one reason to change. The classic example is a class that has methods that deal with business rules, reports, and databases:
public class Employee {
public Money calculatePay() ...
public String reportHours() ...
public void save() ...
}Some programmers might think that putting these three functions together in the same
class is perfectly appropriate. After all, classes are supposed to be collections of
functions that operate on common variables. However, the problem is that the three
functions change for entirely different reasons. The calculatePay function will change whenever the business rules for
calculating pay do. The reportHours function will
change whenever someone wants a different format for the report. The save function will change whenever the DBAs change the
database schema. These three reasons to change combine to make Employee very volatile. It will change for any of
those reasons. More importantly, any classes that depend upon Employee will be ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access