Sobes.tech
Senior

Tell me about SOLID. What is it?

sobes.tech AI

Answer from AI

SOLID is a set of five principles of object-oriented programming aimed at creating flexible, extendable, and maintainable code:

  • S (Single Responsibility Principle) — the 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 subclasses should be replaceable with objects of the base class without affecting correctness.
  • I (Interface Segregation Principle) — prefer many specific interfaces over a single general interface.
  • D (Dependency Inversion Principle) — high-level modules should not depend on low-level modules; both should depend on abstractions.

Example in Go (Single Responsibility Principle):

// Bad: the class handles both data management and output
type User struct {
    Name string
}

func (u *User) Save() {
    // save to database
}

func (u *User) Print() {
    fmt.Println(u.Name)
}

// Good: responsibilities are separated

type User struct {
    Name string
}

type UserRepository struct {}

func (r *UserRepository) Save(u *User) {
    // save to database
}

func PrintUser(u *User) {
    fmt.Println(u.Name)
}

This makes the code easier to maintain and extend.