Problem Statement
When code is tightly coupled and poorly organized, adding new features or fixing bugs becomes risky and slow. Changes in one part can break others unexpectedly, making the system fragile and hard to maintain.
┌───────────────┐ ┌───────────────┐ ┌───────────────┐ │ Single Class │──────▶│ Multiple │──────▶│ Small Classes │ │ Doing Many │ │ Classes with │ │ with One │ │ Jobs │ │ Clear Roles │ │ Responsibility│ └───────────────┘ └───────────────┘ └───────────────┘
This diagram shows the evolution from one big class doing many jobs to multiple small classes each with a single responsibility, illustrating the Single Responsibility Principle from SOLID.
### Before applying SOLID (violating SRP and OCP): class OrderProcessor: def __init__(self, order): self.order = order def calculate_total(self): total = 0 for item in self.order.items: total += item.price * item.quantity return total def save_order(self): # code to save order to database pass def send_confirmation_email(self): # code to send email pass ### After applying SOLID (SRP and OCP applied): class OrderCalculator: def calculate_total(self, order): total = 0 for item in order.items: total += item.price * item.quantity return total class OrderRepository: def save(self, order): # code to save order to database pass class EmailService: def send_confirmation(self, order): # code to send email pass class OrderProcessor: def __init__(self, calculator, repository, email_service): self.calculator = calculator self.repository = repository self.email_service = email_service def process(self, order): total = self.calculator.calculate_total(order) self.repository.save(order) self.email_service.send_confirmation(order) return total