Single responsibility principle

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(SRP conflict with Model the real world)
Line 33: Line 33:
 
* [[Design maxims]]
 
* [[Design maxims]]
 
*[[Behavioral completeness]]
 
*[[Behavioral completeness]]
 +
 +
 +
[[Category:Bob Martin's principles]]

Revision as of 06:48, 7 October 2010

As the name suggests each class in a program should only have one responsibility.

Each responsibility that a class fulfils is an axis of change. When the requirements of a responsibility change so to must the class. In the case of multiple classes this can result in conflicting pressures. This leads to fragile design that is hard to maintain and hard to change.

A responsibility is in this context a reason for change. For example Uncle Bob

Modem.java -- SRP Violation 
interface Modem 
{ 
    public void dial(String pno); 
    public void hangup(); 
    public void send(char c); 
    public char recv(); 
}

In this case the interface is handling two responsibilities, one for connection and one for data transfer. It needs to be split into two separate interfaces.

A note from Uncle Bob

"The SRP is one of the simplest of the principle, and one of the hardest to get right. Con- joining responsibilities is something that we do naturally. Finding and separating those responsibilities from one another is much of what software design is really about. Indeed, the rest of the principles we will discuss come back to this issue in one way or another. "Uncle Bob

Conflicts with

Model the real world as real world concepts often have multiple responsiblities. Despite this, it is often possible to adhere to both principles if the developer is able to use appropriately granular real world concepts. In my view it is acceptable for developers to violate Model the real world if it results in a design that is easier to understand or more open to change User:BenjaminTaylor.

See also

Personal tools