Single Responsibility Principle (SRP)

Cohesion: functional correlation between constituent elements of a module.
On a category, it should only be one the cause of change.
When needs change, the change will be reflected as a change in responsibilities of the class, if a class bear more than one role, then the cause of it there will be more changes.
If a class too many responsibilities to bear, it means these functions coupled together. A change in responsibilities may weaken or inhibit the ability of this class perform other duties.
This coupling will lead to fragile designs, when a change occurs, the design will suffer unexpected damage.

What are the responsibilities?
In the SRP, it defined responsibilities "reasons for the changes." If you can think of more than a motivation to change a class, then the class will have more than one role. Sometimes it is difficult to notice this, we are accustomed to consider as a group responsibility.
Modem interface, most people think that this interface is very reasonable:

public interface Modem {
    public void dial(String pno);

    public void hangup();

    public void send(char c);

    public void recv();
}

However, this interface has two display functions (1) Connection Management (2) data communications.
dial and hangup a connection process, send and recv data communication
both functions should be separated from it? This depends on how the application changes. If the application changes affect the function of the signature connection, then this will have a rigid design of the smell, because send and recv class must be recompiled.
In this case, the two functions should be separated, do so to avoid the client and the two coupled together responsibilities.

interface DataChannel {
    public void send(char c);

    public void recv();
}

interface Connection {
    public void dial(String pno);

    public void hangup();
}

In addition, if the changes in the way the application will always result in a change of these two functions simultaneously, without separating them for so long, in fact, they will have separate unnecessary complexity of smell.

Summary
SRP is one of the easiest of all the principles, but also one of the most difficult to correct use. Much of the software design really need to do is find those duties and responsibilities separated from each other.

  

  

Guess you like

Origin www.cnblogs.com/lujiango/p/11454862.html