Single Responsibility Principle-SRP

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.