Single responsibility principle

From CSSEMediaWiki
Revision as of 08:46, 21 September 2008 by Jason Clutterbuck (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

Personal tools