Sobes.tech
Middle

Tell us about the principles of SOLID.

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 only one reason to change.
  • O (Open/Closed Principle) — software entities should be open for extension but closed for modification.
  • L (Liskov Substitution Principle) — objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.
  • I (Interface Segregation Principle) — clients should not depend on interfaces they do not use.
  • D (Dependency Inversion Principle) — dependencies should be on abstractions, not on concrete implementations.

Example in Python:

from abc import ABC, abstractmethod

# Single Responsibility Principle
class ReportGenerator:
    def generate(self):
        pass

class ReportSaver:
    def save(self, report):
        pass

# Dependency Inversion Principle
class Database(ABC):
    @abstractmethod
    def connect(self):
        pass

class MySQLDatabase(Database):
    def connect(self):
        print("Connecting to MySQL")

class Application:
    def __init__(self, db: Database):
        self.db = db

    def run(self):
        self.db.connect()

app = Application(MySQLDatabase())
app.run()

This example demonstrates separation of responsibilities and the use of abstractions to manage dependencies.