Reading history

SOLID Principles in Java

7 min read 0 views

Learn the five SOLID design principles in Java with clear before-and-after examples: single responsibility, open/closed, Liskov, interfaces and dependencies.

Small programs work no matter how you arrange them. Bigger programs grow, change hands and collect new features, and then design starts to matter. SOLID is a set of five design rules. They help keep classes easy to change and test. The name comes from the first letter of each rule. This lesson explains all five with plain Java examples: a shop bill, discounts, shapes and office machines. For each one you will see a “before” design, what goes wrong, and a better “after”.

In this lesson you will learn

  • Single responsibility: one reason to change
  • Open/closed: add features without editing old code
  • Liskov substitution: subclasses must keep the parent’s promises
  • Interface segregation: small, focused interfaces
  • Dependency inversion: depend on interfaces, not concrete classes

You should know interfaces and abstract classes, inheritance and design patterns.

SSingleresponsibilityone job per classOOpen/closedextend, don’t editLLiskovsubstitutionsubclass fits inIInterfacesegregationsmall interfacesDDependencyinversionuse interfaces

S, O and D: an Invoice Example

import java.util.*;

public class Main {
    // BEFORE: one class does everything (calculating, formatting, saving)
    static class InvoiceAllInOne {
        List<Double> items = new ArrayList<>();
        double total() { return items.stream().mapToDouble(Double::doubleValue).sum(); }
        String print() { return "Total: " + total(); }
        void saveToFile() { System.out.println("  (pretend) writing invoice.txt"); }
    }

    // AFTER (S): each class has one reason to change
    record Invoice(List<Double> items) {
        double total() { return items.stream().mapToDouble(Double::doubleValue).sum(); }
    }
    static class InvoicePrinter {
        String print(Invoice inv) { return String.format("Total: %.2f Tk", inv.total()); }
    }
    interface InvoiceStore { void save(Invoice inv); }          // (D) depend on an interface
    static class MemoryStore implements InvoiceStore {
        final List<Invoice> saved = new ArrayList<>();
        public void save(Invoice inv) { saved.add(inv); }
    }

    // (O) open for extension, closed for modification: add a new discount without editing old code
    interface Discount { double apply(double amount); }
    static class NoDiscount implements Discount { public double apply(double a) { return a; } }
    static class PercentOff implements Discount {
        final double pct;
        PercentOff(double pct) { this.pct = pct; }
        public double apply(double a) { return a * (1 - pct / 100); }
    }
    static class EidOffer implements Discount {                  // added later, nothing else changed
        public double apply(double a) { return a >= 2000 ? a - 300 : a; }
    }

    static class Checkout {
        private final InvoiceStore store;                       // injected, so easy to test
        Checkout(InvoiceStore store) { this.store = store; }
        double pay(Invoice inv, Discount d) {
            store.save(inv);
            return d.apply(inv.total());
        }
    }

    public static void main(String[] args) {
        InvoiceAllInOne old = new InvoiceAllInOne();
        old.items.addAll(List.of(1200.0, 950.0));
        System.out.println("Old design: " + old.print());
        old.saveToFile();

        Invoice inv = new Invoice(List.of(1200.0, 950.0));
        System.out.println("New design: " + new InvoicePrinter().print(inv));

        MemoryStore store = new MemoryStore();
        Checkout checkout = new Checkout(store);
        for (Discount d : List.of(new NoDiscount(), new PercentOff(10), new EidOffer())) {
            System.out.printf("  %-10s pays %.2f Tk%n", d.getClass().getSimpleName(), checkout.pay(inv, d));
        }
        System.out.println("Invoices saved in memory: " + store.saved.size());
    }
}

Output

Old design: Total: 2150.0
  (pretend) writing invoice.txt
New design: Total: 2150.00 Tk
  NoDiscount pays 2150.00 Tk
  PercentOff pays 1935.00 Tk
  EidOffer   pays 1850.00 Tk
Invoices saved in memory: 3
  • Single responsibility. InvoiceAllInOne adds up prices, formats text and saves a file. A change to the file format or to the print layout means editing the same class, and a mistake in one part can break the others. The new design splits it into Invoice (the data and total), InvoicePrinter (text) and InvoiceStore (saving).
  • Open/closed. Each discount is its own class that implements Discount. When the shop adds an Eid offer, we write EidOffer and nothing else changes. Compare this with a long if/else on discount names, which must be edited, and retested, every time.
  • Dependency inversion. Checkout needs somewhere to save invoices, but it asks only for an InvoiceStore. In this program we pass a MemoryStore, which is perfect for tests. A real app could pass a database store, and Checkout would not change at all.
  • Passing the store into the constructor, instead of writing new MemoryStore() inside Checkout, is called dependency injection.

L and I: Shapes and Machines

import java.util.*;

public class Main {
    // (L) Liskov: a subclass must work wherever its parent is expected.
    // A Square that extends Rectangle breaks this, so model them as separate Shapes.
    static 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; }
    }
    static class BadSquare extends Rectangle {
        @Override void setWidth(int w) { this.w = w; this.h = w; }
        @Override void setHeight(int h) { this.w = h; this.h = h; }
    }
    static int stretch(Rectangle r) {          // written for rectangles
        r.setWidth(5);
        r.setHeight(4);
        return r.area();                        // a caller expects 20
    }

    sealed interface Shape permits Rect, Square {}
    record Rect(int w, int h) implements Shape {}
    record Square(int side) implements Shape {}
    static int area(Shape s) {
        return switch (s) {
            case Rect r -> r.w() * r.h();
            case Square q -> q.side() * q.side();
        };
    }

    // (I) Interface segregation: small interfaces, so classes implement only what they need
    interface Printer { String print(String doc); }
    interface PageScanner { String scan(); }
    static class SimplePrinter implements Printer {
        public String print(String doc) { return "printed " + doc; }
    }
    static class OfficeMachine implements Printer, PageScanner {
        public String print(String doc) { return "printed " + doc; }
        public String scan() { return "scanned page"; }
    }

    public static void main(String[] args) {
        System.out.println("stretch(Rectangle) = " + stretch(new Rectangle()));
        System.out.println("stretch(BadSquare) = " + stretch(new BadSquare()) + "  <- surprise: not 20");

        for (Shape s : List.of(new Rect(5, 4), new Square(4)))
            System.out.println(s + " area = " + area(s));

        Printer p = new SimplePrinter();
        OfficeMachine m = new OfficeMachine();
        System.out.println(p.print("notice.pdf"));
        System.out.println(m.print("form.pdf") + ", " + m.scan());
    }
}

Output

stretch(Rectangle) = 20
stretch(BadSquare) = 16  <- surprise: not 20
Rect[w=5, h=4] area = 20
Square[side=4] area = 16
printed notice.pdf
printed form.pdf, scanned page
  • Liskov substitution. In maths a square is a rectangle, so BadSquare extends Rectangle seems natural. But stretch sets the width to 5 and the height to 4 and expects an area of 20. BadSquare forces both sides to be equal, so it returns 16. Code written for the parent breaks when given the child. That breaks the rule.
  • The fix is to stop pretending one is a kind of the other. Rect and Square are both Shapes, each with its own data. A sealed interface and a switch work out the area safely.
  • Interface segregation. If one big Machine interface had print, scan and fax, a simple printer would have to fake the methods it cannot do. Small interfaces let SimplePrinter implement only Printer, while OfficeMachine implements both.
PrincipleWarning signUsual fix
Single responsibilityA class name with “And” or “Manager”, many unrelated importsSplit into smaller classes
Open/closedA growing if/else or switch on a type nameAn interface with one class per case
Liskov substitutionAn override that throws “not supported” or changes the meaningRethink the inheritance; use composition
Interface segregationEmpty or fake methods in an implementationSplit the interface
Dependency inversionnew DatabaseStore() inside business logicAsk for an interface in the constructor

Common Mistakes

  1. Splitting too much. A ten-line program does not need five interfaces. Apply SOLID where change is likely.
  2. Using inheritance only to reuse code. If the child cannot keep every promise of the parent, use composition instead.
  3. Creating dependencies inside the class. It makes the class hard to test without a real database or network.
  4. One giant interface “for future use”. Add methods to interfaces only when a real class needs them.
  5. Treating SOLID as strict law. These are guidelines for judgement, not rules a compiler checks.

Practice Exercises

Exercise 1. The shop wants a “buy over 5000 Tk, get 500 Tk off” offer. Add it the open/closed way.

Show answer
static class BigSpenderOffer implements Discount {
    public double apply(double a) { return a > 5000 ? a - 500 : a; }
}
// checkout.pay(inv, new BigSpenderOffer());  no other class changes

Exercise 2. Which principle does this break, and why?

class Penguin extends Bird {
    @Override void fly() { throw new UnsupportedOperationException(); }
}
Show answer

It breaks the L rule, Liskov substitution. Code that calls bird.fly() on a list of birds will crash on a penguin. A better design keeps fly() out of Bird. Put it in its own Flyer interface, and let only birds that can fly use it. That also follows the I rule.

Frequently Asked Questions

What does SOLID stand for in Java?

SOLID is a name for five design rules: Single responsibility, Open/closed, Liskov substitution, Interface segregation and Dependency inversion. They work in any language with classes, and Java code uses them a lot.

Is dependency inversion the same as dependency injection?

They are linked, but not the same. Dependency inversion is the rule: main code should rely on interfaces. Dependency injection is one way to follow it. You pass the real object in through the constructor, instead of making it inside the class.

Summary

  • S: give each class one job and one reason to change.
  • O: add new behaviour with new classes, not edits to old ones.
  • L: a subclass must work everywhere its parent works.
  • I: prefer several small interfaces to one big one.
  • D: depend on interfaces and pass real objects in from outside.

Next: Java Command-Line Arguments and Properties.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *