CSE Roadmap

Common tier · about 2 hours · 7 parts

Part 3 of 7 · 1 min read

Small methods

One method, one job, about ten lines.

A short method is easy to read, test and change. A rough guide: if a method does not fit on a screen, or has two jobs joined by "and", split it.

Compare two versions of one check:

// Hard to read
boolean ok(Booking b, Room r, TimeSlot s) {
    return b.isActive() && b.room().equals(r) && b.slot().overlaps(s);
}

// Reads like the rule
boolean blocks(Booking existing, Room room, TimeSlot slot) {
    return existing.isActive()
        && existing.room().equals(room)
        && existing.slot().overlaps(slot);
}

The second name says the rule: an existing booking blocks a new one when it is active, in the same room and overlapping. Better still, the check can live on Booking as blocks(room, slot), so the service loop reads if (b.blocks(room, slot)).

Other habits: return early on bad input, keep nesting to two levels, and avoid methods with more than three parameters. When there are many, group them into a record.

Check yourself: 1. What is the rule for splitting a method? 2. Where could the blocks check live instead? 3. What can replace many parameters?