This is part one of a five part series about SOLID class design principles by
Robert C. Martin.
The SOLID principles focus on achieving code that is maintainable,
robust, and reusable. In this post, I will discuss the Single
Responsibility Principle.
The Single Responsibility Principle (SRP): A class should have one, and only one, reason to change.
The SRP is roughly the same as having "high cohesion".
A class is said to have high cohesion if it's behaviours are highly
related, and strongly focused. The SRP states that a class should be
cohesive to the point that it has a single responsibility, where a
responsibility is defined as "a reason for change."
The Benefits
- The class is easier to understand
When the
class only does "one thing", its interface usually has a small number
of methods that are fairly self explanatory. It should also have a small
number of member variables (less than seven-ish).
- The class is easier to maintain
Changes
are isolated, reducing the chance of breaking other unrelated areas of
the software. As programming errors are inversely proportional to
complexity, being easier to understand makes the code less prone to
bugs.
- The class is more reusable
If a class has
multiple responsibilities, and only one of those is needed in another
area of the software, then the other unnecessary responsibilities hinder
reusability. Having a single responsibility means the class should be
reusable without modification.
No comments:
Post a Comment