Mastering Design Principles: The Foundation of Scalable Systems
Introduction Design principles are the foundation upon which scalable, maintainable, and efficient systems are built. They provide a set of guidelines that help developers create software that is easy to understand, modify, and extend. In this masterclass, we will delve into the world of design principles, exploring the concepts of SOLID, DRY, KISS, YAGNI, Separation of Concerns, Loose Coupling, and High Cohesion.
SOLID Principles
SOLID is an acronym that stands for five design principles that aim to promote cleaner, more robust, and updatable code for software development in object-oriented languages.
-
Single Responsibility Principle (SRP): This principle states that a class should have only one reason to change. In other words, a class should have a single responsibility or functionality.
Bad design
class Employee: def init(self, name, salary): self.name = name self.salary = salary
def get_employee_info(self):
return f"Name: {self.name}, Salary: {self.salary}"
def save_to_database(self):
# Code to save employee data to database
Good design
class Employee: def init(self, name, salary): self.name = name self.salary = salary
def get_employee_info(self):
return f"Name: {self.name}, Salary: {self.salary}"
class EmployeeRepository: def save_to_database(self, employee): # Code to save employee data to database
* **Open/Closed Principle (OCP)**: This principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.
```python
# Bad design
class Calculator:
def calculate(self, operation, num1, num2):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
# Good design
class Calculator:
def calculate(self, operation, num1, num2):
return operation(num1, num2)
class AddOperation:
def __call__(self, num1, num2):
return num1 + num2
class SubtractOperation:
def __call__(self, num1, num2):
return num1 - num2
-
Liskov Substitution Principle (LSP): This principle states that derived classes should be substitutable for their base classes.
Bad design
class Bird: def fly(self): pass
class Duck(Bird): def fly(self): # Code for duck to fly
class Ostrich(Bird): def fly(self): raise Exception("Ostrich cannot fly")
Good design
class Flyable: def fly(self): pass
class Duck(Flyable): def fly(self): # Code for duck to fly
class Ostrich: def run(self): # Code for ostrich to run
* **Interface Segregation Principle (ISP)**: This principle states that clients should not be forced to depend on interfaces they do not use.
```python
# Bad design
class PrintAndScan:
def print(self):
pass
def scan(self):
pass
class Printer(PrintAndScan):
def print(self):
# Code for printing
def scan(self):
raise Exception("Printer cannot scan")
# Good design
class Printable:
def print(self):
pass
class Scanable:
def scan(self):
pass
class Printer(Printable):
def print(self):
# Code for printing
class Scanner(Scanable):
def scan(self):
# Code for scanning
-
Dependency Inversion Principle (DIP): This principle states that high-level modules should not depend on low-level modules, but both should depend on abstractions.
Bad design
class EmployeeService: def init(self): self.employee_repository = EmployeeRepository()
def get_employees(self):
return self.employee_repository.get_employees()
class EmployeeRepository: def get_employees(self): # Code to get employees from database
Good design
class EmployeeService: def init(self, employee_repository): self.employee_repository = employee_repository
def get_employees(self):
return self.employee_repository.get_employees()
class EmployeeRepository: def get_employees(self): # Code to get employees from database
### DRY Principle
The DRY principle stands for Don't Repeat Yourself. It states that every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
```python
# Bad design
def greet_morning(name):
print(f"Good morning, {name}!")
def greet_afternoon(name):
print(f"Good afternoon, {name}!")
def greet_evening(name):
print(f"Good evening, {name}!")
# Good design
def greet(name, time_of_day):
print(f"Good {time_of_day}, {name}!")
def main():
greet("John", "morning")
greet("Alice", "afternoon")
greet("Bob", "evening")
if __name__ == "__main__":
main()
KISS Principle
The KISS principle stands for Keep it Simple, Stupid. It states that most systems work best if they are kept simple rather than made complicated.
# Bad design
def calculate_area_of_rectangle(length, width):
if length < 0 or width < 0:
raise Exception("Length and width must be non-negative")
return length * width
def calculate_area_of_square(side_length):
if side_length < 0:
raise Exception("Side length must be non-negative")
return side_length ** 2
# Good design
def calculate_area(length, width=None):
if length < 0 or (width is not None and width < 0):
raise Exception("Length and width must be non-negative")
if width is None:
return length ** 2
return length * width
YAGNI Principle
The YAGNI principle stands for You Ain't Gonna Need It. It states that one should not add functionality until it is necessary.
# Bad design
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_employee_info(self):
return f"Name: {self.name}, Salary: {self.salary}"
def save_to_database(self):
# Code to save employee data to database
def send_email(self):
# Code to send email
# Good design
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def get_employee_info(self):
return f"Name: {self.name}, Salary: {self.salary}"
# Only add functionality when it is necessary
Separation of Concerns
Separation of Concerns is a design principle that states that a system should be divided into separate components, each with its own specific concern or responsibility.
# Bad design
class EmployeeService:
def __init__(self):
self.employee_repository = EmployeeRepository()
def get_employees(self):
employees = self.employee_repository.get_employees()
# Code to format employee data
return formatted_employees
class EmployeeRepository:
def get_employees(self):
# Code to get employees from database
# Good design
class EmployeeService:
def __init__(self, employee_repository, employee_formatter):
self.employee_repository = employee_repository
self.employee_formatter = employee_formatter
def get_employees(self):
employees = self.employee_repository.get_employees()
return self.employee_formatter.format_employees(employees)
class EmployeeRepository:
def get_employees(self):
# Code to get employees from database
class EmployeeFormatter:
def format_employees(self, employees):
# Code to format employee data
Loose Coupling
Loose Coupling is a design principle that states that components should be designed to be independent of each other, with minimal dependencies between them.
# Bad design
class EmployeeService:
def __init__(self):
self.employee_repository = EmployeeRepository()
def get_employees(self):
return self.employee_repository.get_employees()
class EmployeeRepository:
def get_employees(self):
# Code to get employees from database
# Good design
class EmployeeService:
def __init__(self, employee_repository):
self.employee_repository = employee_repository
def get_employees(self):
return self.employee_repository.get_employees()
class EmployeeRepository:
def get_employees(self):
# Code to get employees from database
High Cohesion
High Cohesion is a design principle that states that components should be designed to be self-contained, with a clear and well-defined purpose.
# Bad design
class EmployeeService:
def __init__(self):
self.employee_repository = EmployeeRepository()
def get_employees(self):
return self.employee_repository.get_employees()
def save_employee(self, employee):
# Code to save employee data to database
def send_email(self, employee):
# Code to send email
# Good design
class EmployeeService:
def __init__(self, employee_repository):
self.employee_repository = employee_repository
def get_employees(self):
return self.employee_repository.get_employees()
class EmployeeRepository:
def get_employees(self):
# Code to get employees from database
def save_employee(self, employee):
# Code to save employee data to database
class EmailService:
def send_email(self, employee):
# Code to send email
⚔️ YOUR MISSION
Design a system that allows users to create, read, update, and delete (CRUD) employee data. The system should follow the SOLID principles and be loosely coupled.
Read the exercise prompt
What are the benefits of using the SOLID principles in software design?
