Skip to content
Ameen Abozaid
PublishedBEG-028-L01

From requirements to classes: worked example

  • Lesson 1 of 5
  • 12 min read
  • Beginner
On This Lesson 11 topics

Lesson Overview

Up to now you have learned the pieces of object-oriented programming: classes, encapsulation, inheritance, polymorphism, interfaces, associations, and packages. This module is about using them together. The hardest step is the first one: someone hands you a paragraph of plain English and you must decide what the classes are.

This lesson walks through that step on one small example, a library that lends books. You will underline nouns and verbs, sort them into classes, fields, and behaviors, write down the rules as invariants, choose relationships and multiplicities, and sketch a first diagram. We use the staffing a small shop picture for the whole module: a design is a decision about who works at the shop, and each job should go to the person who already has the tools and information for it. This lesson decides who works there. The next lesson decides who does which job.

This lesson builds on BEG-020 and BEG-021 (classes, invariants), BEG-025 (relationships and UML), and BEG-024 (interfaces). The Java in this lesson was compiled and run with JDK 21.

Learning Objectives

By the end of this lesson you will be able to:

  • Underline the nouns, verbs, and rules in a written description.
  • Sort nouns into candidate classes, fields, and things outside the system.
  • Turn rules in the text into invariants that a class guarantees.
  • Choose relationships (has-a, is-a, uses) and multiplicities between your classes.
  • Sketch a small UML class diagram and treat it as a first draft.
  • Explain why the simplest working design is the right starting point.

Written Explanation

Step 1: read the requirements and underline

Here is our description:

A library lends books to members. Each loan has a due date. Late loans pay a fine. A member may hold at most two books at a time.

Read it twice. On the second pass, mark three kinds of words.

  • Nouns are candidates for classes or fields: library, book, member, loan, due date, fine.
  • Verbs are candidates for behaviors: lends, pay.
  • Rules are sentences with "must", "at most", "each", "only": "each loan has a due date", "at most two books".

The word candidates matters. Underlining gives you a list to think about, not a list to type in. This is a common starting technique in object-oriented design; the course scripts for this module use it, and we did not find a primary source that defines it formally, so treat it as a practical habit rather than a rule.

Step 2: sort the nouns

Ask three questions of each noun.

  1. Does it have behavior or rules of its own? Then it is probably a class.
  2. Is it just a value that describes something else? Then it is probably a field.
  3. Is it outside the system, or the whole system itself? Then it may need no class at all.
NounVerdictReason
BookClassHas a title and an identity; later it will know if it is lent
MemberClassHas a name and a loan limit
LoanClassLinks a member to a book and carries a due date and rules
due dateField of LoanA value, not a thing with behavior
fineMethod of Loan for nowA calculation on a loan; a class only if rules grow
libraryMaybe a classCoordinates lending; we will decide in the next lesson

Not every noun becomes a class. A noun that becomes a class too early adds files and arrows and gives you more to keep consistent.

Step 3: write the rules as invariants

From BEG-021 you know an invariant is a rule that an object guarantees is always true. The text already contains some.

Rule in the textInvariantWhere it is enforced
"Each loan has a due date"A loan always has a due date, a member, and a bookLoan constructor
"At most two books"A member never holds more than two loansMember
(implied)A book cannot be lent to two people at onceBook

The third row is not written in the text, it is implied. Good modeling includes asking about implied rules: "Can two members hold the same book?" Ask the person who wrote the requirements. Guessing silently is how designs end up wrong.

Step 4: choose relationships and multiplicities

Use the vocabulary from BEG-025.

  • A member has many loans over time: association, Member 1 --- * Loan.
  • Each loan is for one book: Loan * --- 1 Book. Over time a book appears in many loans, but at any moment at most one is active.
  • A library holds books and members. Whether the library owns them (composition) or just keeps references (aggregation) is a decision for later, and for a first sketch aggregation is enough.
  • No is-a is needed so far. Do not invent one.
text
Library 1 ◇------ * Book
Library 1 ◇------ * Member
Member  1 --------- * Loan
Loan    * --------- 1 Book

Step 5: sketch, then expect to revise

Draw only class names, the few members that matter, relationship lines, and multiplicities. As BEG-025 taught, a sketch is a conversation tool: leaving details out is the skill. Your first sketch will be wrong somewhere. Writing code against it or showing it to a teammate is how you find out where.

Step 6: start with the simplest design that works

A beginner's reflex is to build abstract class Item, class Book extends Item, class Dvd extends Item, and an interface for every service. Nothing in the text asks for that. The text mentions books only. Add an interface or a superclass when a real variation appears, such as "the library also lends DVDs with a different loan period". Until then it is guessing, and a wrong guess costs more than a late change: this is premature inheritance, one of this module's common mistakes.

Examples

Example 1: a coffee loyalty card (simple)

A café gives each customer a card. Every tenth coffee is free.

  • Nouns: café, customer, card, coffee. Rule: every tenth coffee is free.
  • The café is the system itself and needs no class. A coffee is an event we count, so it is a number on the card, not a class.
  • Result: Customer and LoyaltyCard, with LoyaltyCard holding stamps and the invariant "stamps is between 0 and 9". Two classes and one invariant are a complete first design.

Example 2: the library skeleton in code (practical)

Here are the classes from our sorting table, with the first invariant enforced in the Loan constructor. Fine and loan limit come in the next lessons.

java
class Book {
    private final String title;
    Book(String title) { this.title = title; }
    String title() { return title; }
}

class Member {
    private final String name;
    Member(String name) { this.name = name; }
    String name() { return name; }
}

class Loan {
    private final Member member;
    private final Book book;
    private final int dueDay;

    Loan(Member member, Book book, int dueDay) {
        if (member == null || book == null) {
            throw new IllegalArgumentException("a loan needs a member and a book");
        }
        this.member = member;
        this.book = book;
        this.dueDay = dueDay;
    }

    String describe() {
        return member.name() + " has " + book.title() + ", due on day " + dueDay;
    }
}

public class Main {
    public static void main(String[] args) {
        Loan loan = new Loan(new Member("Lina"), new Book("Dune"), 14);
        System.out.println(loan.describe());
        try {
            new Loan(null, new Book("Dune"), 14);
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }
    }
}
text
Lina has Dune, due on day 14
rejected: a loan needs a member and a book

For simplicity the due date is a day number, an int. A date class would be a later refinement, and nothing in the design depends on it. The three classes are all in one file only for this demo; in your project, each would be its own file in a package, as BEG-027 taught.

Example 3: a course platform with unclear requirements (realistic)

Students enroll in courses. A course has lessons. Students who finish all lessons receive a certificate. Teachers publish courses.

Underline: student, course, lesson, certificate, teacher, enroll, finish, receive, publish.

  • Classes: Student, Course, Lesson, Teacher. Enrollment is not in the text as a noun but "students enroll in courses" is a many-to-many link with its own facts (when, which lessons are done), so it earns a class, like Loan in the library.
  • Certificate: a class or just a yes/no answer from Enrollment.isComplete()? The text does not say if it has a number, a date, or a printed form. This is a question for the requirements author, not for guessing. Start with the method and promote it to a class if the answer is yes.
  • Lesson belongs to its course and ends when the course ends: that is composition, Course 1 ◆--- * Lesson.
  • Unanswered: can a teacher unpublish? Can a course have several teachers? Write them as open questions beside the diagram.

A good first design is short, and it ends with a list of questions.

Backend Insight

In a backend service, this modeling step produces the domain model: the classes that hold the business rules. Later modules will connect them to a database and to web endpoints, but the order matters. A team that designs the database tables or the URLs first often ends up with classes that only mirror them and contain no behavior. This is the anemic style you will meet again in the next lessons. Getting the domain classes and their invariants right first means the rest of the system has a stable center. A domain model is, by one common definition, a conceptual model of the problem area that captures both data and behavior, and is kept free of technology details such as databases.

Common Mistakes

Mistake 1: Turning every noun into a class

  • Incorrect: a class DueDate with one int field and no behavior.
  • Correct: dueDay is a field of Loan. Create the class only when the value gets rules of its own.

Mistake 2: Starting with inheritance

  • Incorrect: abstract class LibraryItem with one subclass Book and nobody asking for others.
  • Correct: one Book class. Introduce a supertype when the second real kind arrives.

Mistake 3: Ignoring the verbs and rules

If you only collect nouns, you get classes with fields and no behavior. Verbs and rules tell you what each class must do and guarantee.

Mistake 4: Guessing instead of asking

An unstated rule such as "can a member renew a loan?" changes the design. Write it as an open question, and ask.

Mistake 5: Treating the first sketch as final

The diagram is a draft. Changing it after the first scenario you walk through is a sign of progress, not of failure.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

A1. What are the three kinds of words you mark in a requirements text, and what does each become in a design?

Show solution A1

A1. Nouns become candidate classes or fields, verbs become candidate behaviors (methods), and rules become invariants a class must guarantee.

A2. In "A gym has members; each member has a monthly fee", which of Gym, Member, fee is most likely a field rather than a class? Why?

Show solution A2

A2. fee. It is a value that describes a member and has no behavior of its own so far. Gym is the system itself, and Member has an identity and rules.

A3. Write the multiplicity for each side: "A teacher teaches many courses; a course has exactly one teacher."

Show solution A3

A3. Teacher 1 --- * Course. Read from the teacher: one teacher, many courses. Read from the course: exactly one teacher (written 1).

Level B: Application

B1. Read: "A bike-sharing company has stations. Each station has docks. Riders unlock a bike from a dock and return it to any dock. A bike can be in only one place at a time." List candidate classes, one behavior, and two invariants.

Show solution B1

B1. Candidates: Station, Dock, Rider, Bike. Behavior: a dock can release a bike, or a rider can unlock a bike. Invariants (any two): a bike is in at most one dock at a time; a dock holds at most one bike; a rider cannot unlock a second bike while holding one (only if the owner confirms this rule, so it is an open question).

B2. In B1, which noun is in the text but probably should not be a class, and which concept is not a noun in the text but may deserve one? Explain.

Show solution B2

B2. "Company" is the system, not a class we need. "Unlock" or "ride" is a verb, but the period between unlock and return has its own facts (start dock, end dock, times), so a Ride class is probably worth having. It resembles Loan.

B3. Draw the text diagram (with multiplicities) for your B1 classes.

Show solution B3

B3.

text
Station 1 ◆--- * Dock
Dock    1 --------- 0..1 Bike
Rider   1 --------- * Ride
Ride    * --------- 1 Bike

Any consistent diagram is acceptable if the multiplicities agree with your invariants.

Level C: Challenge

C1. A colleague's first design for the library has abstract class Person, Member extends Person, Librarian extends Person, and abstract class Media with Book extends Media. The requirements mention neither librarians nor other media. Say what is wrong and what you would build instead.

Show solution C1

C1. Nothing in the text asks for Person, Librarian, or Media. That is premature inheritance: extra classes and arrows now, with no variation they support. Build Member and Book, plus Loan. Add Media when the library really lends a second kind of item with different rules.

C2. Write three questions you would ask the author of this text before finishing a design: "Customers place orders. Orders contain products. Orders are delivered."

Show solution C2

C2. Examples: Can an order be changed after it is placed? Can one product appear in several lines of an order? What does "delivered" involve, and does the system track the courier? Can an order be cancelled, and by whom?

Mini Challenge

Pick a system you know (a school timetable, a pharmacy, a football league) and write a short description of three to four sentences with at least one rule. Then produce:

  1. The nouns and verbs you underlined.
  2. A table with each noun as class, field, or not needed, with a reason.
  3. Two invariants and where each is enforced.
  4. A text diagram with multiplicities.
  5. Two open questions for the author.

Check your work: you did not create a superclass, and every class has at least one behavior or invariant.

Summary & Next Lesson

Key takeaways

  • Underline nouns, verbs, and rules; they are candidates, not decisions.
  • Nouns with behavior or rules become classes; plain values become fields.
  • Write each rule as an invariant and decide which class guarantees it.
  • Choose relationships and multiplicities, sketch lightly, and expect to revise.
  • Start with the simplest design. Add interfaces and inheritance only when a real variation appears.

Next lesson

You now know who works at the shop. The next lesson, "Assigning responsibilities", decides who does which job: how to place each behavior in the class that already has the information to do it.

Self-check

  1. What do verbs and rules in a description become?
  2. Is every noun a class? Give one example that is not.
  3. Why is an implied rule dangerous?
  4. In Member 1 --- * Loan, how many loans can a member have?
  5. When should you introduce a superclass or interface?
Show answers
  1. Verbs become candidate behaviors; rules become invariants.
  2. No. A due date is usually a field of a loan, not a class.
  3. It is easy to miss, so the design silently allows something the business forbids. Ask about it.
  4. Any number (zero or more); a loan belongs to exactly one member.
  5. When a real variation exists, such as a second kind of item with different rules, not before.

References

  • Wikipedia, Domain model. Supports the description of a domain model as a conceptual model capturing data and behavior in the vocabulary of the domain, without technology details. The page does not describe the noun/verb technique.
  • Wikipedia, Class-responsibility-collaboration card. Supports the idea of deciding what each class is responsible for and with whom it cooperates; a brainstorming tool for early design.
  • Not verified against a primary source: the noun/verb underlining technique (taken from this course's module notes) and the claim that the first design should be the simplest that works (common design advice).

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.