S.O.L.I.D. : 1. Single Responsibility Principle

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 expresses the principle as, “A class should have only one reason to change.


Violation Of Single Responsibility Principle:

In this example class is supposed to create response for any request, but in the same class we are also formatting the response in json format which is not acceptable because in future response may be in xml or in csv then it will be very complex to handle all things in a single class. To avoid these messy things from a class we should follow this principle.

Refactored code:

For example we can refactor this class and can split in some classes according to their responsibility.

Next Principle >>

<< SOLID Principles

Please follow and like us: