JAVA-270 · Lesson 1 of 12 · 25 min

What makes design good

▶ Video coming soon A video version of this lesson is on the way.

Tuesday, January 11, 2028, 5:00 pm, in the back room of Second Gear Cycles before repair night. Hamza puts his laptop on the workbench and opens a file called CounterApp.java. It is the program that runs on the shop's one counter computer, and he wrote most of it himself during the summer of 2027, between the first and second years of his program, by pasting together PartsDesk, ShopBook and the RentalDesk prices from his testing course and adding whatever Odile asked for that week. It works. It is also one class of 1,140 lines with 23 static fields, a main method of 210 lines, and a switch statement with 31 cases. Last Saturday Odile asked for one small change, a 10 in 100 discount for earn-a-bike graduates, and it took Hamza three evenings, because the price of a rental was worked out in four different places.

This course follows Hamza through Ingrid's Tuesday sessions in the winter term of 2028: Tuesday, January 11 to Tuesday, March 28, at 5:00 pm before repair night, with no session on Tuesday, February 22, during the college's reading week. On Mondays the same term he is learning concurrency for OrderDesk; on Tuesdays he learns how to design code that is easy to change. Leif Quarmby, the build engineer from his tools course, joins for the lessons on architecture. After OrderDesk's review on April 10, Hamza will spend the second half of April redesigning CounterApp, and he will present the new design to Ingrid, Leif, Odile and Kofi on Tuesday, May 2, 2028. All of this is planned work; the course is written ahead of time, and every runnable example has been compiled and run on Java 21.

Design is about change

Every working program does what it does today. The difference between a well-designed program and a poorly designed one shows up tomorrow, when someone needs it to do something slightly different. Software design is the set of decisions about how a program is divided into parts, what each part is responsible for, and how the parts depend on each other. Good design makes the likely changes cheap and safe. Poor design makes every change expensive, risky or both.

Ingrid puts it in shop terms. A well-organized parts room has one place for brake pads, labelled, and when a new kind of pad arrives everybody knows where it goes. A badly organized one has pads in four drawers, under the counter and in Tamsin's apron, and nobody can say how many there are. The parts are the same; what differs is how easy the room is to work in. Code is the same. CounterApp has all the right logic in it. The trouble is where that logic lives and how tightly it is tied to everything else.

Three ideas carry most of the weight in this course: cohesion, coupling and the cost of change. They are old ideas, described by Larry Constantine and Edward Yourdon in the 1970s, and every pattern and principle in later lessons is a way of getting more of the first, less of the second, and lowering the third.

Cohesion: one job per part

A part of a program, whether a method, a class or a package, has high cohesion when everything in it works toward one clear purpose. A class called RentalPricing that only calculates rental prices is highly cohesive. A class called CounterApp that reads files, calculates prices, formats receipts, sends text messages and talks to the till has low cohesion: it does many unrelated jobs, so a change to any one of them means opening the same crowded class.

Here is a method much like one in CounterApp. It works out a rental quote, adds tax, applies the new discount and prints a receipt, all in one place.

Java Example · Main.java
public class Main {
    static void rentalQuote(String bike, int days, boolean graduate) {
        int perDay;
        if (bike.equals("CITY")) perDay = 2500;
        else if (bike.equals("CARGO")) perDay = 4000;
        else perDay = 4500;
        int charged = days == 7 ? 5 : days;
        int cents = perDay * charged;
        if (graduate) cents = cents - cents / 10;
        int tax = Math.round(cents * 13 / 100.0f);
        System.out.println("Rental: " + bike + " x " + days + " days");
        System.out.println("Subtotal: " + cents / 100 + "." + String.format("%02d", cents % 100));
        System.out.println("HST: " + tax / 100 + "." + String.format("%02d", tax % 100));
        int total = cents + tax;
        System.out.println("Total: " + total / 100 + "." + String.format("%02d", total % 100));
    }

    public static void main(String[] args) {
        rentalQuote("CARGO", 3, true);
    }
}
Output
Rental: CARGO x 3 days
Subtotal: 108.00
HST: 14.04
Total: 122.04

What this code does

One method chooses a daily price, applies the seven-day deal and the graduate discount, works out tax and prints a receipt. The answer is right, but four different jobs are knotted together, so the rule for prices cannot be used without the printing, and the tax rate is buried in the middle. Every change to prices, tax or receipts means editing this same method.

Nothing in that method is wrong, and for a ten-line program it would be fine. The trouble starts when the same price rule is needed somewhere else, for example on the shop's website, on the weekly report and in the booking screen. With no separate place for the rule, each of those places gets its own copy, and that is exactly how CounterApp ended up with four versions of the rental price that had drifted apart.

The cohesive version gives each job its own small piece: a record for money, a class that knows the rental price rules, a class that knows the tax rate, and a method that formats a receipt. Each piece can be read, tested and changed on its own.

Java Example · Main.java
public class Main {
    record Money(int cents) {
        Money plus(Money o) { return new Money(cents + o.cents); }
        Money minusTenth() { return new Money(cents - cents / 10); }
        public String toString() { return cents / 100 + "." + String.format("%02d", cents % 100); }
    }

    static final class RentalPricing {
        static int perDay(String bike) {
            return switch (bike) { case "CITY" -> 2500; case "CARGO" -> 4000; default -> 4500; };
        }
        static Money quote(String bike, int days, boolean graduate) {
            int charged = days == 7 ? 5 : days;
            Money m = new Money(perDay(bike) * charged);
            return graduate ? m.minusTenth() : m;
        }
    }

    static final class Tax {
        static final String NAME = "HST";
        static Money on(Money m) { return new Money(Math.round(m.cents() * 13 / 100.0f)); }
    }

    static String receipt(String bike, int days, Money sub) {
        Money tax = Tax.on(sub);
        return "Rental: " + bike + " x " + days + " days\n"
             + "Subtotal: " + sub + "\n" + Tax.NAME + ": " + tax + "\n" + "Total: " + sub.plus(tax);
    }

    public static void main(String[] args) {
        Money sub = RentalPricing.quote("CARGO", 3, true);
        System.out.println(receipt("CARGO", 3, sub));
    }
}
Output
Rental: CARGO x 3 days
Subtotal: 108.00
HST: 14.04
Total: 122.04

What this code does

The same receipt is produced, but now the price rule lives in RentalPricing, the tax rule in Tax, money formatting in Money and the layout in receipt. Each piece does one job, so the website could call RentalPricing.quote without printing anything. When the tax rate or the discount changes, there is exactly one place to change it.

The second version is longer, which surprises beginners. Good design rarely makes a program shorter on the first day. It makes it shorter on the hundredth day, because the pieces get reused instead of copied, and because each future change touches one small piece instead of a long method.

Coupling: how parts depend on each other

Coupling measures how much one part of a program depends on the details of another. Two classes are tightly coupled when a change inside one forces changes in the other: when one reaches into the other's fields, relies on the order of its internal steps, or creates it directly by name. They are loosely coupled when one depends only on a small, stable promise made by the other, such as an interface with two methods.

Some coupling is unavoidable; parts that never depended on each other could not work together. The goal is to keep dependencies few, narrow and pointed at things that rarely change. In CounterApp, the booking code reads the parts spreadsheet file directly, so when Kofi renamed a column in December 2027, bookings broke as well as the parts screen. That is tight coupling to a detail, the file layout, that changes often.

The standard tool for loosening coupling in Java is the interface. Code that needs a list of parts asks for anything that can list parts, rather than for one particular class that reads one particular file.

Java Example · Main.java
import java.util.*;

public class Main {
    interface PartCatalog {
        int stock(String code);
    }

    static final class SpreadsheetCatalog implements PartCatalog {
        public int stock(String code) { return code.equals("TUBE-700x25") ? 14 : 0; }
    }

    static final class InMemoryCatalog implements PartCatalog {
        private final Map<String, Integer> counts;
        InMemoryCatalog(Map<String, Integer> counts) { this.counts = counts; }
        public int stock(String code) { return counts.getOrDefault(code, 0); }
    }

    static final class LowStockCheck {
        private final PartCatalog catalog;
        LowStockCheck(PartCatalog catalog) { this.catalog = catalog; }
        String check(String code, int minimum) {
            int n = catalog.stock(code);
            return code + ": " + n + (n < minimum ? " (reorder)" : " (ok)");
        }
    }

    public static void main(String[] args) {
        LowStockCheck live = new LowStockCheck(new SpreadsheetCatalog());
        LowStockCheck test = new LowStockCheck(new InMemoryCatalog(Map.of("TUBE-700x25", 3)));
        System.out.println(live.check("TUBE-700x25", 10));
        System.out.println(test.check("TUBE-700x25", 10));
    }
}
Output
TUBE-700x25: 14 (ok)
TUBE-700x25: 3 (reorder)

What this code does

LowStockCheck depends only on the PartCatalog interface, so it neither knows nor cares where the counts come from. The program gives it a spreadsheet-backed catalog in one case and an in-memory map in the other, and the check works unchanged with both. That loose coupling is what lets the same rule run against the real file at the counter and against made-up numbers in a test.

Look at how LowStockCheck gets its catalog: through its constructor, from whoever creates it. It never says new SpreadsheetCatalog() itself. That small habit, passing in the things a class needs instead of creating them inside, is called dependency injection, and lesson 3 returns to it. It is the single most useful habit for keeping classes loosely coupled and easy to test.

Two diagrams side by side. On the left, a large box labelled CounterApp has arrows going directly to a parts file, a bookings file, the till and a text message service, and other boxes reach into it. On the right, small boxes for pricing, booking and stock each point to a small interface, and the file, till and message service sit behind those interfaces.
Tight coupling (left) and loose coupling through small interfaces (right)

The cost of change

The most practical way to judge a design is to ask what the likely changes will cost. For each change, count the places you would need to edit, the tests you would need to run, and the chance that something unrelated breaks. A design where a typical change touches one or two small classes is cheap to change. A design where every change ripples through the program is expensive, and the expense grows with every feature added, which is why poorly designed programs seem to slow down their teams month by month.

Hamza tries this on CounterApp with the last six things Odile asked for. He lists the requests and, for each one, how many places in the code he had to edit.

Java Example · Main.java
import java.util.*;

public class Main {
    record Change(String request, int placesEdited, boolean brokeSomethingElse) {}

    public static void main(String[] args) {
        List<Change> changes = List.of(
            new Change("graduate discount", 4, true),
            new Change("new tandem price", 4, false),
            new Change("HST on receipts only", 3, true),
            new Change("phone numbers hidden in logs", 6, false),
            new Change("new bell supplier", 2, false),
            new Change("Saturday repair hours", 3, true));

        int total = 0, broken = 0;
        for (Change c : changes) {
            total += c.placesEdited();
            if (c.brokeSomethingElse()) broken++;
            System.out.printf("%-30s %d%s%n", c.request(), c.placesEdited(), c.brokeSomethingElse() ? "  broke another feature" : "");
        }
        System.out.printf("average places per change: %.1f%n", total / (double) changes.size());
        System.out.println("changes that broke something else: " + broken + " of " + changes.size());
    }
}
Output
graduate discount              4  broke another feature
new tandem price               4
HST on receipts only           3  broke another feature
phone numbers hidden in logs   6
new bell supplier              2
Saturday repair hours          3  broke another feature
average places per change: 3.7
changes that broke something else: 3 of 6

What this code does

Each record lists one request Odile made, how many places in CounterApp had to be edited, and whether the change broke an unrelated feature. The loop prints the list, then the average number of places per change and how many changes caused a second problem. Numbers like these turn a vague feeling that the code is messy into evidence that a redesign would pay for itself.

An average of three or four places per change, with half the changes breaking something else, is a clear signal. Ingrid's rule of thumb is that a change to one business rule should usually mean editing one class, plus its tests. She also warns against the opposite mistake: designing for changes that will never come. Adding interfaces and layers for possibilities nobody has asked for is called speculative generality, and it makes code harder to read for no benefit. Good design responds to the changes you can reasonably expect, such as prices, tax rules, storage and the screens customers see, and keeps everything else simple.

Other signs of good design

Beyond cohesion and coupling, a few more qualities appear in every discussion of design, and they all serve the same goal of cheap, safe change.

Qualities of a good design
QualityWhat it meansSign that it is missing
ReadabilityA newcomer can tell what the code does and whyNames like data2, flag and doIt; long methods with comments explaining each block
EncapsulationEach class hides its internal data and exposes a small set of operationsPublic fields, getters and setters for everything, other classes changing state directly
Single source of truthEach rule or fact is stated in one placeThe same price or rate written in several places
TestabilityParts can be checked on their own, with fake inputsA test needs the real file, the real till and the network
SimplicityNo more structure than the problem needsInterfaces with one implementation that will never have a second, layers that only pass calls through

The principle of a single source of truth is often called DRY, for don't repeat yourself, a name from Andrew Hunt and David Thomas's book The Pragmatic Programmer. It is about knowledge, not text: two lines that look the same but represent different rules can stay separate, while two lines that look different but encode the same rule should be merged. The rental price in CounterApp was one rule written four ways, which is the kind of repetition that hurts.

Ingrid adds one more test, which she calls the explaining test. Can you describe what a class does in one sentence without using the word and? RentalPricing calculates rental prices. CounterApp reads files and calculates prices and prints receipts and sends messages and talks to the till. The second sentence is a design problem written out in plain English.

Technical debt

Ward Cunningham coined the phrase technical debt for the cost that shortcuts in code add to future work. Taking a shortcut is like borrowing money: it can be the right decision, for example to get CounterApp working before the summer rush of 2027, but you pay interest on every later change until you pay the debt back by cleaning the code up. CounterApp's debt is now so large that most of each change goes on interest. This course is about recognizing debt, avoiding unnecessary debt, and paying it back safely, which lesson 10 covers in detail.

Hamza writes three goals on the whiteboard for the term. First, every business rule in one place. Second, the rules testable without files, the till or the network. Third, a new screen, such as Odile's planned website, able to reuse the rules without copying them. The rest of the course gives him the tools: principles in lesson 2, patterns in lessons 3 to 6, architecture in lessons 7 and 8, modelling in lesson 9, legacy techniques in lesson 10, diagrams in lesson 11 and the redesign itself in lesson 12.

Try it yourself

Give the tax rule one home

The starter works out tax in two places, once for repairs and once for parts, and the two copies have drifted: one uses 13 and the other 12. Add a single static method tax(int cents) that returns Math.round(cents * 13 / 100.0f), and use it in both places.

The program should print repair tax: 845 and parts tax: 117.

public class Main {
    public static void main(String[] args) {
        int repair = 6500;
        int repairTax = Math.round(repair * 13 / 100.0f);
        System.out.println("repair tax: " + repairTax);

        int parts = 899;
        int partsTax = Math.round(parts * 12 / 100.0f);
        System.out.println("parts tax: " + partsTax);
    }
}

Try it yourself

Depend on an interface

The starter's Reminder class creates a ConsolePhone itself, so it cannot be tested without printing. Add an interface Phone with a method void send(String number, String text), make ConsolePhone implement it, and give Reminder a constructor that takes a Phone. In main, pass Reminder a lambda that only counts messages instead.

The program should print messages sent: 2.

public class Main {
    static final class ConsolePhone {
        void send(String number, String text) { System.out.println(number + ": " + text); }
    }

    static final class Reminder {
        private final ConsolePhone phone = new ConsolePhone();
        void remind(String number, String bike) { phone.send(number, "Your " + bike + " is ready"); }
    }

    public static void main(String[] args) {
        Reminder r = new Reminder();
        r.remind("555-0101", "city bike");
        r.remind("555-0102", "cargo bike");
    }
}

Common mistakes

  • MistakeJudging a design by how short it is today.

    InsteadJudge it by how many places a likely change would touch and how safely you can make it.

  • MistakeWriting the same business rule in several places.

    InsteadGive each rule one home, a single source of truth, and call it from everywhere.

  • MistakeLetting classes create their own collaborators with new.

    InsteadPass collaborators in through the constructor so they can be swapped and tested.

  • MistakeAdding interfaces and layers for changes nobody expects.

    InsteadDesign for the changes you can reasonably foresee and keep the rest simple.

  • MistakeTreating technical debt as free.

    InsteadTake shortcuts knowingly and plan to pay them back before the interest swamps every change.

Summary and key terms

  • Software design is the set of decisions about how a program is divided into parts, what each part does and how parts depend on each other.
  • A good design makes likely changes cheap and safe.
  • Cohesion means each part has one clear purpose; low cohesion puts unrelated jobs in one place.
  • Coupling measures how much one part depends on another's details; loose coupling relies on small, stable promises such as interfaces.
  • Dependency injection passes collaborators in through constructors instead of creating them inside.
  • The cost of change can be estimated by counting the places a change touches and how often changes break other features.
  • A single source of truth, or DRY, keeps each rule in one place.
  • Speculative generality adds structure for changes that never come.
  • Technical debt is the extra cost that shortcuts add to later changes, and it has to be paid back.
Software design
The decisions about how a program is divided into parts and how those parts depend on each other.
Cohesion
How closely everything in one part of a program works toward a single purpose.
Coupling
How much one part of a program depends on the details of another.
Loose coupling
Depending only on a small, stable promise such as an interface.
Interface
A Java type that lists operations without saying how they are done.
Dependency injection
Giving a class the objects it needs from outside, usually through its constructor.
Cost of change
The effort and risk involved in making a typical change to a program.
Single source of truth
Stating each rule or fact in exactly one place.
DRY
Don't repeat yourself: avoid stating the same knowledge in more than one place.
Speculative generality
Structure added for changes that nobody needs, which makes code harder to read.
Technical debt
The extra cost later changes pay because of shortcuts taken earlier.
Encapsulation
Hiding a class's internal data and exposing only a small set of operations.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Describe CounterApp in one sentence. What does the sentence reveal?

    Show answer

    It reads files and calculates prices and formats receipts and sends messages and talks to the till; all the ands reveal low cohesion.

  2. Why is the cohesive rental example longer than the first version?

    Show answer

    Good design adds small named pieces on the first day; it pays back over later changes and reuse.

  3. What made LowStockCheck easy to test?

    Show answer

    It depends on the PartCatalog interface and receives its catalog through the constructor.

  4. Two lines in different classes both say 13. Should they always be merged?

    Show answer

    Only if they state the same rule, such as the HST rate; equal numbers for different rules can stay separate.

  5. What is speculative generality?

    Show answer

    Structure, such as extra interfaces or layers, added for changes nobody expects.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz