OO Principles - Single Responsibility Principle (SRP)

I have recently started reading "Agile, Principles, Patterns and Practices in C#" by Robert Martin. It is an excellent book that speaks about the basics of OOAD, Patterns and using them in C#.

One of the things that I remember reading long time back are the 5 main principles of OOAD. They were

  1. Single Responsibility principle (SRP)
  2. Open/Closed Principle  (OCP)
  3. Liskov Substitution Principle (LSP)
  4. Dependency Inversion Principle (DIP)
  5. Interface Segregation Principle (ISP)

Any good object oriented programmer SHOULD know about these principles. Lets look at the SRP in this entry

The SRP is defined as follows:
 
                                     A class should have only one reason to change.

As simple as this sounds, over the time of development a class becomes blown up and becomes responsible for more than one functionality or the original purpose it was designed for.

Robert defines a Responsibility to be a reason for change.


He gives 2-3 examples in the book that violates this principle and then a way to fix them. My favorite was the good old Rectangle example where a Rectangle class is defined as follows

Rectangle
{
    Draw()
    Area()
}


Imagine a case where this class(in Shapes.dll) is used by two applications. One application(A.exe) just needs the Area value while the other application(B.exe) needs both the Draw and Area methods.

In .NET terms, this would be two exe using the same "Shape" dll.  Now if changes are made to to the Rectangle class because of changes required by B.exe in the draw method, this would require us to recompile, rebuild, retest the A.exe application.

A better idea as Robin suggests would be to separate the rectangle class into two classes as given below



GeometryRectangle
{
    Area()
}

Rectangle: GeometryRectangle
{
    Draw()
}

And of course these have to be in different dlls. So lets say that GeometricRectangle is in a dll called GeometricShapes.dll and Rectangle is in Shapes.dll then the depndency becomes 

A --> GeometricShapes.Shape.dll 

B --> Shapes.dl
  --> GeometricShapes.Shape.dll 



Good thing is changes made to Rectangle(draw method) will affect only recompiling B.exe and not A.exe!!

In the next entry we will look into the Open/Closed Principle  (OCP)
HTH
Hari

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Enter the above security code (required)

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.