Problem Statement
When code mixes responsibilities, changes in one part cause unexpected bugs in others. Classes become hard to understand and maintain, slowing down development and increasing errors.
This diagram shows how a design with many roles in one class leads to problems, while applying SOLID principles separates roles and brings benefits.
### Before (Violating SOLID - Single Responsibility Principle) class UserManager: def __init__(self, user_data): self.user_data = user_data def save_user(self): # code to save user to database pass def send_welcome_email(self): # code to send email pass def validate_user(self): # code to validate user data pass ### After (Applying SOLID - Single Responsibility Principle) class UserValidator: def validate(self, user_data): # code to validate user data pass class UserRepository: def save(self, user_data): # code to save user to database pass class EmailService: def send_welcome_email(self, user_data): # code to send email pass # Usage user_data = {...} validator = UserValidator() if validator.validate(user_data): repo = UserRepository() repo.save(user_data) email_service = EmailService() email_service.send_welcome_email(user_data)
class Shape {
draw() { /* draw shape */ }
}
class Circle extends Shape {
draw() { /* draw circle */ }
}robot.work()?interface Worker {
void work();
void eat();
}
class Robot implements Worker {
public void work() { System.out.println("Robot working"); }
public void eat() { throw new UnsupportedOperationException(); }
}
Robot robot = new Robot();
robot.work();class Bird {
void fly() { System.out.println("Flying"); }
}
class Ostrich extends Bird {
void fly() { throw new UnsupportedOperationException(); }
}PaymentProcessor interface has methods payWithCreditCard(), payWithPayPal(), and payWithCrypto(). A new payment method is added, but many classes implementing this interface do not support all methods, causing empty or error implementations. How should you fix this design following SOLID principles?Pass the test and this pattern moves unknown