Single Responsibility Principle explained with simple example

Single Responsibility Principle (SRP) is a software design principle which states that every module, class or function of a software should have one and only one responsiblity/functionality to perform. As stated by Robert C.Martin, “A class should have one and only one reason to change“.

Before going ahead we should know why do we need software design principle and what is software design principle.

SRP advantages:

  • Better code organisation
  • Low coupling
  • Easy to maintain
  • Easy to test

Let’s understand SRP with a simple example.

Consider the problem where we have to implement a calculator.

// Sample code
class calculator
{
	public:
		int add (int x, int y)
		{
			cout << "Sum of x: "<< x << " and y: " << y << " = " << (x + y) << endl;
		}
};

Above class looks like doing a very simple operation. Let’s have a look about what this class responsibilities are:

  • Arithmetic responsibility
  • Result displaying responsibility

Now this is a violation of SRP which states that every class should have one and only one responsibility.

Let’s redesign the above class

// Sample code
// This class will only do the arithmetic operation. 
class calculator_srp
{
	public:
		int add (int x, int y)
		{
			return (x + y);
		}
};

// This class will print the result
class print_srp
{
	public:
		void print_result (const char *str)
		{
			cout << str << endl;
		}
};

// Helper function
template <typename T>
std::string ToString(T val)
{
	std::stringstream stream;
	stream << val;
	return stream.str();
}

// This class will process the operation
class command_srp
{
	private:
		calculator_srp calc;
		print_srp      print;

	public:
		void calculate_sum (int x, int y)
		{
			int result = calc.add (x, y);
			string str = "Sum of x: " + ToString (x) + " and y: " + ToString (y) + " = " + ToString (result);
			print.print_result (str.c_str ());
		}
};

Now as you can see, every class has only one job to do.
Also, every class is unaware of how other classes are implemented.

Let’s see how we are going to be benefitted from SRP designs.

Let’s consider we have to enhance the above program to print the result into a file or on screen depending on some configuration. In that case, only “print_srp” class needs to be changed and all other class will remain same.

//Sample code
class print_srp
{
	private:
		bool print_on_screen;
	public:
		void print_result (const char *str)
		{
			if (print_on_screen)
			{
				cout << str << endl;
			}
			else
			{
				// Print in file
			}
		}
};

Let’s consider another example, where we have to only print the result on the screen (currently we are printing both input and results). In this case, we only need to change “command_srp” class and rest all classes will remain same.

Try it out by yourself !!!

Leave a Reply

Your email address will not be published. Required fields are marked *