Single Responsibility Principle — S of SOLID

Ashan Priyadarshana
2 min readAug 6, 2021

The Single Responsibility principle states that any software entity (class, method) should have only one responsibility assigned to it. If you are in any doubt on whether should you change a class or a method code, the only thing you need to do is ask the following two questions and if the answer is yes, then you need to change that particular class code/method code.

Bulbs are meant to give light only — photo by Rodolfo Clix
  1. Does the class or method do more than one procedure? If so, it is advisable to separate it into two distinct classes/methods, so that each will handle a single responsibility.
  2. Does that logic solely represent or belong only to the relevant class? If not, you should abstract out those methods (logic) and put or implement them in interfaces.

Here in the highlighted section, the method addPagesAndPrint() violates the S of SOLID principles — which is Single Responsibility. As you can see it does two tasks, it updates the number of pages in the book and prints the book’s current details. These two tasks should be separated and should be in two different methods as below:

With that separation, we come to the next question which is checking whether are we still…

--

--

Ashan Priyadarshana

Associate Technical Lead | BSc. Information Technology | MSc. Artificial Intelligence | Founder Programming.lk | GSoC 2017 |