This principle is also called the cohesion principle. In the past, we advocated the following modules in the process-oriented era: High Cohesion and low coupling (of course, this principle is almost the fundamental principle of software design ).
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. this is because the responsibility is an axis of change. When the demand changes, this change will reflect the changes in the responsibilities of the class.
For example, to design a class, this class needs to retrieve basic information such as a person's name from the database. modified and saved to the database as required. basically, this type of data is required by developers every day. Interface Person
{
Public VoidConnectdb ();
Public VoidDisconnectdb ();
PublicDataset getpersoninfo ();
Public BoolSavepersoninfo ();
..
}
In fact, we can see that the above class (Interface) actually causes two reasons for his change. One is the database change, and the other is the change of the rules for saving user information. we should properly separate the two parts.Interface Dbmanager
{
Public VoidConndb ();
Public VoidDisconndb ();
//Other dB functions;
//,
}
Abstract Class Personinfo
{
Public Dataset getpersoninfo ();
Public Bool Savepersoninfo ();
Private Dbmanager dBm;
Public Personinfo (dbmanager paramdbm)
{
DBM=Paramdbm;
}
}
Interface Persomanager
{
PublicDbmanager dBm;
PublicPersoninfo PI;
}
In fact, it seems that personmanager violates the SRP principle again, but because no one depends on him, we can reuse dbmanager and personinfo very well.
Must multiple roles be separated? Not necessarily, when the applicationProgramThe way these roles change at the same time does not have to be separated. In other words, it is wise to apply SRP if there is no indication. This is also the consistent style of agile development, as is other principles of agile development.