Single Responsibility Principle

Upasana | January 08, 2018 | 2 min read | 11 views


(from SOLID Principles with Uncle Bob - Robert C. Martin - http://www.hanselminutes.com/145/solid-principles-with-uncle-bob-robert-c-martin)

Single Responsibility Principle, what does it mean? It means that a software module should have one reason to change, then that’s what I call a responsibility, a reason to change.

So for example, take a payroll application, if there’s an employee class in that payroll application, you could imagine that it might have methods for calculate pay or perhaps another method for print a report, perhaps another method in the employee object for save me to the database, and what’s unfortunate about these three methods existing in the same class is that they have all three completely different reasons to change. The payroll, the calculate pay will change if the accountants decides on a new way of calculating pay. The report generator will change if the people who consume the reports want the format of the reports to change. The save function will change if the DBA’s decide that we needto change the database’s schema. That means that this one class has three different reasons to change and there are probably many other classes that depend upon it and so as it changes those depending classes also suffer through change, they’ll be effective or impacted by those changes.

So the Responsibility Principle simply says, "Find one reason to change and take everything else out of the class." So that you separate the things that change for different reasons, you group together the things to change for the same reasons. This is somewhat out of the norm for object oriented design, early object oriented design principles had as grouping together functions that operated on the same data structures so that the methods of a class would all manipulate the same variables of that class, but if those methods change for different reasons then they really belong in separate classes.

Cohesion is a very important concept when we think about microservices, its the drive to have related code grouped together.

Robert C. Martin has reinforced this while defining the ‘Single Responsibility Principle’, which states

“Gather together those things that change for the same reason, and separate those things that change for different reasons.”


Top articles in this category:
  1. Cracking Spring Microservices Interviews - question bank
  2. 50 microservices interview questions for Java developers
  3. Is it a good practice to deploy multiple microservices in a single tomcat container
  4. Spring Cloud and its advantages
  5. Why Microservices are better than Monoliths
  6. What is Spring Boot and what are its advantages
  7. How will you Partition a typical e-shop into Microservices Architecture

Recommended books for interview preparation:

Find more on this topic: