JAVA-102 · Lesson 12 of 12 · 28 min
Capstone: an object-oriented booking system
▶ Video coming soon A video version of this lesson is on the way.
The winter term's plan ends where it began, with Odile. On the first evening, January 13, she asked for a way to book repairs and, from the spring, the shop's rental bikes, so that Fenna at the counter and Tamsin in the workshop can see each day at a glance. The capstone, which Hamza plans to build in the two weeks from Monday, April 5, 2027 and demonstrate on Saturday, April 17, is ShopBook: a console booking system that uses every idea from this course. This lesson follows the plan from requirements to a tested program, and shows the whole program, about 230 lines in one file.
Requirements
Ingrid's first rule for any project is to agree, in writing, what the program must do before writing it. Hamza and Odile plan to agree eight requirements, kept short enough to fit on one page and specific enough to test.
| # | Requirement |
|---|---|
| R1 | Record repair bookings with a customer, a one-hour slot between 9:00 and 16:00, a job and a quoted price. |
| R2 | Record rental bookings with a customer, a start date, a bike type (city, cargo or tandem) and 1 to 28 days. |
| R3 | Allow at most a set number of repairs per day, and never two repairs in the same slot. |
| R4 | Never rent more bikes of a type than the fleet has: 4 city bikes, 1 cargo bike, 1 tandem. |
| R5 | Give every booking a unique number, starting at 1001, for the repair tag. |
| R6 | Move bookings through REQUESTED, CONFIRMED, READY and PICKED_UP, or WITHDRAWN, refusing any other move. |
| R7 | Price rentals by the day with every seventh day free, and add tax to every price. |
| R8 | Print a day sheet listing each booking with its kind, status and total, and the day's total. |
Each requirement will be checked by a line of the final test run. If a requirement cannot be tested, it is not yet clear enough.
The design
The nouns in the requirements point to the classes, and the earlier lessons point to the kind of type for each. Values that never change and compare by value are records: Customer, Slot and Money. Fixed sets are enums: Status, with its allowed moves, and BikeType, with its rate and fleet size. The two kinds of booking share state and identity, so they are subclasses of an abstract sealed Booking class, which implements a Priced interface. Rules that involve many bookings, such as the daily limit, live in a BookingService, and refusals are a checked BookingException.
| Type | Kind | Why | Lesson |
|---|---|---|---|
| Customer, Slot, Money | records | Immutable values compared by value, validated in compact constructors | 9, 10 |
| Status | enum | A fixed set of states with the allowed moves | 9 |
| BikeType | enum | A fixed fleet with a rate and size for each type | 9 |
| Priced | interface | Anything with a price gets total() with tax | 6 |
| Booking | abstract sealed class | Shared state and identity for exactly two kinds | 5, 6, 7 |
| RepairBooking, RentalBooking | final classes | Each supplies its own price and summary | 5, 7 |
| BookingService | class | Rules about many bookings: limits and availability | 1, 2 |
| BookingException | checked exception | A full day is normal business the caller must handle | 8 |
| Rates | utility class | Tax rate and limits as constants | 4 |
Building in small steps
Hamza's plan follows the habit JAVA-101's capstone taught: build the smallest piece that runs, test it, then add the next. The planned order is the value types first, because everything else uses them; then Status and its rules, tested on its own; then Booking and its two subclasses; then the service with one rule at a time; and the day sheet last. At each step the program compiles and prints something checkable. The steps below show the key pieces before the full program.
First, the values. Each record checks its own components, so an invalid customer or slot can never exist anywhere in the program.
public class Main {
record Slot(String date, int hour) {
Slot {
if (hour < 9 || hour > 16) throw new IllegalArgumentException("no repairs at " + hour + ":00");
}
}
record Money(long cents) {
static Money ofDollars(long d) { return new Money(d * 100); }
Money plus(Money o) { return new Money(cents + o.cents); }
Money times(long n) { return new Money(cents * n); }
@Override public String toString() { return String.format("%d.%02d", cents / 100, cents % 100); }
}
public static void main(String[] args) {
Slot a = new Slot("2027-04-24", 10);
System.out.println(a + " equals a copy? " + a.equals(new Slot("2027-04-24", 10)));
Money cargo = new Money(3000).times(3);
System.out.println("Three cargo days: " + cargo + ", plus a brake bleed: " + cargo.plus(Money.ofDollars(45)));
try {
new Slot("2027-04-24", 18);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}Slot[date=2027-04-24, hour=10] equals a copy? true Three cargo days: 90.00, plus a brake bleed: 135.00 Rejected: no repairs at 18:00
What this code does
Slot and Money are records, so they compare by value and print themselves, and Slot's compact constructor rejects hours outside 9 to 16. Money keeps whole cents and returns new values from plus and times. The test prints the expected results for equality, arithmetic and a rejected slot before any booking code exists.
Next, the status rules, checked on their own. An enum whose canMoveTo covers every value means javac will flag any status added later without a rule.
public class Main {
enum Status {
REQUESTED, CONFIRMED, READY, PICKED_UP, WITHDRAWN;
boolean canMoveTo(Status next) {
return switch (this) {
case REQUESTED -> next == CONFIRMED || next == WITHDRAWN;
case CONFIRMED -> next == READY || next == WITHDRAWN;
case READY -> next == PICKED_UP;
case PICKED_UP, WITHDRAWN -> false;
};
}
}
public static void main(String[] args) {
int allowed = 0;
for (Status from : Status.values()) {
StringBuilder sb = new StringBuilder(from + " ->");
for (Status to : Status.values()) {
if (from.canMoveTo(to)) { sb.append(" ").append(to); allowed++; }
}
System.out.println(sb);
}
System.out.println("Allowed moves: " + allowed);
}
}REQUESTED -> CONFIRMED WITHDRAWN CONFIRMED -> READY WITHDRAWN READY -> PICKED_UP PICKED_UP -> WITHDRAWN -> Allowed moves: 5
What this code does
The test prints every allowed move from every status, which can be checked against Odile's rules line by line. There are exactly five allowed moves, and the two closed statuses allow none. Testing the enum alone means a mistake here is found before it hides inside the bookings.
Then the bookings themselves. The numbering, the identity-based equals and the move rules all live in the abstract class, so the two subclasses only add what is different about them.
public class Main {
public static void main(String[] args) {
Booking r = new RepairBooking("Ana Ruiz", "brake bleed", 4500);
Booking t = new RentalBooking("Theo Park", 7);
System.out.println(r + " costs " + r.priceCents());
System.out.println(t + " costs " + t.priceCents());
System.out.println("Same booking? " + r.equals(t));
}
}
abstract class Booking {
private static int nextNumber = 1001;
private final int number = nextNumber++;
private final String customer;
protected Booking(String customer) { this.customer = customer; }
abstract long priceCents();
abstract String summary();
@Override public final boolean equals(Object o) { return o instanceof Booking b && number == b.number; }
@Override public final int hashCode() { return Integer.hashCode(number); }
@Override public String toString() { return "#" + number + " " + customer + ", " + summary(); }
}
final class RepairBooking extends Booking {
private final String job;
private final long quote;
RepairBooking(String c, String job, long quote) { super(c); this.job = job; this.quote = quote; }
@Override long priceCents() { return quote; }
@Override String summary() { return "repair: " + job; }
}
final class RentalBooking extends Booking {
private final int days;
RentalBooking(String c, int days) { super(c); this.days = days; }
@Override long priceCents() { return 3000L * (days - days / 7); }
@Override String summary() { return "cargo rental, " + days + " days"; }
}#1001 Ana Ruiz, repair: brake bleed costs 4500 #1002 Theo Park, cargo rental, 7 days costs 18000 Same booking? false
What this code does
Each booking takes the next number from the shared static counter through a field initializer, and equals compares only that number. The repair returns its quote, and the seven-day cargo rental charges six days at 30 dollars. Marking equals and hashCode final stops a subclass from breaking the identity rule.
The whole program
The finished ShopBook brings the pieces together with the BookingService and the day sheet. main plays out a planned Saturday at the counter: a mix of repairs and rentals, three refusals because of the rules, and two status changes. The run helper takes the booking request as a small lambda, the arrow syntax from JAVA-101's sorting, so that each request's BookingException is caught and reported the same way.
import java.util.Objects;
public class Main {
public static void main(String[] args) {
BookingService shop = new BookingService(Rates.REPAIRS_PER_DAY);
Customer ana = new Customer("Ana Ruiz", "905-555-0142");
Customer theo = new Customer("Theo Park", "905-555-0177");
Customer mei = new Customer("Mei Lin", "905-555-0101");
Slot sat = new Slot("2027-04-24", 10);
run(() -> shop.bookRepair(ana, sat, "brake bleed", Money.ofDollars(45)));
run(() -> shop.bookRental(theo, sat, BikeType.CARGO, 3));
run(() -> shop.bookRepair(mei, sat, "full tune-up", Money.ofDollars(85)));
run(() -> shop.bookRepair(mei, new Slot("2027-04-24", 11), "full tune-up", Money.ofDollars(85)));
run(() -> shop.bookRepair(theo, new Slot("2027-04-24", 13), "wheel true", Money.ofDollars(30)));
run(() -> shop.bookRental(ana, sat, BikeType.TANDEM, 1));
run(() -> shop.bookRental(mei, sat, BikeType.CARGO, 2));
shop.find(1001).moveTo(Status.CONFIRMED);
shop.find(1001).moveTo(Status.READY);
try {
shop.find(1002).moveTo(Status.PICKED_UP);
} catch (IllegalStateException e) {
System.out.println("Refused: " + e.getMessage());
}
System.out.println();
System.out.println(shop.daySheet("2027-04-24"));
}
interface Action { Booking act() throws BookingException; }
static void run(Action a) {
try {
System.out.println("Booked " + a.act());
} catch (BookingException e) {
System.out.println("Not booked: " + e.getMessage());
}
}
}
record Customer(String name, String phone) {
Customer {
Objects.requireNonNull(name, "name");
if (!phone.matches("\\d{3}-\\d{3}-\\d{4}")) throw new IllegalArgumentException("bad phone: " + phone);
}
}
record Slot(String date, int hour) {
Slot {
if (hour < 9 || hour > 16) throw new IllegalArgumentException("no repairs at " + hour + ":00");
}
@Override public String toString() { return date + " " + hour + ":00"; }
}
record Money(long cents) {
static Money ofDollars(long d) { return new Money(d * 100); }
Money plus(Money o) { return new Money(cents + o.cents); }
Money times(long n) { return new Money(cents * n); }
Money tax() { return new Money((cents * Rates.TAX_PER_HUNDRED + 50) / 100); }
@Override public String toString() { return String.format("%d.%02d", cents / 100, cents % 100); }
}
final class Rates {
private Rates() { }
static final int TAX_PER_HUNDRED = 13;
static final String TAX_NAME = "HST";
static final int REPAIRS_PER_DAY = 2;
}
enum Status {
REQUESTED, CONFIRMED, READY, PICKED_UP, WITHDRAWN;
boolean canMoveTo(Status next) {
return switch (this) {
case REQUESTED -> next == CONFIRMED || next == WITHDRAWN;
case CONFIRMED -> next == READY || next == WITHDRAWN;
case READY -> next == PICKED_UP;
case PICKED_UP, WITHDRAWN -> false;
};
}
}
enum BikeType {
CITY(1500, 4), CARGO(3000, 1), TANDEM(2500, 1);
private final long dailyCents;
private final int fleet;
BikeType(long dailyCents, int fleet) { this.dailyCents = dailyCents; this.fleet = fleet; }
Money daily() { return new Money(dailyCents); }
int fleet() { return fleet; }
}
interface Priced {
Money price();
default Money total() { return price().plus(price().tax()); }
}
abstract sealed class Booking implements Priced permits RepairBooking, RentalBooking {
private static int nextNumber = 1001;
private final int number;
private final Customer customer;
private final Slot slot;
private Status status = Status.REQUESTED;
protected Booking(Customer customer, Slot slot) {
this.number = nextNumber++;
this.customer = Objects.requireNonNull(customer);
this.slot = Objects.requireNonNull(slot);
}
int number() { return number; }
Customer customer() { return customer; }
Slot slot() { return slot; }
Status status() { return status; }
void moveTo(Status next) {
if (!status.canMoveTo(next)) {
throw new IllegalStateException("#" + number + " is " + status + " and cannot become " + next);
}
status = next;
}
abstract String summary();
@Override public final boolean equals(Object o) { return o instanceof Booking b && number == b.number; }
@Override public final int hashCode() { return Integer.hashCode(number); }
@Override public String toString() { return "#" + number + " " + customer.name() + ", " + summary(); }
}
final class RepairBooking extends Booking {
private final String job;
private final Money quote;
RepairBooking(Customer c, Slot s, String job, Money quote) {
super(c, s);
this.job = job;
this.quote = quote;
}
@Override public Money price() { return quote; }
@Override String summary() { return "repair: " + job; }
}
final class RentalBooking extends Booking {
private final BikeType type;
private final int days;
RentalBooking(Customer c, Slot s, BikeType type, int days) {
super(c, s);
if (days < 1 || days > 28) throw new IllegalArgumentException("days must be 1 to 28");
this.type = type;
this.days = days;
}
BikeType type() { return type; }
@Override public Money price() { return type.daily().times(days - days / 7); }
@Override String summary() { return "rental: " + type + ", " + days + (days == 1 ? " day" : " days"); }
}
class BookingException extends Exception {
BookingException(String message) { super(message); }
}
class BookingService {
private final Booking[] bookings = new Booking[200];
private int count;
private final int repairsPerDay;
BookingService(int repairsPerDay) { this.repairsPerDay = repairsPerDay; }
Booking bookRepair(Customer c, Slot s, String job, Money quote) throws BookingException {
long sameDay = countOn(s.date(), RepairBooking.class);
if (sameDay >= repairsPerDay) {
throw new BookingException(s.date() + " already has " + sameDay + " repairs");
}
for (int i = 0; i < count; i++) {
if (bookings[i] instanceof RepairBooking && bookings[i].slot().equals(s)) {
throw new BookingException(s + " is taken");
}
}
return add(new RepairBooking(c, s, job, quote));
}
Booking bookRental(Customer c, Slot s, BikeType type, int days) throws BookingException {
int out = 0;
for (int i = 0; i < count; i++) {
if (bookings[i] instanceof RentalBooking r && r.type() == type && r.slot().date().equals(s.date())) out++;
}
if (out >= type.fleet()) {
throw new BookingException("no " + type + " bike free on " + s.date());
}
return add(new RentalBooking(c, s, type, days));
}
Booking find(int number) {
for (int i = 0; i < count; i++) if (bookings[i].number() == number) return bookings[i];
throw new IllegalArgumentException("no booking #" + number);
}
String daySheet(String date) {
StringBuilder sb = new StringBuilder("Day sheet " + date + "\n");
Money total = new Money(0);
for (int i = 0; i < count; i++) {
Booking b = bookings[i];
if (!b.slot().date().equals(date)) continue;
String kind = switch (b) {
case RepairBooking r -> "REPAIR";
case RentalBooking r -> "RENTAL";
};
sb.append(String.format("%-6s %-38s %-10s %8s%n", kind, b, b.status(), b.total()));
total = total.plus(b.total());
}
sb.append(String.format("Total with " + Rates.TAX_NAME + ": %s", total));
return sb.toString();
}
private long countOn(String date, Class<?> kind) {
long n = 0;
for (int i = 0; i < count; i++) {
if (kind.isInstance(bookings[i]) && bookings[i].slot().date().equals(date)) n++;
}
return n;
}
private Booking add(Booking b) {
bookings[count++] = b;
return b;
}
}Booked #1001 Ana Ruiz, repair: brake bleed Booked #1002 Theo Park, rental: CARGO, 3 days Not booked: 2027-04-24 10:00 is taken Booked #1003 Mei Lin, repair: full tune-up Not booked: 2027-04-24 already has 2 repairs Booked #1004 Ana Ruiz, rental: TANDEM, 1 day Not booked: no CARGO bike free on 2027-04-24 Refused: #1002 is REQUESTED and cannot become PICKED_UP Day sheet 2027-04-24 REPAIR #1001 Ana Ruiz, repair: brake bleed READY 50.85 RENTAL #1002 Theo Park, rental: CARGO, 3 days REQUESTED 101.70 REPAIR #1003 Mei Lin, repair: full tune-up REQUESTED 96.05 RENTAL #1004 Ana Ruiz, rental: TANDEM, 1 day REQUESTED 28.25 Total with HST: 276.85
What this code does
Every requirement shows up in the output: a repair in a slot that is already taken is refused, a third repair is refused because the day's limit of two repairs is reached, and the second cargo rental is refused because the fleet has one cargo bike. Booking 1002 cannot jump from REQUESTED to PICKED_UP, so the enum's rules throw and main reports the refusal. The day sheet uses a pattern switch over the sealed Booking to label each line, and every total includes tax through Priced's default total method.
Read the output against the requirements. R1 and R2: four bookings are recorded with their details. R3: a second repair at 10:00 is refused because the slot is taken, and a third repair on the 24th is refused because of the daily limit. R4: the second cargo rental is refused. R5: the numbers run 1001 to 1004. R6: 1001 moves to READY, and an illegal move is refused. R7: the three-day cargo rental is 90 dollars before tax. R8: the day sheet lists every booking with its kind, status and total.
How the design pays off
Several features of the finished program come from the course's ideas rather than from extra code. Nothing outside Booking can set a status without the rules, because the field is private and moveTo checks the enum (lessons 2 and 9). The day sheet never asks what kind of booking it has to work out a price, because price is polymorphic (lesson 7). Adding a third kind of booking, say a fitting appointment, would require adding it to the permits list, and javac would then point to the one switch that must handle it (lessons 6 and 7). A customer, slot or price can be shared anywhere without copying, because records are immutable (lesson 9).
| Change Odile might ask for | Where it goes | What else changes |
|---|---|---|
| Three repairs a day instead of two | Rates.REPAIRS_PER_DAY | Nothing |
| A fourth city bike | The CITY value of BikeType | Nothing |
| A new status, ON_HOLD | Status and its canMoveTo | javac flags the switch until ON_HOLD has a rule |
| A fitting appointment booking | A new final subclass, added to permits | javac flags the day sheet switch |
| Saving bookings to a file | A new class that reads and writes bookings (JAVA-230) | BookingService gains a save method |
Testing before the demo
Hamza's planned test session, the evening before the demo, uses a checklist that tries each requirement with good and bad input, just as JAVA-101's acceptance tests did. Because the classes check their own rules, many tests are one line: try to create a bad slot, or move a status the wrong way, and see the right exception. JAVA-205 introduces JUnit, which turns such checks into automatic tests that run with one command.
| Test | Expected result |
|---|---|
| A slot at 18:00 | IllegalArgumentException: no repairs at 18:00 |
| A rental of 0 or 30 days | IllegalArgumentException: days must be 1 to 28 |
| A third repair on one day | BookingException naming the date and the count |
| Two repairs in the same slot | BookingException: the slot is taken |
| A second cargo rental on one day | BookingException: no CARGO bike free |
| READY back to CONFIRMED | IllegalStateException naming both statuses |
| A phone number without dashes | IllegalArgumentException: bad phone |
| find(9999) | IllegalArgumentException: no booking #9999 |
What the program does not yet do is equally clear. Bookings vanish when it stops, the fixed array holds 200 bookings at most, and the dates are plain text. JAVA-120 replaces the array with collections, JAVA-230 adds real dates with java.time and saving to files, and JAVA-250 moves the bookings into a database. Each of those changes touches only one or two classes, which is the point of an object-oriented design.
Try it yourself
A new booking rule
Odile wants rentals of 14 days or more to need a manager's approval. Add a method needsApproval() to RentalBooking that returns true for 14 or more days, and print each rental with (approval needed) when it applies.
The program should print #1 Theo Park, 3 days, #2 Mei Lin, 14 days (approval needed) and #3 Ana Ruiz, 21 days (approval needed).
public class Main {
public static void main(String[] args) {
RentalBooking[] rentals = {
new RentalBooking("Theo Park", 3),
new RentalBooking("Mei Lin", 14),
new RentalBooking("Ana Ruiz", 21),
};
for (RentalBooking r : rentals) {
System.out.println(r);
}
}
}
final class RentalBooking {
private static int next = 1;
private final int number = next++;
private final String customer;
private final int days;
RentalBooking(String customer, int days) {
this.customer = customer;
this.days = days;
}
@Override
public String toString() {
return "#" + number + " " + customer + ", " + days + " days";
}
}Try it yourself
Refuse a double-booked slot
Complete book(Slot s) in Workshop so it throws BookingException with the message <slot> is taken (for example 2027-04-24 10:00 is taken) when the slot has already been booked, and otherwise records it.
The program should print Booked 2027-04-24 10:00, Booked 2027-04-24 11:00 and Not booked: 2027-04-24 10:00 is taken.
public class Main {
public static void main(String[] args) {
Workshop w = new Workshop();
Slot[] requests = { new Slot("2027-04-24", 10), new Slot("2027-04-24", 11), new Slot("2027-04-24", 10) };
for (Slot s : requests) {
try {
w.book(s);
System.out.println("Booked " + s);
} catch (BookingException e) {
System.out.println("Not booked: " + e.getMessage());
}
}
}
}
record Slot(String date, int hour) {
@Override public String toString() { return date + " " + hour + ":00"; }
}
class BookingException extends Exception {
BookingException(String message) { super(message); }
}
class Workshop {
private final Slot[] taken = new Slot[20];
private int count;
void book(Slot s) throws BookingException {
taken[count++] = s;
}
}Common mistakes
MistakeStarting to code before the requirements are agreed and testable.
InsteadWrite short, specific requirements first, and test each one.
MistakeBuilding the whole program before running any of it.
InsteadBuild and test in small steps: values, rules, bookings, service, then output.
MistakePutting the daily limit inside each Booking.
InsteadRules about many bookings belong in a service that can see them all.
MistakeUsing a String for the bike type or status in the capstone.
InsteadUse enums so the fleet and the status rules are part of the type.
MistakeCatching BookingException and printing nothing.
InsteadReport the reason to the person at the counter, as run does.
Summary and key terms
- The capstone, ShopBook, turns Odile's request into eight short, testable requirements and a design in which each kind of type does one job.
- Customer, Slot and Money are validated, immutable records; Status is an enum holding the allowed moves; BikeType is an enum with each type's rate and fleet size; Priced is an interface whose default method adds tax; Booking is an abstract sealed class with a shared number, identity-based equals and the move rules, extended by two final subclasses.
- BookingService holds the rules that involve many bookings and throws a checked BookingException when a request breaks them.
- The program is built and tested in small steps, and its output is read against every requirement.
- Encapsulation, polymorphism, sealed types and records make likely changes small and let javac point to the code a new kind or status affects.
- Later courses replace the array, add dates and files, and move the data to a database.
- Requirement
- A short, testable statement of something a program must do.
- Acceptance test
- A check, agreed with the client, that a requirement is met.
- Domain model
- The classes that represent the things and rules of the problem, such as bookings and slots.
- Service class
- A class that holds rules involving many objects, such as daily limits.
- Day sheet
- The printed list of a day's bookings for the workshop and counter.
- Incremental development
- Building and testing a program in small working steps.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why are Customer, Slot and Money records in ShopBook?
Show answer
They are immutable values compared by value, and their compact constructors validate them.
Where does the rule "at most two repairs a day" live, and why?
Show answer
In BookingService, because it involves many bookings that only the service can see.
What happens if a new status is added to Status without a rule?
Show answer
The switch in canMoveTo no longer covers every value, so javac reports an error.
How is a seven-day cargo rental priced?
Show answer
Six days at 30 dollars, since every seventh day is free, plus tax.
Why are equals and hashCode final in Booking?
Show answer
So no subclass can change the rule that bookings are equal by their number.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.