SOLID Principles

The five SOLID principles with before-and-after code — single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion — plus when not to apply them.

Intermediate 3 min readLesson 2 of 24 Interview Q&A

SOLID is five principles (collected by Robert C. Martin) for object-oriented code that's easy to change. They are heuristics, not laws: each one reduces a specific kind of pain. Learn the pain, and you'll know when to apply them.

LetterPrincipleIn one line
SSingle ResponsibilityA class should have one reason to change
OOpen/ClosedOpen for extension, closed for modification
LLiskov SubstitutionSubtypes must be usable wherever the base type is
IInterface SegregationDon't force clients to depend on methods they don't use
DDependency InversionDepend on abstractions, not concrete details

S — Single Responsibility

"One reason to change" means one actor or concern that might ask for changes. A class that calculates pay, formats reports and saves to the database changes when accounting, the report designers or the DBAs want something.

Before
Java
class Invoice {
    long total() {...}
    String toPdf() {...}         // presentation
    void saveToDb() {...}        // persistence
    void emailCustomer() {...}   // notification
}
After
Java
class Invoice { long total() {...} }
class InvoicePdfRenderer { byte[] render(Invoice i) {...} }
class InvoiceRepository { void save(Invoice i) {...} }
class InvoiceMailer { void send(Invoice i) {...} }

O — Open/Closed

You should be able to add behaviour without editing existing, tested code. The typical smell is a switch on type that grows with every new case.

// Before: every new shipping method edits this function
double cost(Order o) {
    switch (o.shipping()) {
        case "standard": return 5;
        case "express":  return 15;
        default: throw new IllegalArgumentException();
    }
}

// After: add a class, touch nothing else
interface ShippingPolicy { double cost(Order o); }
class Standard implements ShippingPolicy { public double cost(Order o) { return 5; } }
class Express  implements ShippingPolicy { public double cost(Order o) { return 15; } }
class Drone    implements ShippingPolicy { public double cost(Order o) { return 25; } }  // new

This is the Strategy pattern. Don't pre-abstract everything, though: apply OCP where change is actually happening.

L — Liskov Substitution

If S is a subtype of T, code written for T must work correctly with an S. Subtypes must honour the parent's contract: they may not strengthen preconditions, weaken postconditions, or throw surprising exceptions.

The classic violation: Square extends Rectangle.

Java
class Rectangle {
    protected int w, h;
    void setWidth(int w) { this.w = w; }
    void setHeight(int h) { this.h = h; }
    int area() { return w * h; }
}
class Square extends Rectangle {
    @Override void setWidth(int w) { this.w = w; this.h = w; }    // keeps it square...
    @Override void setHeight(int h) { this.w = h; this.h = h; }
}

void stretch(Rectangle r) {
    r.setWidth(5); r.setHeight(4);
    assert r.area() == 20;          // fails for Square: area is 16
}

Mathematically a square is a rectangle, but a mutable Square doesn't behave like a mutable Rectangle. Fixes: make shapes immutable, or don't relate them by inheritance. Other LSP smells: overriding a method to throw UnsupportedOperationException, or instanceof checks in callers.

I — Interface Segregation

Many small, focused interfaces beat one fat one. Clients shouldn't have to implement or depend on methods they don't need.

Fat interface
Java
interface Machine {
    void print(Doc d);
    void scan(Doc d);
    void fax(Doc d);
}
class BasicPrinter implements Machine {
    public void scan(Doc d) {
        throw new UnsupportedOperationException();
    }
    ...
}
Segregated
Java
interface Printer { void print(Doc d); }
interface Scanner { void scan(Doc d); }
interface Fax { void fax(Doc d); }

class BasicPrinter implements Printer {...}
class OfficeMachine
    implements Printer, Scanner, Fax {...}

D — Dependency Inversion

High-level policy (business rules) shouldn't depend on low-level details (databases, HTTP clients). Both should depend on abstractions, and the abstraction is owned by the high-level side.

usesimplementsOrderServicebusiness logic«interface» OrderRepositoryPostgresOrderRepositoryInMemoryOrderRepository
interface OrderRepository { void save(Order o); Optional<Order> find(String id); }

class OrderService {
    private final OrderRepository repo;
    OrderService(OrderRepository repo) { this.repo = repo; }   // injected
    void place(Order o) { /* rules */ repo.save(o); }
}

// Production
new OrderService(new PostgresOrderRepository(dataSource));
// Tests
new OrderService(new InMemoryOrderRepository());

Dependency inversion is the principle; dependency injection is the technique of passing dependencies in (Dependency injection).

When SOLID goes wrong

Key takeaways
  • SRP: separate concerns that change for different reasons.
  • OCP: add behaviour by adding code (polymorphism), not by editing switches.
  • LSP: subtypes must honour the base contract — Square/Rectangle is the classic violation.
  • ISP: small, role-specific interfaces.
  • DIP: business logic depends on interfaces it owns; details implement them; inject dependencies.
Interview questions
QExplain the Liskov Substitution Principle with an example.medium

Any code expecting a base type must work correctly with a subtype. A mutable Square extending Rectangle violates it: code that sets width 5 and height 4 expects area 20, but the square forces both sides equal and returns 16. The subtype changed the parent's behaviour contract, so it isn't a valid substitute.

QWhat is the difference between dependency inversion and dependency injection?medium

Dependency inversion is a design principle: high-level modules depend on abstractions rather than concrete low-level modules. Dependency injection is a technique for supplying those dependencies from outside (constructor, setter, container) instead of creating them internally. DI is a common way to achieve DIP.