How would you refactor a class that violates SRP?
Answer
The process starts with identifying distinct responsibilities within the class by asking "what reasons does this class have to change?" For each distinct reason, extract the related methods and properties into a new, focused class. Then inject the new classes into the original via constructor injection. Example: a UserService that validates, saves, and emails users gets split into UserValidator, UserRepository, and UserEmailService. The original UserService becomes an orchestrator that coordinates these single-responsibility services. This refactoring should be done incrementally with test coverage at each step. Use IDE refactoring tools (Extract Class, Move Method) to reduce manual errors during the process.
Previous
What is a "god class" and which SOLID principle does it violate?
Next
How does the Strategy pattern support OCP?
More SOLID Principles Questions
View all →- Intermediate How does the Strategy pattern support OCP?
- Intermediate What are the conditions for LSP compliance?
- Intermediate How does ISP prevent "fat interfaces"?
- Intermediate What is the difference between DIP and dependency injection containers?
- Intermediate How does SOLID relate to GRASP principles?