← All lessons
Advanced Java · Lesson 9 of 9

Design and patterns

Code is read and changed far more often than it's written. Good design is whatever makes the next change easy and safe. A few ideas carry most of the weight.

Prefer immutable objects

An object that can't change after it's made is simple to reason about: it can be shared between threads with no locks, used as a map key, and passed anywhere without someone changing it behind your back. Make fields final, set them in the constructor, return new objects instead of changing old ones, and use records where they fit. When a field is a list, store an unmodifiable copy so callers can't change it through their reference:

Java
public class Main {
    record Cart(List<String> items) {
        Cart { items = List.copyOf(items); }
        Cart add(String item) {
            List<String> next = new ArrayList<>(items);
            next.add(item);
            return new Cart(next);
        }
    }

    public static void main(String[] args) {
        List<String> start = new ArrayList<>(List.of("tea"));
        Cart a = new Cart(start);
        start.add("sneaky");
        Cart b = a.add("cake");
        System.out.println(a.items() + " " + b.items());
    }
}
Prints
[tea] [tea, cake]

Composition over inheritance

Inheritance ties a subclass tightly to its superclass: change the parent and every child may break. Often it's better to compose: give the class a field holding the other object and pass work to it. You can swap the part at run time, and test it on its own. "Is a kind of" can be inheritance; "has a" or "uses a" should be a field.

Strategy

The strategy pattern is composition in action: the varying part of a job is an interface, and you pass in the version you want. With lambdas it's tiny. Here the discount rule is swappable without touching Checkout:

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

    record Checkout(Discount discount) {
        int pay(int cents) { return discount.apply(cents); }
    }

    public static void main(String[] args) {
        Discount none = c -> c;
        Discount tenOff = c -> c * 90 / 100;
        Discount fiveDollarsOver50 = c -> c >= 5000 ? c - 500 : c;
        for (Discount d : List.of(none, tenOff, fiveDollarsOver50)) {
            System.out.print(new Checkout(d).pay(6000) + " ");
        }
        System.out.println();
    }
}
Prints
6000 5400 5500 

Builder and factory

A constructor with eight parameters is hard to read: which true was which? A builder names each value as you set it and checks the whole thing once at the end. A static factory method (like List.of or Duration.ofMinutes) is a named way to make objects that can check input, pick a subclass or reuse an existing object.

Java
public class Main {
    record Email(String to, String subject, String body, boolean urgent) {
        static Builder to(String to) { return new Builder(to); }

        static class Builder {
            private final String to;
            private String subject = "(no subject)", body = "";
            private boolean urgent;
            Builder(String to) { this.to = to; }
            Builder subject(String s) { subject = s; return this; }
            Builder body(String b) { body = b; return this; }
            Builder urgent() { urgent = true; return this; }
            Email build() {
                if (!to.contains("@")) throw new IllegalStateException("bad address: " + to);
                return new Email(to, subject, body, urgent);
            }
        }
    }

    public static void main(String[] args) {
        Email e = Email.to("[email protected]").subject("Lunch?").urgent().build();
        System.out.println(e.subject() + " " + e.urgent() + " [" + e.body() + "]");
        try {
            Email.to("nobody").build();
        } catch (IllegalStateException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
Prints
Lunch? true []
bad address: nobody

Each builder method returns this, which is what lets the calls chain.

Observer

The observer pattern lets one object tell others that something happened without knowing who they are: listeners register, and the subject calls each one. It's behind button clicks, events and message queues.

Java
public class Main {
    static class Stock {
        private final List<Consumer<Integer>> listeners = new ArrayList<>();
        private int level = 10;
        void onChange(Consumer<Integer> l) { listeners.add(l); }
        void take(int n) {
            level -= n;
            for (Consumer<Integer> l : listeners) l.accept(level);
        }
    }

    public static void main(String[] args) {
        Stock pens = new Stock();
        pens.onChange(level -> System.out.println("level now " + level));
        pens.onChange(level -> { if (level < 5) System.out.println("reorder pens!"); });
        pens.take(3);
        pens.take(4);
    }
}
Prints
level now 7
level now 3
reorder pens!

The principles behind them

  • One reason to change: a class should have one job. A class that formats invoices, emails them and saves them changes for three different reasons.
  • Depend on interfaces, not concrete classes, at the boundaries: the database, the clock, the mailer. That's what makes testing and swapping possible.
  • Open to extension: adding a new discount or payment kind should mean adding code, not editing a long if chain in five places. Strategies and sealed types both help.
  • Keep it simple: a pattern is a tool for a problem you actually have. Three lines that work beat five classes "in case".

Where to go next

You now have the core of professional Java. Good next steps: build something real end to end (a command-line tool, then a small web service with a framework like Spring Boot or a lighter one), read other people's code on open-source projects, and practise problems on data structures and algorithms. The Data structures, Algorithms and SQL courses here fill in the computer science that interviews and real systems lean on.

Practice

Which is a benefit of immutable objects?

More info

Quick reference

immutablefinal fields, no setters, return new objects; List.copyOf for lists.
compositionA field holding a part (has a), instead of a subclass (is a).
strategyThe varying rule as an interface or lambda, passed in.
builderNamed, chained setters and one check in build().
static factoryA named method that makes objects: List.of, Email.to.
observerListeners register; the subject calls each one.
one reason to changeA class does one job.

Related courses