Refactoring to SRP: Extracting Classes
What you'll learn: How to take a class that does too much and break it into smaller, focused classes—each with a single responsibility.
The Core Idea
When you identify that a class violates the Single Responsibility Principle (you've spotted multiple responsibilities or axes of change), the most direct fix is extraction. You literally pull out one responsibility into its own class, leaving the original class cleaner and more focused.
Think of it like organizing a cluttered junk drawer. Instead of one drawer holding batteries, tools, receipts, and snacks, you create separate containers: one for office supplies, one for tools, one for snacks. Each container now has a single, clear purpose.
How It Works
- Identify distinct responsibilities in your bloated class (you learned this in "Identifying Multiple Responsibilities")
- Choose one responsibility to extract
- Create a new class to hold that responsibility
- Move related methods and data to the new class
- Update the original class to use the new class (through composition)
The original class may now use the extracted class, but it no longer does that work itself. This reduces coupling between concerns and increases cohesion within each class.
Example Scenario (Conceptual)
Imagine a Report class that both calculates report data and formats it for printing. Extract a ReportFormatter class to handle formatting, leaving Report to focus solely on data calculation. Now each class has one reason to change: calculation logic or formatting logic—never both.
Key Takeaway: Extracting classes is the primary technique for fixing SRP violations—pull each responsibility into its own focused class, letting them collaborate rather than coexist in chaos.