Skip to content
Tutorials Center
My learning

Topics

Lesson 158 of 201 ยท JVM and Advanced Topics

Object-Oriented Design Principles (SOLID)

Learn the SOLID principles in Java - single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion - with runnable before/after code.

Code that works today still has to survive tomorrow's change requests: a new payment method, a second database, a different report format. Whether that change takes ten minutes or two days depends mostly on design: how responsibilities are split between classes and how tightly those classes depend on each other. SOLID is an acronym for five principles, collected and named by Robert C. Martin in the early 2000s, that push code toward designs that are easy to change:

Letter Principle In one sentence
S Single Responsibility A class should have one reason to change.
O Open/Closed Add new behavior by adding code, not by editing working code.
L Liskov Substitution A subtype must work everywhere its supertype is expected.
I Interface Segregation Don't force clients to depend on methods they don't use.
D Dependency Inversion Depend on abstractions, not on concrete details.

They're guidelines, not laws. Each section below shows a realistic "before" design, explains what goes wrong when requirements change, and then runs an "after" version. You'll need interfaces, polymorphism and composition; the design pattern lessons that follow build directly on these ideas.

S: the Single Responsibility Principle

A class should have one reason to change.

"Responsibility" doesn't mean "one method." It means one axis of change, usually one group of people who might ask for changes. Look at this class:

Java
class Invoice {
    List<Line> lines;
    String customerEmail;

    double total() { ... }                          // business rules: finance team
    String toHtml() { ... }                         // presentation: design team
    void saveToDatabase(Connection c) { ... }       // persistence: database admins
    void emailTo(String address) { ... }            // delivery: operations
}

Four different groups have reasons to edit Invoice. A change to the HTML layout means touching and retesting the class that computes money. You can't calculate a total in a unit test without pulling in JDBC and mail classes. And two developers working on unrelated features end up editing the same file.

The fix is to split along those axes. The data and its rules stay together; formatting, storage and delivery become separate classes that use the invoice:

Java SRP: one class per reason to change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Now each class is small and testable on its own: Invoice.total() needs no database, and a new formatter is a new class that can't break the tax rule. A useful smell test: if describing a class needs the word "and" ("it calculates totals and formats and saves"), it probably has more than one responsibility. Don't overdo it, though. Splitting every method into its own class creates a different problem: logic scattered across dozens of tiny files. Group what changes together; separate what changes for different reasons.

O: the Open/Closed Principle

Software entities should be open for extension but closed for modification.

You should be able to add a new kind of behavior without editing code that already works and is tested. The classic violation is a growing chain of type checks:

Java
double shippingCost(Order order) {
    switch (order.shippingMethod()) {
        case "standard": return 4.99;
        case "express":  return order.weightKg() * 2.0 + 9.99;
        case "pickup":   return 0;
        // Next month: "drone", then "locker", then "international"...
        default: throw new IllegalArgumentException("unknown method");
    }
}

Every new method edits this function, and such switch statements tend to be copied into several places (cost, delivery estimate, label printing). Miss one copy and you ship a bug. The open/closed fix is to make each variation a separate implementation of one interface. Adding a method then means adding a class:

Java OCP: new shipping methods without editing old code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

printOptions will never need to change for a new shipping method. That's polymorphism doing what it's best at.

When a switch is the better choice

The open/closed principle favors one direction of change: adding new types is easy, but adding a new operation (say, carbonFootprint) means editing every implementation. When the set of types is fixed and known, and you add operations more often than types, modern Java offers the opposite trade-off: a sealed hierarchy plus an exhaustive pattern-matching switch.

Java
sealed interface Payment permits Card, BankTransfer, Voucher {}

static double fee(Payment payment) {
    return switch (payment) {            // no default: the compiler checks every case
        case Card c         -> c.amount() * 0.029;
        case BankTransfer b -> 0.50;
        case Voucher v      -> 0;
    };
}

If someone adds a fourth Payment type, every such switch stops compiling until it handles the new case, so nothing is forgotten silently. Choose interfaces with polymorphism when new variants arrive often (plugins, strategies, providers), and sealed types with switch for closed domain models (shapes, payment kinds, AST nodes).

L: the Liskov Substitution Principle

If S is a subtype of T, code that works with a T must keep working when given an S.

Barbara Liskov stated this in 1987. It's about behavior, not just method signatures. The compiler happily accepts any subclass, but a subclass that changes what its parent promised breaks code that relied on that promise. A subtype must not:

  • demand more from callers (stronger preconditions: rejecting inputs the parent accepted),
  • promise less (weaker postconditions: returning something the parent's contract ruled out),
  • break invariants the parent guarantees, or throw new kinds of exceptions callers can't expect.

Here's a violation that looks perfectly reasonable when you write it:

Java LSP: a subclass that breaks its parent's promise

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

payRent did everything right according to Account's contract, and still crashed. The bug is not in payRent; it's in the hierarchy. "Is-a" in the real world ("a deposit is a kind of account") doesn't guarantee "is substitutable for" in code. The fix is to model what each type can actually do:

Java
interface Account { String id(); double balance(); }
interface Withdrawable extends Account { void withdraw(double amount); }

final class CheckingAccount implements Withdrawable { ... }
final class FixedTermDeposit implements Account { ... }   // no withdraw method at all

static void payRent(List<? extends Withdrawable> accounts, double rent) { ... }

Now the mistake is impossible: a FixedTermDeposit can't even be passed to payRent. Typical warning signs of an LSP violation are overrides that throw UnsupportedOperationException, overrides that do nothing, and callers that check instanceof to avoid a particular subclass.

The JDK has a famous trade-off here: List.of(...) returns a List whose add throws UnsupportedOperationException. The List interface documents add as an optional operation, so this is technically within the contract, but it's exactly the kind of surprise LSP warns about, and why you need to know which lists are modifiable (see Immutable Collections).

I: the Interface Segregation Principle

Clients should not be forced to depend on methods they do not use.

Big "do everything" interfaces force implementers to write dummy methods and couple every client to every method:

Java
interface Device {
    void print(Document d);
    void scan(Document d);
    void fax(Document d, String number);
    void staple(Document d);
}

class BasicPrinter implements Device {
    public void print(Document d) { ... }
    public void scan(Document d)   { throw new UnsupportedOperationException(); }   // forced
    public void fax(Document d, String n) { throw new UnsupportedOperationException(); }
    public void staple(Document d) { throw new UnsupportedOperationException(); }
}

Notice that ISP violations cause LSP violations: the forced methods throw. The fix is several small role interfaces. A class implements the roles it really has, and each client asks only for the role it needs:

Java ISP: small role interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

printAll works with any printer, including the cheap one, and copy states precisely what it needs with an intersection bound (T extends Scanner & Printer). Small interfaces are also what make lambdas possible: Printer has one method, so printAll(d -> System.out.println(d), queue) works. The JDK's functional interfaces (Supplier, Predicate, Consumer) are interface segregation taken to its logical end.

D: the Dependency Inversion Principle

High-level modules should not depend on low-level modules. Both should depend on abstractions.

High-level code holds your business rules ("place an order, charge the customer, send a confirmation"). Low-level code holds details (a MySQL driver, an SMTP client, a payment provider's SDK). If the business class creates its details directly, it's welded to them:

Java
class CheckoutService {
    private final StripeClient payments = new StripeClient("sk_live_...");   // concrete detail
    private final SmtpMailer mailer = new SmtpMailer("smtp.example.com");     // concrete detail

    void checkout(Cart cart) { ... }
}

You can't test checkout without charging a real card, and switching payment providers means rewriting business code. Inverting the dependency means the high-level side defines the interface it needs (PaymentGateway), the details implement it, and the concrete objects are passed in from outside, usually through the constructor. That last part is dependency injection, the technique Spring automates:

Java DIP: business logic depends on interfaces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The arrow of dependency now points from the details to the abstraction: CardGateway depends on PaymentGateway, which belongs to the business layer. The business code is testable in milliseconds, and switching from email to SMS is a one-line change where the objects are wired together. You'll write tests like this properly in Unit Testing with JUnit.

DIP doesn't mean "an interface for every class." A record Money or a LocalDate needs no abstraction. Introduce interfaces at boundaries: I/O, external services, time and randomness (inject a java.time.Clock instead of calling LocalDate.now() everywhere), and anything you'd want to replace in a test.

Beyond SOLID

A few more principles show up constantly in code reviews:

  • Composition over inheritance. Inheritance couples a subclass to its parent's internals; composing objects (a class has a strategy, a repository, a formatter) is more flexible and avoids LSP traps. See Composition, Aggregation and Association.
  • DRY (Don't Repeat Yourself). Every piece of knowledge (a tax rule, a validation rule) should live in one place. Two pieces of code that merely look alike but change for different reasons are not duplication; merging them couples unrelated features.
  • KISS and YAGNI ("Keep it simple," "You aren't gonna need it"). Don't add extension points for changes that may never come. Apply OCP where change has actually happened or is clearly coming.
  • Tell, don't ask, and the Law of Demeter. Prefer order.ship() over pulling data out (order.getCustomer().getAddress().getCity()) and deciding elsewhere. Long chains of getters mean one class knows too much about others.
  • High cohesion, low coupling. The goal behind all of the above: things that belong together stay together, and connections between parts are few, narrow and explicit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A Report class computes statistics, renders them as PDF and uploads the file to cloud storage. Which principle does it most directly violate?

    Statistics, rendering and storage change for different reasons and are requested by different people, so the class has several responsibilities.
  2. 2. A subclass overrides save(Document) and throws UnsupportedOperationException because read-only documents can't be saved. Code that works with the parent type now crashes. Which principle is broken?

    The subtype can't be substituted for its parent, because it breaks the parent's promise that save works. Model read-only documents with a type that has no save method.
  3. 3. Which change best applies the Dependency Inversion Principle to a service that calls new SmtpMailer() internally?

    The service then depends on an abstraction it owns, and the concrete mailer (or a test double) is injected from outside.
  4. 4. Your domain has exactly three payment kinds that rarely change, but you often add new operations on them. What does modern Java offer that fits this well?

    With a closed set of types, sealed types plus exhaustive switches make adding operations easy, and the compiler flags every switch if a type is ever added.
  5. 5. An interface has 12 methods and most implementers throw from half of them. What's the usual fix?

    That is the Interface Segregation Principle. Default methods that throw only hide the problem, which then shows up as a Liskov violation at run time.

Summary

  • SRP: give each class one reason to change; separate business rules from presentation, persistence and delivery.
  • OCP: add new variants by adding classes behind an interface; use sealed types with exhaustive switch when the set of types is closed and operations change more often.
  • LSP: subtypes must honor the parent's contract (no stronger preconditions, weaker guarantees or surprise exceptions); throwing overrides and instanceof checks are warning signs.
  • ISP: prefer small role interfaces; clients ask only for what they use, and single-method interfaces work with lambdas.
  • DIP: business code depends on interfaces it owns, and concrete details are injected (usually through constructors), which makes code testable and replaceable.
  • Use the principles where change really happens; combine them with composition over inheritance, DRY, KISS and YAGNI.

Next: Creational Design Patterns, where you'll apply these principles to the problem of creating objects: singletons, factories, builders and prototypes.