Share via


Single Responsibility Principle

If you are following the Software Design Principles while developing an application, the first thing that comes to your mind is the Single Responsibility Principle. The Single Responsibility principle says that there should be never be more than one reason to change a class..

"A class should have only one reason to change. " 

This principle states that if we have more than one reason to change a class, we have to split the functionality into as many classes as we need such that one responsibility is handled by one class only. This will make sure that when there is a certain change that need to be made on the application, there is always on specific class where change can be applied.  For example, let us take an example below : 

class Calculator
{
   public void  Add(int  a, int  b) { ... }
   public void  WriteToConsole(){ ... }
}

Here the calculator has two methods, one is Add, which adds two numbers and a method to display the content into screen. But these are two responsibilities if you see closely. The Calculator can only add but should not print the data within itself. Rather there should be a separate class that is dedicated to print items. 

Lets say, after a certain time, you get a requirement to change the Add method to add float values and also display the value in an XML file. These are two responsibilities. Thus we need to refactor the class into two classes, one of which takes responsibility to add items, while the other takes responsibility to print. 

class Calculator
{
   public void  Add(int  a, int  b) { ... }
}
 
class Print
{
   public void  PrintToStream(TextWriter writer) { ... }
}

Here for simplicity purpose, I have used a Textwriter class on .NET that can hold a Console.Out to write to console, or a FileStream object to write to the XML file. If you are going to design this yourself, you could have also pass your own interface to print the value to either console / or anywhere. 

See Also