This repository provides examples of code refactoring to implement SOLID principles:
- Single Responsibility principle (SRP)
- Open/closed principle (OCP)
- Liskov Substitution principle (LSP)
- Interface Segregation principle (ISP)
- Dependency injection principle (DIP)
You can find 2 commits:
#1- first, "bad" version of code#2- refactored, "good" version of code
Of course, there could be done deeper refactoring, but I decide to show some simple steps to implement this:
- Move code that solves not direct problem to different class, it solves SRP (e.g.
OrderRepository,AnalyticsService,NotificationService,ReportService) - Combine same code to a class, it will be easier to change similar logic after if you need, it solves OCP (e.g.
Logger,ConsoleLogger,OrderRepository) - Add small interfaces, it solves ISP (e.g.
Logger) - Instead of if statements use inheritance and provide abstract methods to child, it solves LSP (e.g.
Order,DigitalOrder,PhysicalOrder) - Inject dependencies, do not create objects by yourself, it solves DIP (e.g.
OrderManager) - Move object's logic to object itself, it solves SRP (e.g.
Order)