Sobes.tech
Middle

Tell about the SOLID principles.

sobes.tech AI

Answer from AI

SOLID is a set of five principles of object-oriented programming that help create flexible, extendable, and maintainable code:

  • S (Single Responsibility Principle) — A class should have only one reason to change, meaning it should perform a single task.
  • O (Open/Closed Principle) — Software entities should be open for extension but closed for modification.
  • L (Liskov Substitution Principle) — Subtypes must be substitutable for their base types without altering the correctness of the program.
  • I (Interface Segregation Principle) — Prefer many specific interfaces over a single general-purpose interface.
  • D (Dependency Inversion Principle) — High-level modules should not depend on low-level modules; both should depend on abstractions.

Example in Python:

class Logger:
    def log(self, message):
        print(message)

class UserService:
    def __init__(self, logger):
        self.logger = logger  # dependency through abstraction

    def create_user(self, username):
        # user creation logic
        self.logger.log(f"User {username} created")

Here, UserService depends on the abstraction Logger, which aligns with the D principle.