Sobes.tech
Middle

Tell about the principles of SOLID.

sobes.tech AI

Answer from AI

SOLID principles are a set of five fundamental object-oriented programming principles that help create flexible and maintainable code:

  • S (Single Responsibility Principle) — a class should have only one single responsibility.
  • O (Open/Closed Principle) — software entities should be open for extension but closed for modification.
  • L (Liskov Substitution Principle) — objects of subclasses should be interchangeable with objects of the base class without breaking the logic.
  • I (Interface Segregation Principle) — it is 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.

Example in JavaScript for the Single Responsibility Principle:

class User {
  constructor(name) {
    this.name = name;
  }
}

class UserRepository {
  save(user) {
    // logic to save user to database
  }
}

Here, the User class is responsible only for user data, and UserRepository handles saving, which aligns with SRP.