Part 5 of 7 · 3 min read
Step 4
Make the main flow compile and run.
The code below is the whole core of the room system. It was compiled and run with Java 21 (records need Java 16 or newer).
import java.util.*;
record TimeSlot(int startMinute, int endMinute) {
TimeSlot {
if (startMinute >= endMinute) {
throw new IllegalArgumentException("start must be before end");
}
}
boolean overlaps(TimeSlot other) {
return startMinute < other.endMinute && other.startMinute < endMinute;
}
}
enum BookingStatus { CONFIRMED, CANCELLED }
record Room(String id, int capacity) {}
class Booking {
private final String id;
private final Room room;
private final String userId;
private final TimeSlot slot;
private BookingStatus status = BookingStatus.CONFIRMED;
Booking(String id, Room room, String userId, TimeSlot slot) {
this.id = id; this.room = room; this.userId = userId; this.slot = slot;
}
String id() { return id; }
Room room() { return room; }
TimeSlot slot() { return slot; }
boolean isActive() { return status == BookingStatus.CONFIRMED; }
void cancel() { status = BookingStatus.CANCELLED; }
}
class BookingService {
private final List<Booking> bookings = new ArrayList<>();
private int nextId = 1;
Booking book(Room room, String userId, TimeSlot slot) {
for (Booking b : bookings) {
if (b.isActive() && b.room().equals(room) && b.slot().overlaps(slot)) {
throw new IllegalStateException("room is taken");
}
}
Booking booking = new Booking("B" + nextId++, room, userId, slot);
bookings.add(booking);
return booking;
}
void cancel(String bookingId) {
for (Booking b : bookings) {
if (b.id().equals(bookingId)) { b.cancel(); return; }
}
throw new NoSuchElementException(bookingId);
}
}
A short run: book room R1 from 10:00 to 11:00, then try 10:30 to 11:30 and get "room is taken". Cancel the first, and the second booking now succeeds and gets id B2. That is the whole rule, shown working.
Notes on the choices:
- Booking is a class, not a record, because its status changes. A record cannot change after it is built.
- Fields are private final unless they must change. Only status changes.
- The service throws exceptions for bad input and does not return null. Level 5 explains this.
- A loop is enough for 800 blocks a day (module 2). Using a faster structure would be extra work with no requirement behind it. Say that aloud.
Main flow
The main flow is the most important path through the program, written first so that a working core exists before any extras.
Example: for the room system, book with no conflict, then book with a conflict, then cancel.
Check yourself:
1. Why is Booking a class and Room a record?
2. What does book do when a slot overlaps an active booking?
3. Why is a plain loop acceptable here?