Sobes.tech
Senior

Tell about the principles of SOLID with specific examples.

sobes.tech AI

Answer from AI

The SOLID principles are five fundamental principles of object-oriented design that help create flexible and maintainable systems.

  1. Single Responsibility Principle (SRP) — the principle of single responsibility. Each class should have one and only one reason to change.
class ReportGenerator {
    void generateReport() { /* report generation */ }
}

class ReportPrinter {
    void printReport() { /* print report */ }
}
  1. Open/Closed Principle (OCP) — openness/closedness. Classes should be open for extension but closed for modification.
interface Shape {
    double area();
}

class Circle implements Shape {
    double radius;
    public double area() { return Math.PI * radius * radius; }
}

class Rectangle implements Shape {
    double width, height;
    public double area() { return width * height; }
}

// New shapes can be added without changing existing code
  1. Liskov Substitution Principle (LSP) — Barbara Liskov's substitution principle. Subclass objects should replace superclass objects without breaking the logic.
class Bird {
    void fly() {}
}

class Sparrow extends Bird {}

class Ostrich extends Bird {
    @Override
    void fly() {
        throw new UnsupportedOperationException();
    }
}

// LSP violation: ostrich cannot fly but inherits the fly method
  1. Interface Segregation Principle (ISP) — the principle of interface segregation. Clients should not depend on methods they do not use.
interface Printer {
    void print();
}

interface Scanner {
    void scan();
}

class MultiFunctionPrinter implements Printer, Scanner {
    public void print() { /* print */ }
    public void scan() { /* scan */ }
}

class SimplePrinter implements Printer {
    public void print() { /* print */ }
}
  1. Dependency Inversion Principle (DIP) — the principle of dependency inversion. High-level modules should not depend on low-level modules; both should depend on abstractions.
interface Database {
    void save(Data data);
}

class MySQLDatabase implements Database {
    public void save(Data data) { /* save to MySQL */ }
}

class UserService {
    private Database database;
    public UserService(Database database) {
        this.database = database;
    }
    void saveUser(User user) {
        database.save(user);
    }
}

Thus, SOLID helps create code that is easier to test, extend, and maintain.