Skip to content
javahacks.dev
Architecture

SOLID Principles in Java With Realistic Examples and Limits

The five SOLID principles in Java with a small order-processing example for each, the symptoms they fix and where applying them becomes overengineering.

8 min read
Summarize in AI
Flat illustration of a controller, a service and a repository stacked above a database, with the OpenJDK, Swagger and PostgreSQL logos.

SOLID is five design principles that appear in every Java interview and in far fewer codebases than the interviews suggest. They are memorable, they are useful, and applied without judgment they produce interfaces with one implementation and a class for every verb. The useful way to learn them is as five questions to ask when a design hurts, each with a concrete example of the pain it relieves and a clear statement of what it costs. This post takes each principle with realistic Java code, shows the violation and the repair and ends with an honest account of the costs and where the ideas come from. Examples use Java 25. The principles are Single responsibility, Open for extension and closed for modification, Liskov substitution, Interface segregation and Dependency inversion.

Single responsibility

A class should have one reason to change, one stakeholder whose request would cause you to edit it. The classic violation is a service that validates, calculates, persists and notifies, so that tax changes, schema changes and email changes all edit the same file. The remedy is to extract each concern into its own class and let the service coordinate. This principle has its own long treatment, with a git-history check for finding violations and the danger of splitting too far, in the Single Responsibility Principle in Java. The summary for this post: count the groups of people who ask for changes to a class, not the methods it has.

Open for extension, closed for modification

Code should let you add new behavior without editing existing code that already works. The pain it relieves is the switch on a type that grows a case every quarter, and every case forces a change to a tested method:

java
// Closed to extension: every new discount type edits this method
long discount(Order order) {
    return switch (order.customerType()) {
        case REGULAR -> 0;
        case VIP -> order.total() / 10;
        case EMPLOYEE -> order.total() / 5;
        // a new case here means editing and retesting this method
    };
}

Replace the type test with polymorphism: each case becomes an implementation of a small interface, and adding one means adding a class:

java
public interface DiscountPolicy {
    long discountFor(Order order);
}

record NoDiscount() implements DiscountPolicy {
    public long discountFor(Order o) { return 0; }
}

record PercentDiscount(int percent) implements DiscountPolicy {
    public long discountFor(Order o) { return o.total() * percent / 100; }
}
java
long total = order.total() - policies.get(order.customerType()).discountFor(order);

A new discount type is a new class registered in the map; discountFor callers are untouched. The Java 21+ alternative gives you the same safety with sealed types and pattern matching: when the set of cases is closed and known, a sealed interface plus an exhaustive switch makes the compiler tell you every place to update when a case is added, which is "closed" in a different sense and often the better trade:

java
sealed interface Shape permits Circle, Square { }
record Circle(double r) implements Shape { }
record Square(double side) implements Shape { }

double area(Shape s) {
    return switch (s) {
        case Circle c -> Math.PI * c.r() * c.r();
        case Square q -> q.side() * q.side();
    };
}

Open/closed fits when new cases come from plugins or configuration and the set is open. Sealed types fit when you own all the cases and want the compiler to find every switch. The language features are covered in the modern Java guide.

Liskov substitution

If code works with a base type, it must keep working when handed any subtype. The principle is about behavior, not about the compiler: a subclass can satisfy every signature and still break the callers' assumptions. The textbook case is the square and the rectangle:

java
class Rectangle {
    protected int width, height;
    void setWidth(int w)  { this.width = w; }
    void setHeight(int h) { this.height = h; }
    int area()            { return width * height; }
}

class Square extends Rectangle {
    @Override void setWidth(int w)  { this.width = w; this.height = w; }
    @Override void setHeight(int h) { this.width = h; this.height = h; }
}

static int resize(Rectangle r) {
    r.setWidth(5);
    r.setHeight(4);
    return r.area();           // callers expect 20
}

resize(new Rectangle()) returns 20. resize(new Square()) returns 16: setting the height changed the width too, and the caller's assumption (width and height vary independently) failed. A square is a rectangle in geometry, and not a subtype of this mutable Rectangle in behavior. The fix is to not model it as inheritance: make the shapes immutable and unrelated through a common Shape interface, so no operation can violate the other's invariant.

Realistic Java violations are less geometric. A subclass that throws UnsupportedOperationException for a method of its parent breaks the contract, as List.of(...) does for add, which is why code receiving a List may throw at runtime; see UnsupportedOperationException on immutable lists. Other signs: a subclass that tightens preconditions (rejects inputs the parent accepted), weakens postconditions (returns less than promised), or overrides a method to do nothing. The rules are stated precisely in the language's subtyping chapter (section 4.10 of the specification). Test for it by running the parent's tests against every subclass; a failure is a violation.

Interface segregation

Clients should not depend on methods they do not use. A fat interface forces every implementer to provide everything and every client to know about everything:

java
public interface OrderRepository {
    Order find(long id);
    List<Order> findByCustomer(long customerId);
    void save(Order order);
    void delete(long id);
    Report monthlyReport(YearMonth month);
    void archiveOlderThan(Instant cutoff);
}

A read-only dashboard that needs find must still depend on delete and archiveOlderThan, and a test double must implement all six. Split by the role a client plays:

java
public interface OrderReader {
    Order find(long id);
    List<Order> findByCustomer(long customerId);
}

public interface OrderWriter {
    void save(Order order);
    void delete(long id);
}

public interface OrderReporting {
    Report monthlyReport(YearMonth month);
}

An implementation can still implement all three, and each client takes only what it uses. The dashboard receives an OrderReader, so it cannot delete by accident and its fake has two methods. The Java standard library does this routinely: Iterable, Collection, List and RandomAccess split capabilities rather than putting everything on one type. Small single-method interfaces also compose with lambdas, which is how Comparator and Runnable stay usable. The caution is to split by client need, not by method count, and to stop when a split buys no client anything.

Dependency inversion

High-level policy should not depend on low-level detail; both should depend on an abstraction, and the abstraction should be owned by the high-level side. The pain is a business class that imports a mail library and cannot run in a test without sending mail:

java
// High-level code depends on a concrete low-level class
class CheckoutService {
    private final SmtpMailer mailer = new SmtpMailer("smtp.example.test", 587);

    void complete(Order o) {
        mailer.send(o.customerEmail(), "Thanks for your order");
    }
}

Invert it: the service declares what it needs, in its own words, and the infrastructure supplies it.

java
interface ReceiptSender {
    void send(String to, String message);
}

class CheckoutService {
    private final ReceiptSender receipts;

    CheckoutService(ReceiptSender receipts) {
        this.receipts = receipts;
    }

    void complete(Order o) {
        receipts.send(o.customerEmail(), "Thanks for your order");
    }
}
java
@Component
class SmtpReceiptSender implements ReceiptSender { /* uses the mail library */ }

The source dependency now points from the detail to the abstraction, and the abstraction lives with the policy. The test passes a lambda: new CheckoutService((to, msg) -> sent.add(to)). A framework such as Spring automates the supply, which is the topic of what dependency injection really is and, with the architectural consequences, of dependency inversion beyond the slogan. The common misreading is that dependency inversion means "use interfaces everywhere". It means to invert where a dependency crosses a boundary you care about, such as framework, database or network. An interface with one implementation, wrapped around a class you will never replace, is noise.

What the principles cost

Each principle has a price, and the price is indirection.

PrincipleTypical costWhen the cost is not worth it
Single responsibilityMore, smaller classesA class with one actual reason to change
Open/closedAn interface and a registry where a switch wasA closed set of cases the compiler can check
LiskovComposition instead of convenient inheritanceTypes that are never substituted
Interface segregationMore interfaces to name and maintainOne client, one implementation
Dependency inversionAn abstraction and wiringStable libraries (the JDK, a date library)

Applied everywhere, the principles yield a codebase in which every concrete class has an interface, every interface one implementation and every feature sixteen files, which is the cost with none of the benefit. The discipline is to apply a principle when you can name the pain it relieves: a class that changes for three reasons, a switch that grows every sprint, a test that needs a mail server. When you cannot name the pain, leave the code alone. The Java language tutorial on interfaces and inheritance gives the mechanics that all five depend on.

Where the principles come from

The five were collected by Robert C. Martin in the early 2000s from older work: the Liskov substitution principle is Barbara Liskov's from 1987, open/closed is Bertrand Meyer's from 1988, and the acronym was coined by Michael Feathers. They come from an era of large class hierarchies in C++ and early Java, when inheritance was the main reuse tool and compile times made change expensive. Modern Java changes the weights: records, sealed types, lambdas and pattern matching make several of the older remedies lighter, and composition is preferred to inheritance almost everywhere. Treat SOLID as a vocabulary for discussing design trade-offs with other developers, not as a checklist to pass, and keep the test that outlasts all of it: can you change the thing you need to change by editing one place, and can you test it without the world?

Also inJava Core
Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.