JAVA-270 · Lesson 2 of 12 · 24 min

SOLID principles

▶ Video coming soon A video version of this lesson is on the way.

Tuesday, January 18, 2028. Hamza arrives with a list. Over the weekend he counted every place in CounterApp that decides a price, and found eleven if statements that check whether a customer is a member, a graduate, a youth rider or a partner agency, scattered across four methods. Ingrid looks at the list and says that he has just discovered, on his own, why five principles became famous. She writes SOLID down the side of the whiteboard and spends the evening on one letter at a time, using CounterApp for every example.

Five principles with one goal

SOLID is an acronym for five principles of object-oriented design, collected and popularized by Robert C. Martin in the early 2000s from his own work and that of others, and named by Michael Feathers. Each principle is a rule of thumb about how to divide responsibilities and dependencies so that changes stay small. None of them is a law. Each describes a kind of trouble, and a way to avoid it, that experienced developers met again and again.

The SOLID principles
LetterPrincipleIn one sentence
SSingle responsibility principleA class should have one reason to change.
OOpen/closed principleAdd new behaviour by adding code, not by editing working code.
LLiskov substitution principleA subtype must work anywhere its supertype is expected.
IInterface segregation principleClients should not depend on methods they do not use.
DDependency inversion principleHigh-level policy should depend on abstractions, not on low-level details.
Five columns, one for each SOLID letter. Each column shows a small before sketch with a crowded box or a tangled arrow, and an after sketch with smaller boxes or an arrow pointing to an interface.
Each SOLID principle as a before-and-after sketch

S: the single responsibility principle

The single responsibility principle says a class should have one reason to change. A reason to change is a person or group who might ask for a change: Odile asking for a new price rule, Kofi asking for a new spreadsheet column, the tax authority changing a rate. If two different people can force changes to the same class for unrelated reasons, the class has two responsibilities, and a change made for one of them can break the other.

CounterApp's BookingScreen class both decides whether a repair slot is free and saves bookings to a file. The first is Tamsin's rule about the workshop; the second is a storage detail Kofi might change. Splitting them gives each its own class with its own reason to change.

Java Example · Main.java
import java.util.*;

public class Main {
    record Booking(String customer, int hour) {}

    static final class SlotRules {
        static final int OPEN = 9, LAST_START = 15, BIKES_PER_HOUR = 2;
        boolean canBook(List<Booking> existing, int hour) {
            if (hour < OPEN || hour > LAST_START) return false;
            long same = existing.stream().filter(b -> b.hour() == hour).count();
            return same < BIKES_PER_HOUR;
        }
    }

    static final class BookingFile {
        private final List<String> lines = new ArrayList<>();
        void save(Booking b) { lines.add(b.customer() + "," + b.hour()); }
        List<String> lines() { return lines; }
    }

    public static void main(String[] args) {
        SlotRules rules = new SlotRules();
        BookingFile file = new BookingFile();
        List<Booking> day = new ArrayList<>();
        for (Booking b : List.of(new Booking("Ana", 10), new Booking("Ben", 10), new Booking("Cy", 10), new Booking("Di", 16))) {
            if (rules.canBook(day, b.hour())) { day.add(b); file.save(b); }
            else System.out.println("refused: " + b.customer() + " at " + b.hour());
        }
        System.out.println("saved: " + file.lines());
    }
}
Output
refused: Cy at 10
refused: Di at 16
saved: [Ana,10, Ben,10]

What this code does

SlotRules holds Tamsin's workshop rules, opening hours and two bikes an hour, and nothing else. BookingFile only knows how to store a booking as a line of text. When Tamsin changes the hours or Kofi changes the file format, only one of the two classes needs to change, and the other cannot be broken by accident.

The principle is easy to overdo. Splitting every method into its own class does not make a design better; it scatters a single responsibility across many places. The test is the reasons to change, not the number of methods. A Money record with plus, minus and toString has one reason to change, the way the shop represents money, even though it has several methods.

O: the open/closed principle

The open/closed principle, first stated by Bertrand Meyer in 1988, says a module should be open for extension and closed for modification. In practice it means arranging code so that the most likely kind of new requirement can be met by adding a new class, rather than by editing a long method that already works and is already tested.

CounterApp's eleven if statements for discounts are the opposite. Every new kind of discount means opening the price method and adding another branch, with the risk of breaking the branches already there. Ingrid shows Hamza how to turn each discount into its own small class behind one interface, so the price calculation just applies whatever discounts it is given.

Java Example · Main.java
import java.util.*;

public class Main {
    interface Discount {
        int apply(int cents);
        String name();
    }

    record PercentOff(String name, int inHundred) implements Discount {
        public int apply(int cents) { return cents - cents * inHundred / 100; }
    }

    record AmountOff(String name, int off) implements Discount {
        public int apply(int cents) { return Math.max(0, cents - off); }
    }

    static int price(int cents, List<Discount> discounts) {
        for (Discount d : discounts) {
            cents = d.apply(cents);
            System.out.println("  after " + d.name() + ": " + cents);
        }
        return cents;
    }

    public static void main(String[] args) {
        List<Discount> graduate = List.of(new PercentOff("graduate", 10));
        List<Discount> partner = List.of(new PercentOff("partner agency", 20), new AmountOff("winter coupon", 500));
        System.out.println("graduate tune-up: " + price(6500, graduate));
        System.out.println("partner tune-up: " + price(6500, partner));
    }
}
Output
  after graduate: 5850
graduate tune-up: 5850
  after partner agency: 5200
  after winter coupon: 4700
partner tune-up: 4700

What this code does

Each kind of discount is a small record that implements the Discount interface, and price simply applies a list of them in order. Adding a new kind, such as a youth rate, means writing one new class; the price method and the existing discounts are not touched. The method is closed for modification but open for extension.

The open/closed principle cannot be applied to every possible change; no design is open to everything. You choose the axes along which change is likely. At Second Gear, new discounts and new kinds of bike arrive every year, so those are worth making extensible. The number of days in a week is not.

L: the Liskov substitution principle

The Liskov substitution principle, from Barbara Liskov's 1987 keynote on data abstraction, says that if code works with a type, it must also work with any subtype of that type, without knowing which subtype it has. A subclass may add behaviour, but it must not break the promises the parent class makes: it must accept the same inputs, produce results the caller can rely on, and not throw exceptions the caller was never told to expect.

In 2027 Hamza added a DemoBike class to CounterApp for the shop's display bike, which is never rented. He made it extend RentalBike, because it has a size and a type, and overrode rent to throw an exception. The first time the end-of-month report looped over all the bikes and rented each one for a price estimate, the report crashed.

Java Example · Main.java
import java.util.*;

public class Main {
    static class RentalBike {
        final String name;
        RentalBike(String name) { this.name = name; }
        int rent(int days) { return days * 2500; }
    }

    static class DemoBike extends RentalBike {
        DemoBike(String name) { super(name); }
        @Override int rent(int days) { throw new UnsupportedOperationException(name + " is for display only"); }
    }

    public static void main(String[] args) {
        List<RentalBike> fleet = List.of(new RentalBike("CITY-1"), new DemoBike("DEMO"), new RentalBike("CITY-2"));
        for (RentalBike b : fleet) {
            System.out.println(b.name + " for 3 days: " + b.rent(3));
        }
    }
}

What this code does

DemoBike extends RentalBike but refuses to do the one thing a RentalBike promises, so the loop over the fleet stops with an exception halfway through. Code that was correct for every RentalBike becomes wrong when a subclass is substituted. That broken substitution is what the Liskov principle warns against.

Running it
$ javac Main.java
$ java Main
CITY-1 for 3 days: 7500
Exception in thread "main" java.lang.UnsupportedOperationException: DEMO is for display only
	at Main$DemoBike.rent(Main.java:12)
	at Main.main(Main.java:18)

The fix is not to add instanceof checks to every loop. It is to admit that a display bike is not a rental bike. Both can share what they really have in common, a name and a size, through an interface or a common parent, while only real rental bikes have a rent method. Then the compiler stops anyone from renting the display bike.

Java Example · Main.java
import java.util.*;

public class Main {
    interface Bike { String name(); }
    record RentalBike(String name, int perDay) implements Bike {
        int rent(int days) { return days * perDay; }
    }
    record DisplayBike(String name) implements Bike {}

    public static void main(String[] args) {
        List<Bike> all = List.of(new RentalBike("CITY-1", 2500), new DisplayBike("DEMO"), new RentalBike("CARGO-1", 4000));
        List<RentalBike> fleet = all.stream().filter(b -> b instanceof RentalBike).map(b -> (RentalBike) b).toList();

        System.out.println("bikes in the shop: " + all.size());
        for (RentalBike r : fleet) System.out.println(r.name() + " for 3 days: " + r.rent(3));
    }
}
Output
bikes in the shop: 3
CITY-1 for 3 days: 7500
CARGO-1 for 3 days: 12000

What this code does

Both kinds of bike implement Bike, which promises only a name, and only RentalBike has a rent method. The report works on the list of rental bikes, so it can never call rent on the display bike, and every element it handles keeps every promise its type makes. The type hierarchy now matches what the bikes can really do.

A good warning sign of a Liskov violation is a subclass method that throws UnsupportedOperationException, does nothing, or demands stricter inputs than its parent. Another is calling code that has to ask which subclass it has before calling a method. Both mean the inheritance is claiming something that is not true.

I: the interface segregation principle

The interface segregation principle says no client should be forced to depend on methods it does not use. A large interface that bundles many unrelated operations forces every class that implements it to provide all of them, and every class that uses it to depend on all of them, even if it needs one. Many small, focused interfaces are better than one big general one.

CounterApp had an interface called CounterDevice with methods to print receipts, scan barcodes, open the cash drawer and charge a card. The label printer in the parts room implemented it too, with three empty methods and one that printed. Splitting the interface by what clients actually need removes the fake methods.

Java Example · Main.java
public class Main {
    interface Printer { void print(String text); }
    interface Scanner { String scan(); }
    interface CardReader { boolean charge(int cents); }

    static final class CounterTerminal implements Printer, Scanner, CardReader {
        public void print(String text) { System.out.println("[counter] " + text); }
        public String scan() { return "TUBE-700x25"; }
        public boolean charge(int cents) { return cents > 0; }
    }

    static final class LabelPrinter implements Printer {
        public void print(String text) { System.out.println("[label] " + text); }
    }

    static void printShelfLabel(Printer p, String code) { p.print("SHELF " + code); }

    public static void main(String[] args) {
        CounterTerminal counter = new CounterTerminal();
        printShelfLabel(new LabelPrinter(), "BELL");
        printShelfLabel(counter, counter.scan());
        System.out.println("card ok: " + counter.charge(899));
    }
}
Output
[label] SHELF BELL
[counter] SHELF TUBE-700x25
card ok: true

What this code does

Three small interfaces replace one large one, and each device implements only what it can really do. The shelf-label method asks only for a Printer, so it works with both the label printer and the counter terminal. Nothing has to implement a method with an empty body just to satisfy an interface.

D: the dependency inversion principle

The dependency inversion principle has two parts. High-level modules, the ones that hold business policy, should not depend on low-level modules that deal with details such as files, databases and devices; both should depend on abstractions. And the abstractions should be designed for the needs of the high-level policy, not shaped after the details. The word inversion refers to the direction of the arrow: in a naive design, the booking policy calls the file code directly, so policy depends on detail. With an interface owned by the policy side, the file code implements an interface that belongs to the policy, so the detail depends on the policy.

Java Example · Main.java
import java.util.*;

public class Main {
    interface BookingStore {
        int countAt(int hour);
        void add(String customer, int hour);
    }

    static final class BookingService {
        private final BookingStore store;
        BookingService(BookingStore store) { this.store = store; }
        String book(String customer, int hour) {
            if (store.countAt(hour) >= 2) return customer + ": " + hour + ":00 is full";
            store.add(customer, hour);
            return customer + ": booked for " + hour + ":00";
        }
    }

    static final class MemoryStore implements BookingStore {
        private final Map<Integer, List<String>> byHour = new TreeMap<>();
        public int countAt(int hour) { return byHour.getOrDefault(hour, List.of()).size(); }
        public void add(String customer, int hour) { byHour.computeIfAbsent(hour, h -> new ArrayList<>()).add(customer); }
        public String toString() { return byHour.toString(); }
    }

    public static void main(String[] args) {
        MemoryStore store = new MemoryStore();
        BookingService service = new BookingService(store);
        for (String c : List.of("Ana", "Ben", "Cy")) System.out.println(service.book(c, 11));
        System.out.println(store);
    }
}
Output
Ana: booked for 11:00
Ben: booked for 11:00
Cy: 11:00 is full
{11=[Ana, Ben]}

What this code does

BookingService holds the policy, two bikes an hour, and depends only on the BookingStore interface, which is written in the terms the policy needs. MemoryStore is one detail that implements that interface, and a file or database store could be another without any change to the service. The arrow now points from the detail toward the policy's abstraction.

Dependency inversion is the principle behind most of the architecture in lessons 7 and 8. It is also the principle that makes testing easy, because a test can hand the service a fake store with exactly the data the test needs.

Using the principles well

The principles overlap and support each other. Splitting responsibilities (S) usually produces the small interfaces (I) that let you inject dependencies (D), and those interfaces are the extension points (O) whose implementations must keep their promises (L). They are guides for when code hurts, not a checklist to apply before writing anything. Ingrid's advice is to write the simple version first, notice where changes are painful, and then apply the principle that removes that pain.

SOLID applied to CounterApp
Symptom in CounterAppPrincipleFix
One class changes for prices, files and receiptsSSplit into classes with one reason to change each
Every new discount means editing the price methodOA Discount interface with one class per kind
A subclass throws when a parent method is calledLFix the hierarchy so each type keeps its promises
Devices implement methods they cannot performISeveral small interfaces
Booking rules call file code directlyDAn interface owned by the rules, implemented by storage

Try it yourself

Add a discount without editing price

The starter has the Discount interface and a PercentOff record. Add a new record YouthRate implements Discount that takes off 1500 cents but never goes below 1000 cents, and use it for the youth tune-up. Do not change the price method.

The program should print youth tune-up: 5000 and youth flat fix: 1000.

import java.util.*;

public class Main {
    interface Discount { int apply(int cents); }
    record PercentOff(int inHundred) implements Discount {
        public int apply(int cents) { return cents - cents * inHundred / 100; }
    }

    static int price(int cents, List<Discount> ds) {
        for (Discount d : ds) cents = d.apply(cents);
        return cents;
    }

    public static void main(String[] args) {
        System.out.println("youth tune-up: " + price(6500, List.of(new PercentOff(0))));
        System.out.println("youth flat fix: " + price(1800, List.of(new PercentOff(0))));
    }
}

Try it yourself

Split the fat interface

The starter's Device interface forces BellRinger to implement print and charge with empty bodies. Split Device into two interfaces, Printer with print and Ringer with ring, so BellRinger implements only Ringer and Till implements both.

The program should print [till] receipt 1, ding and ding.

public class Main {
    interface Device {
        void print(String text);
        void ring();
    }
    static final class Till implements Device {
        public void print(String text) { System.out.println("[till] " + text); }
        public void ring() { System.out.println("ding"); }
    }
    static final class BellRinger implements Device {
        public void print(String text) { }
        public void ring() { System.out.println("ding"); }
    }

    public static void main(String[] args) {
        Device till = new Till();
        Device bell = new BellRinger();
        till.print("receipt 1");
        till.ring();
    }
}

Common mistakes

  • MistakeSplitting classes until each has one method.

    InsteadSplit by reasons to change, not by method count.

  • MistakeAdding another if branch for every new kind of rule.

    InsteadPut each kind behind an interface so new kinds are new classes.

  • MistakeA subclass that throws UnsupportedOperationException for a parent method.

    InsteadFix the hierarchy; a subtype must keep every promise of its supertype.

  • MistakeOne large interface that every device must implement.

    InsteadSeveral small interfaces, each matching what one kind of client needs.

  • MistakeBusiness rules that call file or database code directly.

    InsteadDefine an interface on the rules' side and let storage implement it.

Summary and key terms

  • SOLID is five principles of object-oriented design collected by Robert C.
  • Martin.
  • The single responsibility principle says a class should have one reason to change.
  • The open/closed principle says new behaviour should be added by adding code rather than editing working code, along the axes where change is likely.
  • The Liskov substitution principle says a subtype must work anywhere its supertype is expected, without breaking its promises.
  • The interface segregation principle prefers several small interfaces to one large one.
  • The dependency inversion principle makes high-level policy and low-level details both depend on abstractions owned by the policy.
  • The principles support each other and are guides for removing pain, not a checklist.
SOLID
An acronym for five object-oriented design principles: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
Single responsibility principle
A class should have one reason to change.
Reason to change
A person or group whose requests could force a change to a class.
Open/closed principle
Software should be open for extension but closed for modification.
Extension point
A place in a design, usually an interface, where new behaviour can be plugged in.
Liskov substitution principle
Objects of a subtype must be usable wherever the supertype is expected.
Subtype
A class or interface that extends or implements another type.
Interface segregation principle
Clients should not be forced to depend on methods they do not use.
Dependency inversion principle
High-level policy and low-level details should both depend on abstractions.
High-level module
Code that holds business policy, such as booking rules.
Low-level module
Code that deals with details such as files, devices and databases.
Abstraction
An interface or abstract type that describes what is needed without saying how.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. BookingScreen decides free slots and writes the bookings file. Which principle does it break?

    Show answer

    Single responsibility: Tamsin's rules and Kofi's file format are two reasons to change.

  2. How do you add a youth rate under the open/closed principle?

    Show answer

    Write a new class implementing Discount; leave the price method alone.

  3. Why did DemoBike break the monthly report?

    Show answer

    It overrode rent to throw, so it could not be used wherever a RentalBike was expected.

  4. What should a label printer implement?

    Show answer

    Only a small Printer interface, not a large device interface with methods it cannot perform.

  5. Who owns the BookingStore interface under dependency inversion?

    Show answer

    The booking policy; storage classes implement it.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz