Putting it together: designing a complete program

Advanced

Introduction

You now know Java's building blocks: types, control flow, methods, arrays, strings, classes, inheritance, interfaces, exceptions, collections, generics, lambdas and streams. Real programs combine them. This last lesson shows how to design a small but complete program, a library's lending system, so that it stays correct and easy to change as it grows.

How it works

Start from the problem's nouns and verbs. A library has books and members (nouns) and lends and takes back books (verbs). Nouns become domain classes or records; verbs become methods. Immutable data such as a book's id and title fits a record; something with changing state and rules, such as the library itself, is a class.

Choose collections by how the data is used. Books are looked up by id, so a Map<String, Book>; a TreeMap also keeps them in id order for listings. Loans map a book id to the member who has it. A waiting list would be a queue; a set of member ids would catch duplicates.

Guard the invariants inside the class. The rules "you cannot lend a book that does not exist" and "you cannot lend a book that is already out" belong in Library.lend, not in main. When a rule is broken, the method throws an exception with a clear message, and the object is left unchanged. Because the fields are private, no other code can break the rules by changing the maps directly.

Separate concerns. main reads input, calls methods and prints results; the Library class knows nothing about input formats or printing. That makes the logic easy to test: call its methods with known values and check the results, including the edge cases: lending twice, returning a book that was not lent, an unknown id, an empty library.

Grow it in small steps. Write one method, run it with a few cases, then add the next. Each step stays small enough that a mistake is easy to find. When a method gets long, split it; when two classes need the same behaviour, consider an interface.

Example

import java.util.*;

public class Main {
    static class LibraryException extends RuntimeException {
        LibraryException(String message) { super(message); }
    }

    record Book(String id, String title) {}

    static class Library {
        private final Map<String, Book> books = new TreeMap<>();
        private final Map<String, String> loans = new HashMap<>(); // book id -> member

        void add(Book b) { books.put(b.id(), b); }

        void lend(String id, String member) {
            if (!books.containsKey(id)) throw new LibraryException("no book " + id);
            if (loans.containsKey(id)) throw new LibraryException(id + " is out");
            loans.put(id, member);
        }

        void giveBack(String id) {
            if (loans.remove(id) == null) throw new LibraryException(id + " was not lent");
        }

        List<String> available() {
            List<String> out = new ArrayList<>();
            for (Book b : books.values()) if (!loans.containsKey(b.id())) out.add(b.title());
            return out;
        }
    }

    public static void main(String[] args) {
        Library lib = new Library();
        lib.add(new Book("B2", "Dune"));
        lib.add(new Book("B1", "Emma"));
        String[][] actions = {{"lend", "B1", "Rina"}, {"lend", "B1", "Arif"}, {"lend", "B9", "Zoya"}, {"back", "B2", ""}};
        for (String[] a : actions) {
            try {
                if (a[0].equals("lend")) lib.lend(a[1], a[2]);
                else lib.giveBack(a[1]);
                System.out.println("ok " + a[0] + " " + a[1]);
            } catch (LibraryException e) {
                System.out.println("error: " + e.getMessage());
            }
        }
        System.out.println("available: " + lib.available());
    }
}
Open in compiler

Line by line

  1. Book is a record: immutable data with an id and a title.
  2. Library keeps books in a TreeMap by id and loans in a HashMap from book id to member.
  3. lend and giveBack check the rules and throw LibraryException when one is broken, changing nothing.
  4. main runs four actions and prints the result of each; the error messages come from the class.
  5. available lists the titles of the books not out, in id order.

Expected result

ok lend B1
error: B1 is out
error: no book B9
error: B2 was not lent
available: [Dune]

In the real world

Professional Java applications are organised the same way at a larger scale: domain classes for the business concepts, service classes that enforce rules, and separate layers for input, such as web controllers, and storage. Unit tests call the service classes directly, exactly as main does here.

Common mistakes

  • Putting all the logic in main, which makes it impossible to reuse or test.
  • Public fields or collections that let any code break the rules.
  • Changing state before checking, so a failed operation leaves half its changes behind.
  • Testing only the happy path and missing edge cases.

Best practices

  • Name classes after what they model and methods after what they do.
  • Validate first, then change state, so every operation either fully succeeds or changes nothing.
  • Test each method with normal cases and edge cases as you write it.

Summary

A complete program models the problem with small classes and records, chooses each collection for how its data is used, protects every invariant inside the class that owns it with checks and exceptions, and keeps input and output in main so the logic can be tested on its own, in small steps.

Quick check

1. Where should the rule 'a book cannot be lent twice' live?
2. Why check every rule before changing any state?
3. Which collection suits looking books up by id?
4. What is an edge case?

Key takeaways

  • Model the problem with small classes and records; give each one job.
  • Guard each class's invariants in its own methods and report violations with exceptions.
  • Keep parsing and printing in main, and the rules in classes that can be tested on their own.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.