IAE Academy

FOR CORE AND IT JOBS · CHAPTER 7 OF 7

Design principles and patterns

Some Java classes are easy to change; others break when touched. Cohesion, coupling, SOLID, four patterns, refactoring and unit tests show why, so you can change working code safely.

Updated 30 Oct 2026

What you will be able to do

You will judge a class by its focus and its dependencies. You will spot and fix a broken SOLID principle. You will write Singleton, Factory, Strategy and Observer and say when each helps. You will split a long method and test a class.

Before you start

  1. Chapter 1, Classes and objects in Java

  2. Chapter 2, Encapsulation and immutability

  3. Chapter 3, Inheritance

  4. Chapter 4, Polymorphism, abstract classes and interfaces

  5. Chapter 5, Exceptions

  6. Chapter 6, Collections and generics

  7. Ratios and fractions

Cohesion, coupling and the SOLID principles

A class is cohesive when its methods work on the same fields, so it does one job. It is coupled to each class it names: a change there can break it. Aim for high cohesion, low coupling. All code here is Java 17: classes in PascalCase, methods and fields in camelCase.

COHESION RATIO

For , ; a rough measure from 0 to 1, no unit. , = numbers of methods and fields; = number of (method, field) pairs where the method reads or writes the field. A low value suggests several jobs in one class.

COUPLING COUNT

Counts the concrete classes of your own program, other than , that names: as a type, after new, or in a static call. Interfaces (many classes can stand behind one) and Java's own classes such as String do not count.

WORKED EXAMPLE

Invoice has fields items and printerName. addItem and total use items, print uses both, connectPrinter uses printerName. Find , split the class, and find again.

Solution
  1. Count the pairs, because is the number of (method, field) uses: addItem 1, total 1, print 2, connectPrinter 1, so .

  2. Here and , so and .

  3. Only print uses both fields, and it needs printerName just to reach the printer, so the class does two jobs: keeping items and driving a printer.

  4. Split into Invoice (items; addItem, total) and Printer (printerName; connectPrinter, and print(String text), which is given the text instead of reading items).

  5. Invoice: , , , so . Printer: both methods use printerName, so again , , and .

Answer: The class scores 0.625, and the two classes after the split each score 1.

S, single responsibility. A class should have one reason to change. Broken: Report builds text and writes the file, so a format change and a storage change both edit it.

class Report {
    String build(int total) { return "Total " + total; }
    void save(String text) { /* writes text to r.txt */ }
}

Fix: keep build in Report and move save, unchanged, into a new class ReportStore.

SINGLE RESPONSIBILITY

is a class. A reason to change is a separate decision that would force an edit to , such as the text format or where files go.

O, open for extension, closed for modification. Broken: each new shape edits old, working code.

class Geometry {
    double area(String kind, double x) {
        return kind.equals("square") ? x * x : Math.PI * x * x; // a triangle edits this line
    }
}

Fix: one interface and one class per shape (a record is a short class whose fixed fields are set by its constructor).

interface Shape { double area(); }
record Square(double side) implements Shape { public double area() { return side * side; } }
record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }

OPEN AND CLOSED

Holds when callers use the interface Shape and never test the kind themselves.

L, Liskov substitution. A subclass must work wherever its parent is used. Broken: Penguin extends Bird but fly throws, so a loop calling fly on each bird crashes.

class Bird { void fly() { System.out.println("flying"); } }
class Penguin extends Bird {
    @Override void fly() { throw new UnsupportedOperationException(); }
}

Fix: take fly out of Bird into interface Flyer { void fly(); }, which only flying birds implement. Penguin extends Bird and has no fly. Below, pre is what a method needs from its caller, post what it promises, and means " implies ".

SUBSTITUTION RULE

For each overridden method: the child accepts at least what the parent accepts and promises at least as much. Bird.fly promises to return normally; a fly that always throws breaks the second rule.

I, interface segregation. No class should have to write methods it does not use. Broken: interface Worker { void work(); void eat(); } forces a Robot to write an empty public void eat() { }. Fix: split it into interface Workable { void work(); } and interface Eatable { void eat(); }; Robot implements only Workable.

D, dependency inversion. Depend on interfaces, not concrete classes. Broken: Notifier builds its own helper.

class Notifier {
    private final SmsSender sender = new SmsSender();
}

Fix: receive it through the constructor as an interface.

interface Sender { void send(String m); }
class Notifier {
    private final Sender sender;
    Notifier(Sender sender) { this.sender = sender; }
    void alert(String m) { sender.send(m); }
}

DEPENDENCY INVERSION

An arrow points from a class to the interface it uses or implements. Both point at Sender, so falls from 1 to 0.

Three patterns and Observer

A pattern is a named fix for a recurring problem. Singleton keeps exactly one instance. A thread is one line of execution, and a program can run several at once. This lazy version is not thread-safe: a second thread can run between the test and the assignment.

class Config {
    private static Config instance;
    private Config() {}
    static Config get() {
        if (instance == null) instance = new Config(); // check, then act
        return instance;
    }
}

Fix: write static synchronized Config get(). The keyword synchronized lets only one thread at a time run get(), so the test and the assignment act as one step.

WORKED EXAMPLE

Two threads T1 and T2 call the lazy Config.get() for the first time, with instance null. Show how two objects get built.

Solution
  1. T1 runs the test: instance is null, so it enters the if. It is paused before the assignment.

  2. T2 runs the test: instance is still null, because T1 has not assigned yet, so T2 also enters the if.

  3. T2 builds object A, stores it and returns A. T1 resumes, builds object B, overwrites instance and returns B.

  4. The two callers now hold different objects, so the class is no longer a singleton. With synchronized, T2 waits until T1 has stored its object, then finds instance not null and returns it.

Answer: Check-then-act is two steps, so two objects can exist. The synchronized version builds one.

Factory puts the choice of class in one place: callers name the interface and the factory, not the classes it builds. Strategy passes behaviour in as an object, so the behaviour changes without editing the class that uses it: the Sender handed to the fixed Notifier is one, and so is a Comparator (Chapter 6).

class SmsSender implements Sender { public void send(String m) { System.out.println("SMS: " + m); } }
class EmailSender implements Sender { public void send(String m) { System.out.println("Mail: " + m); } }
class SenderFactory {
    static Sender create(String kind) {
        return switch (kind) {
            case "sms" -> new SmsSender();
            case "email" -> new EmailSender();
            default -> throw new IllegalArgumentException(kind);
        };
    }
}
// new Notifier(SenderFactory.create("email")).alert("hi"); prints Mail: hi

Observer lets one object tell many others that it changed without knowing who they are: it keeps a list of listeners (objects that want to hear of a change) and calls each. v -> ... is a lambda: a short way to write an object of a one-method interface.

interface Listener { void onChange(int v); }
class Sensor {
    private final java.util.List<Listener> ls = new java.util.ArrayList<>();
    void subscribe(Listener l) { ls.add(l); }
    void set(int v) { for (Listener l : ls) l.onChange(v); }
}
// Sensor s = new Sensor(); s.subscribe(v -> System.out.println("got " + v)); s.set(7); prints got 7

Pattern

Helps when

Singleton

Exactly one shared object is needed

Factory

The class to build depends on input

Strategy

Several algorithms can swap in

Observer

Many parts react to one change

WATCH OUT FOR

Factory and Strategy look alike: both work through an interface. Test: Factory decides which object to create; Strategy decides which behaviour to run.

Refactoring and unit testing

Refactoring changes the structure of code without changing what it does. A common first step: cut a long method into small, named ones, rerunning the tests after each step. Before, total held the summing loop and the tax in one body, ending return s + s * rate;. After:

import java.util.List;

class Billing {
    double total(List<Double> prices, double rate) {
        double s = sum(prices);
        return s + tax(s, rate);
    }
    private double sum(List<Double> prices) {
        double s = 0;
        for (double p : prices) s += p;
        return s;
    }
    private double tax(double s, double rate) { return s * rate; }
}

A unit test runs one small piece of code and checks the result: arrange, act, assert. This outline uses JUnit 5: @Test labels a method for JUnit to run. BillingTest sits in Billing's package (a named group of classes), so it can call total, which has default access.

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class BillingTest {
    @Test
    void totalAddsTax() {
        Billing b = new Billing(); // arrange
        double t = b.total(java.util.List.of(10.0, 30.0), 0.5); // act: 40 + 20
        assertEquals(60.0, t, 1e-9); // assert: passes
    }
}

Passing before and after shows the refactoring kept this result. assertThrows checks that a method throws (Chapter 5).

Check yourself

CHECK YOURSELF 1

A class has 3 methods and 4 fields. The methods use 2, 1 and 1 of the fields. Find its cohesion ratio to two decimal places.

Answer and solution

Answer: (accepted range )

  1. .

  2. .

  3. , which is 0.33.

CHECK YOURSELF 2

Penguin extends Bird, and Penguin.fly() always throws UnsupportedOperationException. Which principle does this break?

  1. (A)

    Single responsibility

  2. (B)

    Open for extension, closed for modification

  3. (C)

    Liskov substitution

  4. (D)

    Dependency inversion

Answer and solution

Answer: (C)

  1. Code that works with any Bird calls fly and now crashes for a Penguin.

  2. The child does not keep the parent's promise, so it cannot replace the parent.

  3. That is Liskov substitution.

CHECK YOURSELF 3One or more options are correct

Which statements about the lazy Config.get() shown earlier are true? Select all that apply.

  1. (A)

    A second thread can pass the null test before the first assigns

  2. (B)

    Declaring it static synchronized makes it build one object

  3. (C)

    The private constructor stops two threads from building two objects

  4. (D)

    Static fields are copied for each thread

Answer and solution

Answer: (A), (B)

  1. A is true: check-then-act is two steps, so both threads can see instance as null.

  2. B is true: synchronized lets one thread at a time run get(), so the second finds the stored object.

  3. C is false: the private constructor only stops other classes calling new; get() itself calls it twice.

  4. D is false: one static field is shared by all threads.

CHECK YOURSELF 4

Alert names five concrete classes of its own program: SmsSender, EmailSender, FileLogger, OrderDatabase and Scheduler. It now takes a Sender and a Logger (both interfaces) in its constructor and no longer names the first three. Find .

Answer and solution

Answer:

  1. Before the change .

  2. Sender and Logger are interfaces, which do not count, and the three concrete classes they replace are no longer named.

  3. OrderDatabase and Scheduler remain, so .