Middle
Tell about the principles of SOLID. How were they applied in your project?
sobes.tech AI
Answer from AI
The SOLID principles are five fundamental principles of object-oriented programming aimed at creating flexible and maintainable code:
- S (Single Responsibility Principle) — a class should have one responsibility.
- O (Open/Closed Principle) — software entities should be open for extension but closed for modification.
- L (Liskov Substitution Principle) — objects of subclasses should replace objects of base classes without affecting the correctness of the program.
- I (Interface Segregation Principle) — it's better to have several specific interfaces than one general-purpose interface.
- D (Dependency Inversion Principle) — high-level modules should not depend on low-level modules; both should depend on abstractions.
Application in a project: In one of my projects, I used SOLID for refactoring monolithic code. For example, I split large classes into smaller ones with a single responsibility (SRP), introduced abstract classes and interfaces to extend functionality without changing existing code (OCP), and applied dependency injection (DIP) to simplify testing and increase modularity.
Python example:
from abc import ABC, abstractmethod
class PaymentProcessor(ABC):
@abstractmethod
def pay(self, amount):
pass
class CreditCardProcessor(PaymentProcessor):
def pay(self, amount):
print(f"Paying {amount} with a credit card")
class Order:
def __init__(self, processor: PaymentProcessor):
self.processor = processor
def checkout(self, amount):
self.processor.pay(amount)
# Usage
processor = CreditCardProcessor()
order = Order(processor)
order.checkout(100)
This approach makes it easy to add new payment methods without changing the Order class.