Single Responsibility Principle

This article is a continuation of my previous article on SOLID principles. Here we will talk about the Single Responsibility Principle (SRP), in other words "S" from SOLID.

Look at the following image and understand what this person is doing.




Let us write down the tasks he is doing:

  1. Working on laptop
  2. Talking on cell phone
  3. Dialing number on landline device
  4. Reading some papers
Now, do you think this person is really overloaded or over-occupied?

The same thing happens with our code as well when creating some class/object to get some specific functionality and later we continue adding more and more functionality to the same class/object.

Consider the following more technical example:


Why do we have 3 separate layers since I can still write all the code logic on the aspx.cs itself and execute my program?

But architecture-wise, it is wrong and you understand why we have these 3 layers.

Now, each and every layer is given a responsibility of doing/holding some specific tasks.
  1. The Presentation/UI layer is responsible for showing the User Interface on a browser.

  2. The Business Layer is responsible for handling domain logic.

  3. The Data Access layer is responsible for making database connections and CRUD operations.

In short, we have separated our concerns.

SRP: Single responsibility Principle is exactly the same. Do one thing only and do it properly.

To remember this principle I always use one sentence "Do what is told you to do".

I hope you liked this article and will use this concept when coding/programming.

In my next article we will discuss "O", the Open Closed Principle.

Until then stay tuned and keep learning. Cheers!