Application Development Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
cancel
Showing results for 
Search instead for 
Did you mean: 
naimesh_patel
Active Contributor


Today, we will explore about the Single Responsibility Principle.

Definition:

According to Robert C. Martin, Single Responsibility Principle (SRP) by definition is: There would not be more than one reason to change the class. Class would always represent only one responsibility. Here responsibility is the reason tot change the class.


We must not create a single class which has more than one responsibility. If the class has more than one responsibility, than that would be more than one reason to change that class. Classes with more than one responsibility would have a tendency to break more easily than the classes with less responsibility. Whenever, we do the changes in multi responsibility classes, we have to make sure we don’t break the other responsibility of that class - more responsibilities leads to more testing.

Example:


We have to develop a simple report to select the data and than display this data as an ALV. If we design only one single class ZCL_REPORT to achieve this requirement, than we are giving more than one responsibility to this class: 1) Data Selection, 2) Output of DATA (ALV). Clearly, there are two reasons which lead to change this class: Change in Data selection (e.g. changing the formula to calculate the net price) and change in ALV processing (e.g. adding a provision to display default variant). There is no clear distinction between the attributes which belong to which responsibility and we might change them accidentally. So, we need to test the entire class and make sure we haven’t broken this functionality.


We can avoid this risk by segregating both responsibilities in separate classes: class for data selection ZCL_DATA_SELECT & class for ALV ZCL_OUTPUT_ALV. Since we have different classes, we don’t have to worry about making accidental update in the other classes’ attributes. We can still create a class ZCL_REPORT which uses both data selection ZCL_DATA_SELECT and ALV ZCL_OUTPUT_ALV classes.




Dilemma: 

SRP seems to be the simplest principle but it is one of the hardest to get right. Segregating the responsibilities would depend always on the developer. One could still find more than one responsibility in the data selection class ZCL_DATA_SELECT: data selection from DB ZCL_DATA_DB & Data manipulation ZCL_DATA_PROCESS. Class Data selection from DB ZCL_DATA_DB would be still segregated in to more than one responsibility: data selection for each individual sub objects like Class to select material data ZCL_MATERIAL, class to select Customer data ZCL_CUSTOMER etc. We need to find the optimal segregation of the responsibilities between our classes.







2 Comments