1. Introduction to SRP (SRP -- Single-Responsibility Principle): For a class, you should focus only on one thing and only one cause of its changes. The so-called responsibility, we can understand it as a function, that is, this class function should have only one, not two or more. It can also be understood as the reason for referencing changes. When you find that two changes require us to modify this class, you should consider removing this class. Because responsibility is an axis of change, when the demand changes, this change will reflect the changes in class responsibilities. "Just like a person with multiple roles, and these tasks are not closely related or even have conflicts, then he cannot solve these responsibilities well and should be assigned to different persons to do the same."
Ii. Example: Violation of SRP principlesCode:
The modem interface has two responsibilities: connection management and data communication;
Interface Modem
{
Public void dial (string PNO );
Public void hangup ();
Public void send (char C );
Public void Recv ();
} If the application Program Changes affect the connection function, so reconstruction is required:
interface datachannel
{< br> Public void send (char C);
Public void Recv ();
}< br> interface connection
{< br> Public void dial (string PNO);
Public void hangup ();
}
3. Advantages of SRP: eliminate coupling, reduce code rigidity odor caused by demand changes
4. Notes for using SRP: 1. A reasonable class should have only one reason for its change, that is, a single responsibility;
2. It is unwise to apply the SRP or other principles without any signs of change;
3. the SRP principle should be applied to reconstruct the code when the actual requirement changes;
4. Test-driven development forces us to separate unreasonable code before the design smells bad.
5. If the test cannot force separation of duties, the bad smell of rigidity and vulnerability will become very strong, so we should refactor the code in facade or proxy mode.