Notes on the single responsibility principle of "You must know. Net" by Wang Tao
I. Concepts
Single Responsibility Principle (SRP, single responsibility principle): A class, it is best to do only one thing, there is only one reason for its change.
SRP can be seen as an extension of low coupling and high cohesion in Object-Oriented principles. It defines responsibility as the cause of change to improve cohesion to reduce the cause of change. There are too many responsibilities, and there may be more reasons for change. This will lead to dependency between duties and affect each other, greatly damaging their cohesion and coupling. A single responsibility usually means a single function. Therefore, do not implement too many function points for the class to ensure that the entity has only one reason for its change. Classes that violate this principle should be restructured.
Ii. Case studies
We use a common database management system as an example to describe how to operate data based on different permissions. First look at a design that violates the RSP principles:
We can see that if the permission setting rules change, you must modify all the database operation logic. Here, the responsibility for permission judgment and the responsibility for database operations are implemented in a class. No matter who changes it, dbmanager will modify the current code. According to the principle of single responsibility, we reconstruct the current design as follows:
Looking at the second figure, we find that it is actually a proxy mode. Here we use a proxy mode to solve the division of duties. By using the dbmanagerproxy proxy class to implement separation of duties, the dbmanager class will have only one reason for the change, that is, the change of data operation requirements. The change and modification of permissions will not have any impact on dbmanager, reflects the basic spirit of a single responsibility.
Note: The Key to following this principle is not to divide the number of functional points, but to grasp the cause of class changes.