Junior — Middle
Can you give an example of a situation where the single responsibility principle is applied in software?
sobes.tech AI
Answer from AI
The Single Responsibility Principle (SRP) states that each module or class should have only one reason to change, meaning it should be responsible for a single specific task.
An example from Node.js:
Suppose you have a class that simultaneously handles database logic and is responsible for formatting data for output. This violates SRP.
It is better to separate:
- A class or module that only handles interaction with the database (CRUD operations).
- A separate module that deals with formatting and preparing data for the client.
Such separation simplifies maintenance and testing of the code, as changes in formatting logic will not affect database operations and vice versa.