SOLID one by one — S

Date — 12/Sep/2018

rahul reddy
2 min readSep 13, 2018

This is the second post in the series of posts on Solid. In this I will explain the first principle in SOLID, S. It stands for Single responsibility principle. The most popular definition of SRP is as below:

The single responsibility principle is a computer programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

Robert C. Martin who introduced this principle defined it as, “A class should have only one reason to change.” The key word being “change”. According to this definition state of a class changes only for a single reason.

What it means is that any class in an object oriented code base should have only one responsibility and the state of a class should change only in one way. This is very difficult to implements in practice espically the second part of it. So generally people try to have different classes for each method of a class even when it doesn't make any sense. So another way to understand SRP and avoid falling in this trap can be

“a class should do everything it can do and only things it can do. Nothing less nothing more.”

The ideal design will follow the above rule while maintaining change only for one reason rule. One should be extremely careful while using the above rule because if misused it will create GOD classes every thing SRP stands aganist. To illustrate this point consider a common class like Application class. Now if you say this class should do everything an application should do then we should write entire code in this class making it a GOD class. Insted what we can do is make sub classes to do smaller works and use them in the application class.

--

--