SRP: Single Responsibility Principle

August 20th, 2006 Leave a comment Go to comments

SRP is one of the fundamental object oriented software design principles, first introduced by Tom DeMarco in 1979.

In simple terms, SRP states that every class should have a single well defined goal, and that all members of that class (properties, methods, etc.) should work together to achieve that goal. Robert Martin puts it in slightly different terms:

There should never be more than one reason for a class to change.

Essentially SRP enforces the concept of high cohesion that should not only be applied to classes but also internals of a class, such as methods.

So why is SRP such an important design principle? It is because a class with multiple responsibilities is more difficult to change and more difficult to reuse (design smells: fragility and immobility).

While SRP is quite easy to understand, it’s not always logical to implement. Consider the following class:

Given the convenience of having a customer class that is smart enough to know how to load and save itself, would you rather break it out like this?:

According to SRP, you should, because the combined customer class shares multiple responsibilities: customer business logic, and customer persistence logic. In fact if you use TDD, you may even be forced to separate these two responsibilities.

In practicality, however, while we should keep this principle in mind and try to apply it wherever it makes sense, we should never get so carried away that we start introducing other design smells in our architecture, such as Rigidity, Viscosity, and Needless Complexity.

  1. Jonas
    February 13th, 2007 at 03:19 | #1

    Well. I think that you should separate those two. Will you always save the information to a file? Will you always save it in the same format? I think not =)

  2. M. Haroon
    February 13th, 2007 at 10:22 | #2

    There is not really a silver bullet, if you will, and whether or not to apply this principle should be determined by the situation at hand. There may be situations where extensibility is required, in which case separation of business logic from persistence logic shall be desirable; in other situations where, for example, you are guaranteed to always be persisting to a file in the same format, for example, separating these responsibilities may only introduce needless complexity.

  3. August 27th, 2011 at 13:39 | #3

    I liked your article is an interesting technology
    thanks to google I found you

  1. No trackbacks yet.
 

Comment moderation is enabled. Your comment may take some time to appear.