Sunday, December 29, 2019

Single Responsibility Principle (SRP)

Symptoms / problems

If you are facing any of the following problems randomly or repeatedly then your class is not following SRP

  1. You need to change the same class for Change Requirements with different nature
  2. Many lines of code getting compiled even if you don’t want it
  3. You or QA need to test multiple scenarios even if you make changes to one
  4. When you make one change then you have fear of other code getting affected
  5. Class name consists conjunctions like And, Or
  6. Method names are too long

Solution

Single Responsibility Principle addresses all above problems. Definition itself says that your class or a module must have one and only one reason to change. It makes it clear that your class should not be changed for multiple (even similar) reasons, technically Change Requirements (CRs). Every Change Requirement is nothing but a responsibility.

Let’s understand responsibilities:

Technical Responsibility

Multi-layered applications have clearly defined Separation of Concerns (SOC), Data access layer, Business logic layer, Presentation layer, Utility classes, Business objects, etcs. You must not write logic and data manipulation queries or commands in one class. Data manipulation should go to (may be) Repository and Logic goes to Manager classes. So, that for any change in logic you don’t need to touch Repository. Simple as that - isn’t it? And you know this why Technical SoC is so important.

Functional Responsibility

Let’s say your class processes some request (may be a Controller class) and to process it, it have to validate a request. Your class should not do both. Validation itself is one separate task so it has to go to a different class. So that when any validation changes arrive then you just change Validator class and not the Controller.

Aggregate Responsibility

Trust me, if every class has unit task then you can not write an application. Many times you need to write classes which hold high level flow or logic and to achieve that these classes need to deploy several other classes. Let’s take an example of Controller, it has to validate a request, then process it, maybe it needs to store data in database and parse some response so that it can be sent to client. This is high level flow where, Controller deploys Manager, then Manager deploys Validator & Repository. Here, the Controller does not do everything but it deploys other classes to process its request and that is what aggregate responsibility is.

There is no doubt that by following SRP we end up creating so many classes but that is what Object Oriented Programming is all about, classes - right? Don’t you think - Dependency Injection (DI) is always at your rescue?

No comments:

Post a Comment