Five essential object-oriented design principles for maintainable and scalable software
Principle | Description | Mnemonic |
---|---|---|
SRP | One reason to change | One job per class |
OCP | Open for extension, closed for modification | Plug in new features |
LSP | Subtypes replace base types | Replaceable children |
ISP | Small, focused interfaces | Only what you use |
DIP | Depend on abstractions | Use interfaces |
class Report:
def __init__(self, title, content):
self.title = title
self.content = content
class ReportPrinter:
def print_report(self, report):
print(f"Title: {report.title}")
print(f"Content: {report.content}")
class ReportExporter:
def export(self, report):
raise NotImplementedError
class PDFExporter(ReportExporter):
def export(self, report):
print(f"Exporting '{report.title}' as PDF...")
class HTMLExporter(ReportExporter):
def export(self, report):
print(f"Exporting '{report.title}' as HTML...")
class Bird:
def fly(self):
print("Bird is flying")
class Sparrow(Bird):
def fly(self):
print("Sparrow is flying")
def make_bird_fly(bird):
bird.fly()
make_bird_fly(Sparrow()) # Output: Sparrow is flying
class Printable:
def print(self):
raise NotImplementedError
class Saveable:
def save(self):
raise NotImplementedError
class Document(Printable, Saveable):
def print(self):
print("Printing document...")
def save(self):
print("Saving document...")
class Database:
def connect(self):
raise NotImplementedError
class MySQLDatabase(Database):
def connect(self):
print("Connecting to MySQL database...")
class AppService:
def __init__(self, db: Database):
self.db = db
def start(self):
self.db.connect()
# Usage
db = MySQLDatabase()
service = AppService(db)
service.start()