SOLID principles

SOLID
Single responsibility, Open-closed, Liskov substitution, Interface segregation, Dependency inversion

Mid-level Always asked 6 min

On this page

The question

Can you explain the SOLID principles, with a violation and a fix for each?

30-second answer

S: one reason to change; split a class that prices, saves and emails. O: extend by adding code; replace a discount switch with Discount classes. L: subtypes keep the parent's promises; no refund() that throws. I: small interfaces; a printer should not implement fax(). D: depend on abstractions; inject an OrderRepository instead of calling new MySqlOrderDao().

Understand it

Refactoring OrderService one letter at a time

Step by step

OrderService prices orders with a switch, saves them with new MySqlDao() and sends emails. Every change lands in this one class.

Step 1 of 6
View as text

One class, OrderService, is refactored step by step.

OrderService prices orders with a switch, saves them with new MySqlDao() and sends emails. Every change lands in this one class. The box lists all three jobs.

S: split by reason to change. Pricing, saving and emailing move into their own classes. Three boxes appear under OrderService.

O: each discount becomes a Discount class. A new discount is a new class, not an edit to a switch. The pricing box becomes a Discount interface and a new Loyalty class is added under it.

L: every Discount keeps the same promise, a price never below zero, so OrderService can use any of them without checks.

I: the fat Notifier is split, so the email sender implements only send(), not sms() and push().

D: OrderService depends on an OrderRepository interface, and the MySQL version is passed in. The service no longer names a database. The saving box becomes an interface with MySqlDao below it.

One class, OrderService, is refactored step by step.

OrderService prices orders with a switch, saves them with new MySqlDao() and sends emails. Every change lands in this one class. The box lists all three jobs.

S: split by reason to change. Pricing, saving and emailing move into their own classes. Three boxes appear under OrderService.

O: each discount becomes a Discount class. A new discount is a new class, not an edit to a switch. The pricing box becomes a Discount interface and a new Loyalty class is added under it.

L: every Discount keeps the same promise, a price never below zero, so OrderService can use any of them without checks.

I: the fat Notifier is split, so the email sender implements only send(), not sms() and push().

D: OrderService depends on an OrderRepository interface, and the MySQL version is passed in. The service no longer names a database. The saving box becomes an interface with MySqlDao below it.

Takeaway: Each SOLID letter removes one reason the class had to change, until OrderService only coordinates small parts behind interfaces.

Match each violation to SOLID

Build

Match each violation to the SOLID principle it breaks.

Drag a piece, or select it and then select a place.

  1. Empty
  2. Empty
  3. Empty
  4. Empty
  5. Empty
View as text

Five design violations each need the SOLID principle they break. Match each violation to the SOLID principle it breaks.

The answers are: one class prices orders, saves them and sends emails breaks S, single responsibility. A switch must be edited for every new discount type breaks O, open/closed. A subclass's refund() throws UnsupportedOperationException breaks L, Liskov substitution. A printer class must implement scan() and fax() it never uses breaks I, interface segregation. A service calls new MySqlOrderDao() inside its methods breaks D, dependency inversion.

S, O, L, I, D: each violation now names the principle that fixes it.

Five design violations each need the SOLID principle they break. Match each violation to the SOLID principle it breaks.

The answers are: one class prices orders, saves them and sends emails breaks S, single responsibility. A switch must be edited for every new discount type breaks O, open/closed. A subclass's refund() throws UnsupportedOperationException breaks L, Liskov substitution. A printer class must implement scan() and fax() it never uses breaks I, interface segregation. A service calls new MySqlOrderDao() inside its methods breaks D, dependency inversion.

S, O, L, I, D: each violation now names the principle that fixes it.

Takeaway: Each letter has a typical smell: a class with many jobs, a growing switch, a subtype that refuses, a fat interface, and new on a concrete dependency.

The question each SOLID letter asksS asks whether a class has one reason to change. O asks whether new behavior can be added without edits. L asks whether a subtype can replace its parent. I asks whether clients use the whole interface. D asks whether the code depends on abstractions.SOne reason tochange?OAdd without editing?LSubtype can replaceparent?IClient uses all of it?DDepends onabstractions?
The question each SOLID letter asksS asks whether a class has one reason to change. O asks whether new behavior can be added without edits. L asks whether a subtype can replace its parent. I asks whether clients use the whole interface. D asks whether the code depends on abstractions.SOne reason tochange?OAdd without editing?LSubtype can replaceparent?IClient uses all of it?DDepends onabstractions?
The question each letter asks

In code

interface Discount { Money apply(Money price); }
interface OrderRepository { void save(Order order); }
interface Notifier { void send(Order order); }

class OrderService {
    private final OrderRepository repository;
    private final Notifier notifier;

    OrderService(OrderRepository repository, Notifier notifier) {
        this.repository = repository;
        this.notifier = notifier;
    }

    void place(Order order, Discount discount) {
        order.setTotal(discount.apply(order.subtotal()));
        repository.save(order);
        notifier.send(order);
    }
}
After SOLID: OrderService coordinates, the details are injected
OrderService depends on interfacesOrderService uses the OrderRepository and Notifier interfaces. MySqlOrderDao implements OrderRepository, and EmailNotifier implements Notifier, so the service never names a database or a mail client.«interface»OrderRepository«interface»NotifierOrderServiceMySqlOrderDaoEmailNotifier
OrderService depends on interfacesOrderService uses the OrderRepository and Notifier interfaces. MySqlOrderDao implements OrderRepository, and EmailNotifier implements Notifier, so the service never names a database or a mail client.«interface»OrderRepository«interface»NotifierOrderServiceMySqlOrderDaoEmailNotifier
OrderService depends on interfaces, and the details implement them
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; }
 Wrong     @Override void setHeight(int h) { this.w = h; this.h = h; }   // the caller's width is lost
}

Rectangle r = new Square();
r.setWidth(5);
r.setHeight(4);
int area = r.area();   // 16, but code written for Rectangle expects 20
Liskov: a Square that breaks the Rectangle's promise
 Wrong interface Machine { void print(Doc d); void scan(Doc d); void fax(Doc d); }   // a printer must stub fax()

 Right interface Printer { void print(Doc d); }
 Right interface DocScanner { void scan(Doc d); }

class BasicPrinter implements Printer { public void print(Doc d) { /* send to tray */ } }
class OfficeMachine implements Printer, DocScanner {
    public void print(Doc d) { /* ... */ }
    public void scan(Doc d) { /* ... */ }
}
Interface segregation: each client sees only what it calls

Solve it

Which principles does this report job break, and how do you fix it?

DailyReportJob.run() queries MySQL with JDBC (Java Database Connectivity), builds an HTML table and sends it through an SMTP (Simple Mail Transfer Protocol) client it creates with new. The finance team wants a PDF next quarter, and nobody can test the job without a database and a mail server.

  1. List the reasons to change. The SQL schema, the HTML layout and the mail provider each change for a different team. Three reasons in one class break the Single Responsibility Principle.
  2. Split by reason. ReportRepository loads rows, ReportFormatter renders them and ReportSender delivers the result. The job only coordinates.
  3. Invert the dependencies. new SmtpClient() inside the job ties policy to a detail. The job receives the three interfaces in its constructor (Dependency Inversion).
  4. Check with the change request. PDF is a new ReportFormatter and the job is untouched (Open/Closed). A test passes in-memory fakes, with no database or mail server.
interface ReportRepository { List<Row> rowsFor(LocalDate day); }
interface ReportFormatter { byte[] format(List<Row> rows); }
interface ReportSender { void send(byte[] report); }

class DailyReportJob {
    private final ReportRepository repository;
    private final ReportFormatter formatter;
    private final ReportSender sender;

    DailyReportJob(ReportRepository repository, ReportFormatter formatter, ReportSender sender) {
        this.repository = repository;
        this.formatter = formatter;
        this.sender = sender;
    }

    void run(LocalDate day) { sender.send(formatter.format(repository.rowsFor(day))); }
}
// new DailyReportJob(new JdbcReportRepository(ds), new PdfReportFormatter(), new SmtpReportSender(mail))
The job coordinates; each detail sits behind an interface

How to answer

  • Single responsibility: a class has one reason to change.
  • Open/closed: add behavior with new code, not by editing working code.
  • Liskov substitution: a subtype must work anywhere its parent is expected.
  • Interface segregation: clients depend only on the methods they use.
  • Dependency inversion: high-level code depends on abstractions, and details are injected.
  • Give a concrete violation and its fix for each letter.

Common mistakes

  • Reciting the five names without an example; interviewers ask for a violation next.
  • Confusing dependency inversion with dependency injection; injection is one way to achieve inversion.

Follow-up questions

How do you spot a class that breaks the single responsibility principle?

Ask who would request a change. If pricing rules, the database and email templates all lead to edits in one class, it has three reasons to change. Other signs are many unrelated dependencies, a vague name like OrderManager, and tests that must mock everything.

  • Count the reasons to change, not the methods.
  • Many unrelated fields and imports are a warning sign.
  • Split along the reasons, then let one class coordinate.

See it in the infographic: Refactoring OrderService one letter at a time

How would you remove a switch on discount type to follow the open/closed principle?

Turn each case into a class implementing a Discount interface, and let the caller hold a Discount. A new discount type becomes a new class; the code that applies discounts never changes.

  • Each case becomes a class behind one interface.
  • New behavior is added, not edited in.
  • A map or a factory chooses the class in one place.
interface Discount { Money apply(Money price); }
class Seasonal implements Discount {
    public Money apply(Money price) { return price.times(0.9); }
}
Money total = discount.apply(price); // no switch

See it in the infographic: Refactoring OrderService one letter at a time

Why is Square extending Rectangle a classic Liskov substitution violation?

Rectangle promises that setWidth leaves the height alone. A Square must keep its sides equal, so its setWidth changes the height too. Code written for Rectangle that sets width 5 and height 4 and expects area 20 gets 16 from a Square.

  • Liskov is about behavior, not about whether "is a" sounds right.
  • A subtype cannot weaken the promises of its parent.
  • Fix: do not inherit, or use immutable shapes without setters.

See it in the infographic: Match each violation to SOLID

What is the difference between interface segregation and single responsibility?

Single responsibility is about a class: it should have one reason to change. Interface segregation is about what clients see: an interface should not force a client to depend on methods it does not use. A class can implement several small interfaces and still have one responsibility.

  • Single responsibility looks at the implementation.
  • Interface segregation looks at each client's needs.
  • Split fat interfaces by client.

See it in the infographic: Match each violation to SOLID

Is dependency inversion the same as dependency injection?

No. Dependency inversion is a design rule: high-level code depends on an abstraction it owns, like OrderRepository, and the low-level detail implements it. Dependency injection is a technique: dependencies are passed in instead of created with new. Injection is the usual way to wire inverted dependencies.

  • Inversion decides who owns the interface.
  • Injection decides how an object receives its dependencies.
  • Injecting a concrete class is injection without inversion.

See it in the infographic: Refactoring OrderService one letter at a time

When is a switch statement fine?

When the cases are few and stable, or when the switch lives in one factory that turns input into objects. Open/closed matters where new cases keep arriving and the same switch is copied around.

Can you overdo SOLID?

Yes. An interface for every class and a class for every method add indirection without benefit. Apply a principle when a real change is hurting, not in advance.

How does Spring help with dependency inversion?

Classes declare constructor parameters typed as interfaces, and the container injects the implementation. The service never calls new on its dependencies, so tests can pass fakes.

Check yourself

1. A subclass's refund() throws UnsupportedOperationException. Which principle does it break?
Show answers
  • Liskov substitution: Correct. Code that calls refund() on the parent type breaks when it gets this subtype.
  • Interface segregation: Incorrect. The problem is a subtype breaking a promise, not an interface too wide for its clients.
  • Single responsibility: Incorrect. The class can have one job and still break substitution.
2. OrderService calls new MySqlOrderDao() inside its methods. Which change follows dependency inversion?
Show answers
  • Take an OrderRepository interface in the constructor: Correct. The service depends on an abstraction, and the database class is injected.
  • Make MySqlOrderDao a static singleton: Incorrect. The service still names the concrete database class.
  • Move the new call into a private method: Incorrect. The dependency is hidden but still concrete.
3. A class follows the single responsibility principle. Which pair of change requests could both land in it?
Show answers
  • A new tax rule and a rounding change: Correct. Both are pricing rules, one reason to change.
  • A new tax rule and a new email template: Incorrect. Pricing and messaging are two different reasons to change.
  • A new database and a new email template: Incorrect. Storage and messaging change for different reasons.