Member-only story
Writing quality code involves striking a balance between elegance, performance, and long-term sustainability. Adopting proven design principles facilitates achieving these objectives.
This article explores prominent object-oriented design principles, namely SOLID, DRY, and KISS, and demonstrates their practical application in Python.
Principle I: Single Responsibility Principle (SRP)
According to SRP, every class should have only one reason to change. Put differently, minimize class responsibilities and isolate varying aspects.
Consider refactoring a monolithic logger class, breaking down logging levels into separate entities.
Before:
class Logger:
def debug(self, msg):
self._log("DEBUG", msg)
def info(self, msg):
self._log("INFO ", msg)
def warning(self, msg):
self._log("WARNING", msg)
def _log(self, level, msg):
print(f"{level} {msg}")
After:
class LogLevel:
DEBUG = "DEBUG"
INFO…