JAVA-290 · Lesson 6 of 12 · 33 min

Building the core features

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

Sprint 2 ran from Thursday, June 15 to Wednesday, June 28, 2028, and its goal was the heart of the website: a customer can book, find and cancel a repair on staging. The booking API already knew how to book a slot, so the sprint's work was mostly in the application layer, the use cases that sit between the pages and the domain rules. Hamza and Noemi paired on canceling, Thierry took the limit and the reminders, and the waiting list, which Odile had ranked last among the Should stories, waited for sprint 4 with its rules already written down.

This lesson follows those use cases one at a time. Each one is shown in plain Java with in-memory adapters and a fixed clock, the same way the team wrote them test-first before connecting the real database, because the rules are the part worth understanding and the framework code around them is small.

Where the rules live

The hexagonal design gave every rule an obvious home. Rules about time and slots, such as which starts exist on a Saturday or whether a date is a public holiday, are in the domain and know nothing about storage or the web. Rules about what a customer may do, such as booking only twice per phone or canceling only until two hours before, are in use cases in the application package, which call the domain and the ports. The site adapter translates between HTML forms and use cases and contains no rules at all. Ingrid's test for whether a rule was in the right place was simple: could the counter app, which uses the REST adapter, break it? If so, it was in the wrong layer.

The use cases of sprints 2 and 4.
Use caseStoryRules it enforcesPorts it uses
BookRepairUS-02, US-04Free start, valid details, at most two active bookings per phone, reminder only with consentSlotQuery, Bookings, Outbox, Clock
FindBookingUS-03Reference and phone must both match; same answer for any mismatchBookings
CancelBookingUS-03Until two hours before the start; frees the start; offers it to the waiting listBookings, Waitlist, Outbox, Clock
ScheduleRemindersUS-07One text at 18:00 the evening before, only for opted-in bookings still BOOKEDBookings, Outbox, Clock
OfferFreedStartUS-08First waiting customer for the day; two-hour hold; then the nextWaitlist, Outbox, Clock

Booking a repair

BookRepair existed in version 1.5.0 for the REST API; the website needed it to do more. It had to accept a problem kind and a reminder consent, enforce the per-phone limit that 1.5.0 had shipped behind a feature flag, and, when the customer agreed, write a reminder into the outbox in the same transaction as the booking. Thierry wrote one test per acceptance criterion first, then the code, and the example below is the use case with in-memory adapters, the test fakes from the previous lesson.

Java Example
import java.time.*;
import java.util.*;

public class Main {
    record Booking(long id, String reference, String phone, LocalDateTime start, String kind, boolean remind, String status) {}
    sealed interface Result permits Booked, Refused {}
    record Booked(Booking booking) implements Result {}
    record Refused(String reason) implements Result {}

    static final List<Booking> bookings = new ArrayList<>();
    static final List<String> outbox = new ArrayList<>();
    static long nextId = 2301;
    static final Clock CLOCK = Clock.fixed(Instant.parse("2028-06-20T16:00:00Z"), ZoneId.of("America/New_York"));

    static Result book(String phone, LocalDateTime start, String kind, boolean remind, String reference) {
        LocalDateTime now = LocalDateTime.now(CLOCK);
        if (!start.isAfter(now)) return new Refused("that time has passed");
        boolean taken = bookings.stream().anyMatch(b -> b.start().equals(start) && b.status().equals("BOOKED"));
        if (taken) return new Refused("that time was just booked by someone else");
        long active = bookings.stream().filter(b -> b.phone().equals(phone) && b.status().equals("BOOKED")
            && b.start().isAfter(now)).count();
        if (active >= 2) return new Refused("this phone number already has 2 upcoming bookings");
        Booking b = new Booking(nextId++, reference, phone, start, kind, remind, "BOOKED");
        bookings.add(b);
        outbox.add("CONFIRMATION " + reference + " now");
        if (remind) outbox.add("REMINDER " + reference + " at " + start.toLocalDate().minusDays(1) + "T18:00");
        return new Booked(b);
    }

    static void show(Result r) {
        switch (r) {
            case Booked b -> System.out.println("booked " + b.booking().id() + " " + b.booking().reference() + " at " + b.booking().start());
            case Refused f -> System.out.println("refused: " + f.reason());
        }
    }

    public static void main(String[] args) {
        LocalDateTime sat = LocalDateTime.of(2028, 6, 24, 9, 0);
        show(book("+15555550117", sat, "GEARS", true, "P4KD-7WXN"));
        show(book("+15555550163", sat, "FLAT", false, "R8TM-2QHC"));
        show(book("+15555550117", sat.plusMinutes(30), "FLAT", false, "Z3NB-6PFA"));
        show(book("+15555550117", sat.plusHours(1), "BRAKES", false, "C9WJ-4KTR"));
        show(book("+15555550188", LocalDateTime.of(2028, 6, 20, 11, 30), "TUNE_UP", true, "H6QX-8MLD"));
        System.out.println("outbox: " + outbox);
    }
}
Output
booked 2301 P4KD-7WXN at 2028-06-24T09:00
refused: that time was just booked by someone else
booked 2302 Z3NB-6PFA at 2028-06-24T09:30
refused: this phone number already has 2 upcoming bookings
refused: that time has passed
outbox: [CONFIRMATION P4KD-7WXN now, REMINDER P4KD-7WXN at 2028-06-23T18:00, CONFIRMATION Z3NB-6PFA now]

What this code does

The fixed clock is 16:00 UTC, which is noon in the shop's time zone, so every run sees the same now and the same answers. A sealed Result with two record cases makes the caller handle both outcomes, and the switch over it needs no default because the compiler knows the cases are complete. The third booking for the same phone is refused, and only the booking with consent puts a reminder into the outbox, due at 18:00 the evening before.

The order of the checks was a decision, not an accident. A time in the past is refused first because no other answer makes sense; a taken start comes before the limit because a customer whose chosen time is gone should pick another time, not be told about a limit that might not apply to the next one. And every refusal is a sentence the page can show as it is, written with Noemi, who had insisted that error messages say what happened and what to do next.

The real use case differs in one important way: it runs inside a database transaction, and the check that a start is free is not enough by itself. Two customers can both see 09:00 as free and press the button within the same second. The service's check catches almost every case, and the partial unique index from V6 catches the rest, so the transaction fails for the second customer and the page offers them the next free times. The listing shows how the Spring version turns that failure into the same Refused result.

Java Example · BookRepair.java (needs Spring Boot)
@Transactional
public Result book(BookingRequest req) {
    LocalDateTime now = LocalDateTime.now(clock);
    if (!req.start().isAfter(now)) return new Refused("that time has passed");
    if (!slots.isFree(req.start())) return new Refused("that time was just booked by someone else");
    if (limits.enabled() && bookings.countActiveForPhone(req.phone().e164(), now) >= limits.perPhone())
        return new Refused("this phone number already has " + limits.perPhone() + " upcoming bookings");
    try {
        Booking b = bookings.saveAndFlush(Booking.from(req, references.next(), Source.WEB));
        outbox.queue(Messages.confirmation(b), now);
        if (req.remind()) outbox.queue(Messages.reminder(b), reminderTime(b.start()));
        return new Booked(b);
    } catch (DataIntegrityViolationException e) {   // the partial unique index from V6
        return new Refused("that time was just booked by someone else");
    }
}

What this code does

saveAndFlush sends the INSERT immediately, inside the try block, so a violation of the unique index is caught here rather than at commit time after the method has returned. The outbox rows are written in the same transaction as the booking, which is the point of ADR-004: either the booking and its messages are all stored, or none are. The limit is read from configuration, and limits.enabled() is the feature flag from 1.5.0, which the team switched on in staging in this sprint and in production at release.

Finding and canceling

Hamza and Noemi paired on US-03 for two evenings, one typing while the other read the criteria aloud and watched, switching every half hour. Pairing on it was deliberate: canceling touches the security rule of US-03.3, the two-hour rule Tamsin asked for and the waiting list, and it was the story most likely to be built subtly wrong by one person in a hurry.

FindBooking takes the typed reference and phone, normalizes both with the value types from lesson 5, and returns the booking only if both match. If either is wrong, or the reference does not parse, it returns the same empty answer. That uniform answer is the whole of US-03.3: a page that said wrong phone number for a real reference would tell a stranger that the reference exists, and with enough attempts, whose it is.

Java Example
import java.time.*;
import java.util.*;

public class Main {
    record Booking(String reference, String phone, LocalDateTime start, String status, LocalDateTime cancelledAt) {}
    sealed interface Outcome permits CancelConfirmed, TooLate, NotFound, AlreadyCancelled {}
    record CancelConfirmed(LocalDateTime start) implements Outcome {}
    record TooLate(LocalDateTime deadline) implements Outcome {}
    record NotFound() implements Outcome {}
    record AlreadyCancelled(LocalDateTime when) implements Outcome {}

    static final Map<String, Booking> byRef = new HashMap<>();
    static final Duration CUTOFF = Duration.ofHours(2);

    static Optional<Booking> find(String ref, String phone) {
        Booking b = byRef.get(ref.trim().toUpperCase());
        return b != null && b.phone().equals(phone) ? Optional.of(b) : Optional.empty();
    }

    static Outcome cancel(String ref, String phone, LocalDateTime now) {
        Optional<Booking> found = find(ref, phone);
        if (found.isEmpty()) return new NotFound();
        Booking b = found.get();
        if (b.status().equals("CANCELLED")) return new AlreadyCancelled(b.cancelledAt());
        LocalDateTime deadline = b.start().minus(CUTOFF);
        if (now.isAfter(deadline)) return new TooLate(deadline);
        byRef.put(b.reference(), new Booking(b.reference(), b.phone(), b.start(), "CANCELLED", now));
        return new CancelConfirmed(b.start());
    }

    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2028, 6, 24, 10, 30);
        byRef.put("K7QF-29XM", new Booking("K7QF-29XM", "+15555550142", start, "BOOKED", null));
        LocalDateTime eight = LocalDateTime.of(2028, 6, 24, 8, 0);
        System.out.println("US-03.3 wrong phone:      " + cancel("K7QF-29XM", "+15555550199", eight));
        System.out.println("US-03.3 wrong reference:  " + cancel("K7QF-29XN", "+15555550142", eight));
        System.out.println("US-03.2 at 09:00:         " + cancel("K7QF-29XM", "+15555550142", eight.plusHours(1)));
        System.out.println("US-03.1 at 08:00:         " + cancel("k7qf-29xm", "+15555550142", eight));
        System.out.println("US-03.4 looked up again:  " + cancel("K7QF-29XM", "+15555550142", eight.plusMinutes(5)));
    }
}
Output
US-03.3 wrong phone:      NotFound[]
US-03.3 wrong reference:  NotFound[]
US-03.2 at 09:00:         TooLate[deadline=2028-06-24T08:30]
US-03.1 at 08:00:         CancelConfirmed[start=2028-06-24T10:30]
US-03.4 looked up again:  AlreadyCancelled[when=2028-06-24T08:00]

What this code does

Each line of output is labeled with the acceptance criterion it demonstrates, which is how the team's real tests were named. A wrong phone and a wrong reference produce exactly the same NotFound, so the answer reveals nothing about which part was wrong. The two-hour deadline is computed from the start, and the customer who comes back to a booking already canceled is told when, as US-03.4 requires, rather than being told it does not exist.

The boundary of the two-hour rule needed a decision of its own. At 08:30 exactly, two hours before a 10:30 start, may the customer still cancel? The code above uses isAfter, so yes: the deadline itself is allowed and one minute later is not. Tamsin did not mind which way it went, but she wanted the page to state the deadline as a time, cancel online until 8:30 a.m., rather than as a rule the customer had to calculate. Thierry added a test for the exact boundary, because boundaries are where off-by-one mistakes hide.

Java Example · CancelBookingTest.java (needs JUnit and AssertJ)
@Test
@DisplayName("US-03.2 a cancel is allowed at the deadline and refused one minute after it")
void deadlineBoundary() {
    var booking = aBooking().startingAt(saturdayAt(10, 30)).build();
    bookings.save(booking);

    assertThat(cancel.cancel(booking.reference(), booking.phone(), at(saturdayAt(8, 30))))
        .isInstanceOf(CancelConfirmed.class);

    var another = aBooking().startingAt(saturdayAt(11, 0)).build();
    bookings.save(another);
    assertThat(cancel.cancel(another.reference(), another.phone(), at(saturdayAt(9, 1))))
        .isInstanceOf(TooLate.class);
}

What this code does

The display name starts with the criterion's identifier, which is what the traceability check from lesson 2 reads. aBooking is a test data builder that fills every field with a sensible default, so the test states only what matters to it, the start time. at() creates the use case with a fixed clock at the given moment, so the test controls time completely.

The per-phone limit, switched on

US-04's rule had been in the code since version 1.5.0, off by default behind a property. Switching it on was a one-line change in the staging configuration, but the team treated it as a release in its own right, because a limit that misfires stops real customers from booking. Before switching it on in staging, Thierry ran the counting rule over the generated data and over a copy of the real bookings with the names and numbers replaced by stable random tokens, to see how many people the limit would have affected in the spring.

Java Example
import java.time.*;
import java.util.*;
import java.util.stream.*;

public class Main {
    record B(String phoneToken, LocalDate day, String status) {}

    public static void main(String[] args) {
        List<B> spring = new ArrayList<>();
        Random rnd = new Random(3);
        LocalDate d = LocalDate.of(2028, 4, 4);
        for (int i = 0; i < 260; i++) {
            String token = "p" + (rnd.nextInt(20) < 19 ? rnd.nextInt(200) : rnd.nextInt(3));
            String status = rnd.nextInt(10) == 0 ? "CANCELLED" : "BOOKED";
            spring.add(new B(token, d.plusDays(rnd.nextInt(56)), status));
        }
        LocalDate asOf = LocalDate.of(2028, 5, 1);
        Map<String, Long> upcoming = spring.stream()
            .filter(b -> b.status().equals("BOOKED") && b.day().isAfter(asOf))
            .collect(Collectors.groupingBy(B::phoneToken, TreeMap::new, Collectors.counting()));
        Map<Long, Long> histogram = upcoming.values().stream()
            .collect(Collectors.groupingBy(n -> n, TreeMap::new, Collectors.counting()));
        System.out.println("phones by number of upcoming bookings on " + asOf + ": " + histogram);
        long over = upcoming.values().stream().filter(n -> n > 2).count();
        System.out.println("phones that would have hit the limit of 2: " + over + " of " + upcoming.size());
        upcoming.entrySet().stream().filter(e -> e.getValue() > 2)
            .forEach(e -> System.out.println("  " + e.getKey() + " had " + e.getValue()));
    }
}
Output
phones by number of upcoming bookings on 2028-05-01: {1=62, 2=21, 3=1, 4=1, 5=1}
phones that would have hit the limit of 2: 3 of 86
  p0 had 3
  p1 had 4
  p2 had 5

What this code does

The seeded generator stands in for the anonymized spring bookings, with most bookings spread over many phones and a few phones booking often, which is the pattern the real data showed. Grouping by phone token counts each phone's upcoming bookings on May 1, and a second grouping turns those counts into a histogram. Only a handful of phones would have been stopped, and when Odile saw that they were the shop's own test phone and two regular customers who booked for several family members, she asked for one thing: the refusal message should give the shop's phone number, so families could still book by phone.

Reminders at the right time

US-07 said a text the evening before. The team settled the details with Odile at the sprint review: at 18:00 the evening before, in the shop's time zone, only for customers who ticked the box, and only if the booking is still BOOKED when the time comes. That last condition is why reminders are not sent by a timer set at booking time. The outbox row is written when the booking is made, but the sender checks the booking again just before sending, so a booking canceled in the meantime gets no reminder.

The time needed care. A booking for a Tuesday is reminded on Monday at 18:00, when the shop is closed, which is fine for a text. A booking made at 19:00 for the next morning would have a reminder time in the past: the team decided to skip it, since the confirmation text had just been sent. And because the shop's server runs in UTC, the due time is computed in the shop's zone and stored as an instant, so that the switch to and from daylight saving time in March and November can never move a reminder by an hour.

Java Example
import java.time.*;
import java.util.*;

public class Main {
    static final ZoneId SHOP = ZoneId.of("America/New_York");

    static Optional<Instant> reminderDue(LocalDateTime start, Instant bookedAt) {
        ZonedDateTime due = start.toLocalDate().minusDays(1).atTime(18, 0).atZone(SHOP);
        if (!due.toInstant().isAfter(bookedAt)) return Optional.empty();   // too late: the confirmation is enough
        return Optional.of(due.toInstant());
    }

    public static void main(String[] args) {
        Instant bookedJune20 = ZonedDateTime.of(2028, 6, 20, 12, 0, 0, 0, SHOP).toInstant();
        Instant bookedNov3Late = ZonedDateTime.of(2028, 11, 3, 19, 0, 0, 0, SHOP).toInstant();
        Map<String, Object[]> cases = new LinkedHashMap<>();
        cases.put("Saturday Jun 24 09:00", new Object[] {LocalDateTime.of(2028, 6, 24, 9, 0), bookedJune20});
        cases.put("Tuesday Jun 27 15:00", new Object[] {LocalDateTime.of(2028, 6, 27, 15, 0), bookedJune20});
        cases.put("Wednesday Jun 21 10:00", new Object[] {LocalDateTime.of(2028, 6, 21, 10, 0), bookedJune20});
        cases.put("Saturday Nov 4 09:00 (booked Fri 19:00)", new Object[] {LocalDateTime.of(2028, 11, 4, 9, 0), bookedNov3Late});
        cases.put("Tuesday Nov 7 09:00 (after the clocks change)", new Object[] {LocalDateTime.of(2028, 11, 7, 9, 0), bookedNov3Late});
        for (var e : cases.entrySet()) {
            Optional<Instant> due = reminderDue((LocalDateTime) e.getValue()[0], (Instant) e.getValue()[1]);
            System.out.printf("%-46s %s%n", e.getKey(), due.map(i -> "remind at " + i + " UTC = "
                + i.atZone(SHOP).toLocalDateTime() + " local").orElse("no reminder"));
        }
    }
}
Output
Saturday Jun 24 09:00                          remind at 2028-06-23T22:00:00Z UTC = 2028-06-23T18:00 local
Tuesday Jun 27 15:00                           remind at 2028-06-26T22:00:00Z UTC = 2028-06-26T18:00 local
Wednesday Jun 21 10:00                         remind at 2028-06-20T22:00:00Z UTC = 2028-06-20T18:00 local
Saturday Nov 4 09:00 (booked Fri 19:00)        no reminder
Tuesday Nov 7 09:00 (after the clocks change)  remind at 2028-11-06T23:00:00Z UTC = 2028-11-06T18:00 local

What this code does

The due time is built as 18:00 on the previous day in the shop's zone and only then converted to an Instant, so the conversion uses whatever offset applies on that date. The last two lines straddle Sunday, November 5, 2028, when daylight saving time ends: the UTC hour of the reminder changes from 22:00 to 23:00 while the local time stays 18:00. A reminder whose time has already passed when the booking is made returns an empty Optional and is not queued.

The sender is a scheduled job that runs every minute, takes the due rows from the outbox, checks each booking's status and sends through the Notifier port, the same port the API used for confirmations. If the SMS provider fails, the row stays unsent and its attempt count goes up; the job tries again later, waiting longer each time, and gives up after five attempts, raising an alert. Thierry modeled the retry schedule before writing it, to check that five attempts with doubling waits gave up within an hour, well before the appointment.

Java Example
import java.time.*;
import java.util.*;

public class Main {
    static Duration backoff(int attempt) { return Duration.ofMinutes(2L << (attempt - 1)); }   // 2, 4, 8, 16 minutes

    public static void main(String[] args) {
        LocalTime due = LocalTime.of(18, 0);
        boolean[] providerUp = {false, false, false, true};    // fails three times, then works
        LocalTime at = due;
        for (int attempt = 1; attempt <= 5; attempt++) {
            boolean ok = attempt - 1 < providerUp.length && providerUp[attempt - 1];
            System.out.println("attempt " + attempt + " at " + at + ": " + (ok ? "sent" : "provider error"));
            if (ok) break;
            if (attempt == 5) { System.out.println("giving up; alert raised for Leif"); break; }
            at = at.plus(backoff(attempt));
        }
        LocalTime last = due;
        for (int a = 1; a <= 4; a++) last = last.plus(backoff(a));
        System.out.println("if every attempt fails, the fifth is at " + last + " and the job then gives up");
    }
}
Output
attempt 1 at 18:00: provider error
attempt 2 at 18:02: provider error
attempt 3 at 18:06: provider error
attempt 4 at 18:14: sent
if every attempt fails, the fifth is at 18:30 and the job then gives up

What this code does

backoff doubles the wait after each failed attempt by shifting 2 minutes left, giving waits of 2, 4, 8 and 16 minutes. The first run simulates a provider that fails three times and then recovers, so the reminder goes out at 18:14. The second calculation shows the worst case: the fifth attempt is at 18:30 and the job gives up then, long before any morning appointment.

The waiting list

US-08 was built in sprint 4, but its rules belong here with the other use cases. When a start becomes free because of a cancellation, the first customer waiting for that day gets a text offering it, with a link that holds the start for them. If they book it, the offer is finished. If the hold expires, the start goes to the next person waiting, and so on, until someone books it or nobody is left, when it simply becomes free on the website.

The length of the hold was the subject of a long discussion at the sprint 3 review. Too long, and a start freed in the morning could pass unused through several people until it was too late for anyone; too short, and a customer at work could miss it. Odile settled on two hours, cut short so that every hold ends at least two hours before the start, the same deadline as canceling, because a mechanic plans the morning's work by then.

Java Example
import java.time.*;
import java.util.*;

public class Main {
    record Waiting(String name, LocalDateTime joined) {}

    static LocalDateTime holdUntil(LocalDateTime now, LocalDateTime start) {
        LocalDateTime twoHours = now.plusHours(2), lastChance = start.minusHours(2);
        return twoHours.isBefore(lastChance) ? twoHours : lastChance;
    }

    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2028, 7, 22, 13, 30);
        Deque<Waiting> queue = new ArrayDeque<>(List.of(
            new Waiting("Dana", LocalDateTime.of(2028, 7, 18, 12, 4)),
            new Waiting("Marcus", LocalDateTime.of(2028, 7, 19, 20, 40)),
            new Waiting("Jordan", LocalDateTime.of(2028, 7, 21, 9, 15))));
        Map<String, Boolean> answers = Map.of("Dana", false, "Marcus", false, "Jordan", true);
        LocalDateTime now = LocalDateTime.of(2028, 7, 22, 7, 50);      // the 13:30 booking is CANCELLED
        System.out.println("13:30 freed at " + now.toLocalTime());
        while (!queue.isEmpty()) {
            Waiting w = queue.poll();
            LocalDateTime until = holdUntil(now, start);
            if (!until.isAfter(now)) { System.out.println("too late to offer; 13:30 shown as free"); return; }
            System.out.println("offer to " + w.name() + " until " + until.toLocalTime());
            if (answers.get(w.name())) { System.out.println("  " + w.name() + " booked 13:30"); return; }
            System.out.println("  no answer; hold expired");
            now = until;
        }
        System.out.println("nobody left; 13:30 shown as free");
    }
}
Output
13:30 freed at 07:50
offer to Dana until 09:50
  no answer; hold expired
offer to Marcus until 11:30
  no answer; hold expired
too late to offer; 13:30 shown as free

What this code does

The waiting customers are a queue in the order they joined, and each is offered the start in turn. holdUntil returns the earlier of two hours from now and two hours before the start, so the second hold ends at 11:30 rather than 11:50 and the third would not be offered at all. Here Jordan, third in line, never gets the chance, and the start goes back on the website at 11:30, where anyone can still book it.

A state diagram for a waiting-list entry. WAITING moves to OFFERED when a start frees up and this entry is first in line. OFFERED moves to BOOKED if the customer books within the hold, or to EXPIRED when the hold ends, after which the next WAITING entry is offered the start. Any WAITING entry can move to LEFT if the customer leaves the list. A note says that every hold ends at least two hours before the start.
The life of a waiting-list entry.

Jordan's outcome in the example started an argument that Ingrid enjoyed. Was it fair? Jordan had joined last, so being third was fair, but losing the chance because of a rule about the mechanics' planning felt less fair. The team decided it was the right trade-off, because a start held until the last minute and then wasted helped nobody, and they wrote the reasoning into the ADR for the waiting list so that the next team would not have the same argument from scratch.

The waiting list also had a concurrency trap. The offer job and a customer canceling another booking could both try to offer the same freed start at the same moment. The fix was the one the booking API already used: the waiting list entity carries a version column, so the second transaction to change the same entry fails with an optimistic locking error and simply retries, finding that the entry has already been offered.

The sprint review

On Wednesday, June 28, at the sprint 2 review, Odile booked a repair on staging from her own phone, standing in the back room, and then canceled it. It took her a minute and forty seconds to book and twenty seconds to cancel. She had two complaints, and both were about words rather than code. The cancel page had two buttons, Cancel and Keep my booking, and she had pressed Cancel meaning go back; and the confirmation text said Your booking K7QF-29XM is confirmed without saying for when. Noemi rewrote both that evening: the buttons became Yes, cancel this booking and No, keep it, and the text gained the day and time.

Velocity for the first two sprints was 9 and 10 points, a little above the middle of the guess. Odile's Should list moved from unlikely to probable, and the forecast program from lesson 4 now ran on real numbers. The team's retrospective that evening produced one change: Noemi asked that every pull request touching a page include a screenshot on a phone-sized screen, so reviewers would see what customers would see.

Exercises

Try it yourself

The cancellation rule

Complete decide so that it returns NOT_FOUND if the phone does not match, ALREADY_CANCELLED if the status is CANCELED, TOO_LATE if now is after two hours before the start, and CANCELED otherwise. The deadline itself is still allowed.

import java.time.*;

public class Main {
    static String decide(String phone, String givenPhone, String status, LocalDateTime start, LocalDateTime now) {
        return "CANCELLED";
    }

    public static void main(String[] args) {
        LocalDateTime start = LocalDateTime.of(2028, 6, 24, 10, 30);
        System.out.println(decide("+15555550142", "+15555550199", "BOOKED", start, start.minusHours(5)));
        System.out.println(decide("+15555550142", "+15555550142", "CANCELLED", start, start.minusHours(5)));
        System.out.println(decide("+15555550142", "+15555550142", "BOOKED", start, start.minusHours(2)));
        System.out.println(decide("+15555550142", "+15555550142", "BOOKED", start, start.minusMinutes(119)));
        System.out.println(decide("+15555550142", "+15555550142", "BOOKED", start, start.minusHours(3)));
    }
}

Try it yourself

When is the reminder due?

Complete due so that it returns 18:00 on the day before the start, or null if that time is not after bookedAt. Print each result as in the expected output (none for null).

import java.time.*;

public class Main {
    static LocalDateTime due(LocalDateTime start, LocalDateTime bookedAt) {
        return start;
    }

    public static void main(String[] args) {
        LocalDateTime[][] cases = {
            {LocalDateTime.of(2028, 6, 24, 9, 0), LocalDateTime.of(2028, 6, 20, 12, 0)},
            {LocalDateTime.of(2028, 6, 27, 15, 0), LocalDateTime.of(2028, 6, 26, 17, 59)},
            {LocalDateTime.of(2028, 6, 27, 15, 0), LocalDateTime.of(2028, 6, 26, 18, 0)},
            {LocalDateTime.of(2028, 7, 1, 10, 0), LocalDateTime.of(2028, 6, 30, 19, 30)}};
        for (LocalDateTime[] c : cases) {
            LocalDateTime d = due(c[0], c[1]);
            System.out.println(c[0] + " booked " + c[1] + " -> " + (d == null ? "none" : d));
        }
    }
}

Common mistakes

  • MistakePutting business rules in controllers or templates.

    InsteadKeep rules in the domain and use cases, so every adapter, including the REST API, obeys them.

  • MistakeRelying only on a check that a start is free.

    InsteadBack it with the database constraint and turn its violation into the same friendly refusal.

  • MistakeTelling a visitor which part of a lookup was wrong.

    InsteadGive the same answer for any mismatch, so the page reveals nothing about real bookings.

  • MistakeSending messages directly inside the booking transaction.

    InsteadWrite them to an outbox in the transaction and send them from a job that retries with backoff.

  • MistakeComputing reminder times in the server's zone.

    InsteadBuild local times in the shop's zone and convert them to instants, so daylight saving time cannot shift them.

  • MistakeHolding a freed start until it is too late to use.

    InsteadLimit each offer and end every hold before the planning deadline.

Summary and key terms

  • Sprint 2 built the use cases between the pages and the domain: booking, finding and canceling, with the reminders and, in sprint 4, the waiting list.
  • Rules about time and slots live in the domain, rules about what customers may do live in use cases, and the site adapter contains none, so the REST API obeys them too.
  • BookRepair checks the start, availability and the per-phone limit in a deliberate order, returns a sealed Result, writes confirmation and reminder rows to the outbox in the same transaction, and turns a unique-index violation into the same refusal.
  • FindBooking and CancelBooking give the same answer for any mismatch, allow canceling up to two hours before the start including the exact deadline, and tell a returning customer when a booking was canceled.
  • The per-phone limit was checked against spring data before being switched on.
  • Reminders are due at 18:00 the evening before in the shop's zone, skipped if already past, sent by a retrying job that rechecks the booking.
  • The waiting list offers a freed start to each waiting customer in turn, with holds that end two hours before the start.
Application layer
The use cases that coordinate domain rules and ports for one action of a user.
Use case
One thing a user can do with the system, such as canceling a booking, with its rules.
Sealed interface
A Java interface that lists the only classes allowed to implement it.
Fixed clock
A Clock that always returns the same time, used to make code and tests deterministic.
Uniform response
Giving the same answer for every kind of failed lookup so nothing is revealed.
Boundary test
A test at the exact edge of a rule, and just beyond it.
Outbox
A table of messages written in the same transaction as the change that causes them, sent later by a job.
Exponential backoff
Waiting longer after each failed attempt, often doubling the wait.
Hold
A time-limited reservation of a start for one waiting customer.
Optimistic locking
Detecting a conflicting update by checking a version column when writing.

Practice problems

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

  1. Why is the availability check made before the per-phone limit?

    Show answer

    A customer whose chosen time is gone should choose another time, not be told about a limit that may not apply.

  2. Why does FindBooking give the same answer for a wrong phone and a wrong reference?

    Show answer

    Different answers would tell a stranger that a reference exists.

  3. Why does the reminder sender check the booking again before sending?

    Show answer

    The booking may have been canceled since the outbox row was written.

  4. Why is the reminder time built in the shop's zone and converted to an instant?

    Show answer

    So the conversion uses the offset of that date and daylight saving changes cannot shift the local time.

  5. Why can a waiting customer lose a freed start without being offered it?

    Show answer

    Holds end two hours before the start, so late in the morning there is no time left to offer it.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz