LOW-LEVEL DESIGN · MODELING AND UML · METHOD · 21 OF 48

From Requirements to Classes: Object-Oriented Design Step by Step

A repeatable method for the first fifteen minutes of any low-level design round: clarify the requirements, underline nouns to get candidate classes, drop the weak ones, turn verbs into methods, give each rule to the class that owns the data, add relationships, then check with one flow. Worked end to end on a gym class booking system in Java.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 15

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 152 lines, with a small main() demo. Save it as RequirementsToClassesDemo.java, then run javac RequirementsToClassesDemo.java && java RequirementsToClassesDemo.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * Gym class booking, designed from the requirements in this lesson.
 * Entities hold their own rules; BookingDesk only coordinates.
 */
public class RequirementsToClassesDemo {

    /** "basic" and "premium" became values of one enum, each knowing its own limit. */
    enum MembershipPlan {
        BASIC(3), PREMIUM(Integer.MAX_VALUE);

        private final int weeklyLimit;

        MembershipPlan(int weeklyLimit) {
            this.weeklyLimit = weeklyLimit;
        }

        boolean allowsAnother(int alreadyBooked) {
            return alreadyBooked < weeklyLimit;
        }
    }

    record Member(String name, MembershipPlan plan) { }

    record Trainer(String name) { }

    record Booking(Member member, String sessionName) { }

    /** The thing being booked. Owns capacity, attendees and the waitlist. */
    static final class GymSession {
        private final String name;
        private final Trainer trainer;
        private final int capacity;
        private final Set<Member> attendees = new LinkedHashSet<>();
        private final Deque<Member> waitlist = new ArrayDeque<>();

        GymSession(String name, Trainer trainer, int capacity) {
            this.name = name;
            this.trainer = trainer;
            this.capacity = capacity;
        }

        /** Returns a booking, or empty if the member was put on the waitlist. */
        synchronized Optional<Booking> book(Member m) {
            if (attendees.contains(m) || waitlist.contains(m)) {
                throw new IllegalStateException(m.name() + " already booked or waiting");
            }
            if (attendees.size() == capacity) {
                waitlist.addLast(m);
                return Optional.empty();
            }
            attendees.add(m);
            return Optional.of(new Booking(m, name));
        }

        /** Frees the spot and promotes the first waiting member in the same lock. */
        synchronized Optional<Booking> cancel(Member m) {
            if (!attendees.remove(m)) {
                waitlist.remove(m);
                return Optional.empty();
            }
            Member next = waitlist.pollFirst();
            if (next == null) {
                return Optional.empty();
            }
            attendees.add(next);
            return Optional.of(new Booking(next, name));
        }

        String describe() {
            return name + " with " + trainer.name() + ": " + attendees.size() + "/" + capacity
                    + " booked, waiting " + waitlist.size();
        }
    }

    static final class MemberNotifier {
        void tell(Member m, String message) {
            System.out.println("  notify " + m.name() + ": " + message);
        }
    }

    /** Coordinates a booking across entities. Holds no business rules of its own. */
    static final class BookingDesk {
        private final MemberNotifier notifier;
        private final Map<Member, List<Booking>> thisWeek = new HashMap<>();

        BookingDesk(MemberNotifier notifier) {
            this.notifier = notifier;
        }

        synchronized void book(Member m, GymSession session) {
            int already = thisWeek.getOrDefault(m, List.of()).size();
            if (!m.plan().allowsAnother(already)) {
                notifier.tell(m, "weekly limit reached on the " + m.plan() + " plan");
                return;
            }
            Optional<Booking> booking = session.book(m);
            if (booking.isPresent()) {
                record(booking.get());
                notifier.tell(m, "booked " + booking.get().sessionName());
            } else {
                notifier.tell(m, "class full, you are on the waitlist");
            }
        }

        synchronized void cancel(Member m, GymSession session) {
            thisWeek.getOrDefault(m, new ArrayList<>())
                    .removeIf(b -> b.sessionName().equals(session.name));
            session.cancel(m).ifPresent(promoted -> {
                record(promoted);
                notifier.tell(promoted.member(), "a spot opened, you are in " + promoted.sessionName());
            });
        }

        private void record(Booking b) {
            thisWeek.computeIfAbsent(b.member(), k -> new ArrayList<>()).add(b);
        }
    }

    public static void main(String[] args) {
        BookingDesk desk = new BookingDesk(new MemberNotifier());
        Trainer neha = new Trainer("Neha");

        Member ria = new Member("Ria", MembershipPlan.BASIC);
        Member arjun = new Member("Arjun", MembershipPlan.PREMIUM);
        Member kabir = new Member("Kabir", MembershipPlan.BASIC);

        System.out.println("Weekly limit on the basic plan:");
        for (String day : List.of("Mon yoga", "Tue yoga", "Wed yoga", "Thu yoga")) {
            desk.book(ria, new GymSession(day, neha, 10));
        }

        System.out.println("Full class and waitlist:");
        GymSession spin = new GymSession("Fri spin", neha, 1);
        desk.book(arjun, spin);
        desk.book(kabir, spin);
        System.out.println("  " + spin.describe());

        System.out.println("Cancel promotes the first in line:");
        desk.cancel(arjun, spin);
        System.out.println("  " + spin.describe());
    }
}

Notes

The requirements

Here is the problem. Members book a spot in a fitness class. Each class has a trainer, a start time and a capacity. When a class is full, members can join a waitlist. If someone cancels, the first waiting member gets the spot and is told about it. Basic plan members can book at most three classes a week, and premium members have no limit. Read it twice before you design anything.

Gym class booking
  • Members book a spot in a
  • fitness class. Each class has
  • a trainer, a start time and a
  • capacity. When a class is
  • full, members can join a
  • waitlist. If someone cancels,
  • the first waiting member gets
  • the spot and is told. Basic
  • plan members may book at most
  • three classes a week; premium
  • members have no limit.

Step 1: clarify

Step one, clarify. Ask the questions whose answers change the classes. Can a member book the same class twice? No. Does a waitlist place count toward the weekly limit? Only once it turns into a real booking. Are payments and cancellation deadlines in scope? Not today. One gym, but several front desks working at once, so we must think about threads. Write the answers down. They become your rules and your test cases.

Questions worth asking
  • can a member book the same
  • class twice? no
  • does a waitlisted spot count
  • toward the weekly limit?
  • only once it is confirmed
  • cancel deadline? out of scope
  • payments? out of scope
  • one gym or many? one
  • many front desks at once? yes

Step 2: nouns

Step two, underline the nouns. Member, spot, fitness class, trainer, start time, capacity, waitlist, plan, basic and premium, week, limit, gym, front desk, and the app that is implied. Each noun is only a candidate. Some will become classes, some will become fields of other classes, and some will disappear. The point of this step is to make sure nothing important is missed before you start filtering.

Candidate nouns
  • member, spot, fitness class,
  • trainer, start time,
  • capacity, waitlist, plan,
  • basic plan, premium plan,
  • week, limit, gym, front desk,
  • app (implied)
  • nouns hint at classes
  • and fields; they are not
  • the answer yet

Step 3: filter

Step three, filter. A noun with no behaviour and one value is a field, not a class: start time and capacity belong to the class session. A spot is not an object, it is capacity minus bookings. The week is a rule about dates. There is only one gym, so it adds nothing. The app is outside our model. Basic and premium are values of one enum. We keep Member, GymSession, Trainer, Booking and MembershipPlan. We call it GymSession because class is a Java keyword.

Keep or drop
  • start time, capacity: fields
  • of the class, not classes
  • spot: just capacity minus
  • bookings, a number
  • week: a date range rule
  • gym: only one, so skip it
  • app: outside the model
  • basic, premium: enum values
  • keep: Member, GymSession,
  • Trainer, Booking, Plan

Core entities

Now find the core. In almost every booking problem, there are two central entities: the thing being booked, here a GymSession, and the record that someone booked it, here a Booking. Everything else hangs off them. A member holds a plan. A session is led by a trainer. Getting these two right is most of the design. Parking spots and tickets, seats and reservations, rooms and stays all follow the same shape.

Step 4: verbs

Step four, the verbs. Book, cancel, join the waitlist, get the spot, be told, and may book at most three. Each one becomes a method. Book and cancel, add to waitlist, promote next, notify, and allows another booking. The verb only tells you what happens. The harder and more important question is which class should own each method. That is the next step, and where good designs and poor designs split.

Verbs to methods
  • book a spot -> book()
  • cancel -> cancel()
  • join waitlist -> addToWaitlist()
  • get the spot -> promoteNext()
  • is told -> notify()
  • may book at most three
  • -> allowsAnother()
  • a verb tells you WHAT;
  • the owner is the next step

Step 5: responsibilities

Step five, responsibilities. The simple rule is: give each job to the class that already has the data it needs. Is there room? The session knows its capacity and bookings, so it decides. Who is next in line? The session owns its waitlist. What is the weekly limit? The plan knows its own number. Then one service, BookingDesk, coordinates a whole booking from start to end, without holding the rules itself.

Who owns which rule
  • is there room?
  • GymSession: has capacity
  • and its bookings
  • who is next in line?
  • GymSession: owns waitlist
  • weekly limit?
  • MembershipPlan: knows the
  • number for each plan
  • run the whole booking?
  • BookingDesk (a service)

Step 6: relationships

Step six, connect them and add numbers. Each member has exactly one plan. Each session is led by one trainer and holds between zero and capacity bookings, plus an ordered waitlist of members. Each booking points to one member and one session. The booking desk uses the sessions and a notifier. That is a class diagram. Notice the sizes are small. A first design should fit in about seven boxes.

Step 7: code it

Step seven, write the core code. GymSession's book method checks the duplicate rule and the capacity rule, because it owns that data. If the session is full, the member goes to the end of the waitlist. Otherwise the member is added and a Booking is returned. The method is synchronized, so two front desks booking the last spot at the same moment cannot both get it.

GymSession owns its rules
synchronized Optional<Booking>
    book(Member m) {
  if (attendees.contains(m)) throw ...;
  if (attendees.size() == capacity) {
    waitlist.addLast(m);
    return Optional.empty();
  }
  attendees.add(m);
  return Optional.of(new Booking(m, name));
}

Step 8: test a flow

Step eight, test the design by walking one scenario. Ria is on the basic plan and already has three bookings this week. The desk asks Ria's plan whether a fourth is allowed. The basic plan says no, so the desk refuses before touching any session. Walking a flow like this, out loud, quickly shows a missing method, a rule in the wrong place, or a class nobody uses.

The cancel flow

Now the trickier flow. The evening spin class is full, and Kabir is first on the waitlist. Arjun cancels. The desk calls cancel on the session. The session removes Arjun, takes Kabir off the front of its waitlist, and creates a booking for him in the same step. The desk then asks the notifier to tell Kabir he is in. Because the session does all of this inside one lock, no new booking can steal the freed spot first.

Common mistakes

Watch for the common mistakes. One god class, a gym manager, that does everything. Or the opposite, a class for every noun, like Capacity and StartTime. Data classes with only getters, while every rule sits in one huge service. Reaching for design patterns before the entities are clear. And skipping the clarifying questions. The fix is the same each time: rules live with the data they use, and services only coordinate.

Watch out for
  • GymManager does everything
  • classes for every noun
  • (Capacity, StartTime)
  • data classes with all the
  • rules in a service
  • patterns before entities
  • no clarifying questions
  • fix: rules live with data,
  • services coordinate

Say it like this

In the interview, narrate the method. Say: the core entities are GymSession and Booking. Capacity and the waitlist live in GymSession because it owns that data. The weekly limit lives in the membership plan. BookingDesk coordinates the flow and sends notifications. In under a minute, the interviewer knows your classes, your reasons, and where every rule lives. Then you can start coding with confidence.

In the interview
  • "The core entities are
  • GymSession and Booking.
  • Capacity and waitlist live
  • in GymSession because it
  • owns that data. The weekly
  • limit lives in the plan.
  • BookingDesk coordinates and
  • sends notifications."

Interview questions

How do you identify classes from a problem statement?

Underline the nouns to get candidates, then filter: nouns with a single value become fields, synonyms merge, vague or out-of-scope things are dropped, and fixed kinds become enums. What remains, usually five to eight types, are your classes.

How do you decide which class a method belongs to?

Give the responsibility to the class that already has the information needed to do it, often called the information expert idea. For example, the session that owns capacity and attendees decides whether a booking fits, rather than a separate manager reading its data.

When should a noun be a field instead of a class?

When it is a single value with no behaviour or rules of its own, like a start time or a capacity number. Make it a small class or record only if it carries rules or several related values, such as Money or a date range.

What questions should you ask before designing?

Ask about the rules that change the classes: limits, duplicates, what happens when something is full, cancellations, what is out of scope such as payments, and whether many users or threads act at the same time. Write the answers down as rules and test cases.

What is a god class and how do you avoid it?

A single class, often named Manager or System, that holds most of the data and all of the rules. Avoid it by moving each rule to the entity that owns its data and keeping services thin, coordinating calls between entities.

How do you check that a class design is good before coding everything?

Walk the main scenarios through the classes, out loud or as a sequence diagram. Missing methods, rules in the wrong class, unclear ownership and classes nobody calls become obvious quickly.

Why use services if entities hold the rules?

Some steps involve several entities, like checking a member plan, booking a session and notifying someone. A thin service coordinates that flow and handles cross-cutting concerns, while each entity keeps the rules about its own data.

Should you start with design patterns?

No. Identify entities, responsibilities and relationships first. Patterns such as Strategy or Observer then appear naturally where a rule may vary or where several parties need updates, and you can justify them from the requirements.