SOLID — Explained with Examples
SOLID is a set of five object-oriented design principles that guide developers to build maintainable, scalable, and testable software systems.
SOLID is an acronym coined by Robert C. Martin (Uncle Bob) representing five principles of object-oriented design. These principles help developers create code that is easy to maintain, extend, and refactor over time.
The five principles are:
Single Responsibility Principle (SRP) — A class should have one reason to change. Each class handles a single concern.
Open/Closed Principle (OCP) — Classes should be open for extension but closed for modification. You add new behavior without touching existing code.
Liskov Substitution Principle (LSP) — Subtypes must be substitutable for their base types without altering the correctness of the program.
Interface Segregation Principle (ISP) — Many specific interfaces are better than one general-purpose interface. Clients should not depend on methods they don’t use.
Dependency Inversion Principle (DIP) — High-level modules should not depend on low-level modules. Both should depend on abstractions.
Why SOLID Matters
Without SOLID, codebases become rigid, fragile, and difficult to change. A modification in one place breaks something elsewhere. Testing becomes a nightmare because classes are tightly coupled. SOLID flips this: each principle addresses a specific form of coupling or cohesion problem.
Real-World Analogy
Think of a restaurant kitchen. Each station (grill, prep, pastry) has a single responsibility (SRP). The menu can be extended with new dishes without remodeling the kitchen (OCP). A line cook can substitute for the head chef on specific tasks (LSP). Waitstaff only interact with the expeditor, not every cook (ISP). The kitchen depends on the menu board (abstraction), not on specific chefs (DIP).
Example: Violating vs Following SOLID
# Violating SRP — class handles both data and report generation
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def calculate_tax(self):
return self.salary * 0.2
def generate_report(self):
return f"Employee: {self.name}, Tax: {self.calculate_tax()}"
# Following SRP — separate concerns
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class TaxCalculator:
@staticmethod
def calculate(employee):
return employee.salary * 0.2
class ReportGenerator:
@staticmethod
def generate(employee):
return f"Employee: {employee.name}, Tax: {TaxCalculator.calculate(employee)}"Related Terms
Single Responsibility Principle, Open/Closed Principle, Liskov Substitution Principle, Interface Segregation Principle, Dependency Inversion Principle
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro