Find a course

Module 5: Patterns and Real-World DesignLesson 12 of 1215 min

Modeling a System with Objects

Turn requirements into classes with noun and verb analysis, read UML class diagrams, and design objects that are easy to unit test with injected fakes.

Step 1 of 13Learn

From a paragraph of requirements to classes

Here's a short specification for a library system:

"Members borrow books. Each book has a title, an author and several physical copies. A member may have at most five loans at a time. A loan lasts 21 days; returning a copy late adds a fine of $0.25 per day."

A simple starting technique is noun and verb analysis:

  • Nouns are candidate classes or fields: member, book, title, author, copy, loan, fine, day.
  • Verbs are candidate methods: borrow, return, add a fine.

Then refine. "Title" and "author" are simple values, so they become fields of Book. "Copy" deserves its own class, because the library owns several copies of one book and each copy can be on loan separately. "Loan" connects a member to a copy with a due date, and it is where late fines get calculated. "Day" is just a number of days.

A first model:

  • Book: title, author, a list of Copy objects.
  • Copy: a barcode, its book, and whether it's available.
  • Member: name, current loans; canBorrow() enforces the five-loan limit.
  • Loan: member, copy, due date; fineOn(returnDate) computes the late fee.

Notice where each rule landed: the five-loan limit lives in Member because it's about the member's loans; the fine lives in Loan because it depends on the loan's due date. Put each rule in the class that owns the data it needs. That guideline, sometimes called "information expert", is the noun-verb method's most useful partner.

Step 2 of 13Practice · Work it out

Using the library rules above, a copy is returned 30 days after it was borrowed. How much is the late fine in dollars?

Step 3 of 13Practice · Diagram

Where each library rule lives

Which class should enforce the five-loan limit?

Tap the shape that answers the question, then press Check.

Where each library rule livesHierarchy diagram: Library model, Book, Copy, Member, Loan.Library modelBookCopyMemberLoan
Library model
Book

title, author, a list of copies.

Copy

barcode, its book, available or not.

Member

canBorrow(): at most five loans. The rule uses the member's own loans.

Loan

dueDate, fineOn(returnDate): $0.25 per late day. The rule uses the loan's due date.

Step 4 of 13Learn

Reading a UML class diagram

Teams often sketch object models with UML class diagrams (Unified Modeling Language). Each class is a box with three sections: the name, the fields, and the methods. A - marks a private member and a + a public one.

Lines between boxes show relationships:

  • Association: a plain line. One class knows about another (a loan refers to a member).
  • Multiplicity: numbers at the ends of a line. 1 means exactly one, * means any number, 0..5 means up to five. "One member has 0..5 loans" is written with 1 near Member and 0..5 near Loan.
  • Inheritance (generalization): a line with a hollow triangle pointing at the parent.
  • Aggregation: a hollow diamond at the "whole" end. The parts can exist on their own (a library has books, but a book can move to another library).
  • Composition: a filled diamond. The parts live and die with the whole (an order's line items don't exist without the order).
  • Interface implementation: a dashed line with a hollow triangle.

Diagrams are a thinking and communication tool, not a contract. A quick whiteboard sketch that captures the main classes and their relationships is worth far more than a perfect diagram nobody updates. Many teams draw them before a design discussion and throw them away afterwards.

UML class diagram: a Library aggregates many Book objectsLibrary- name: string- books: Book[]+ add(book)+ findByAuthor(a)Book- title: string- author: string+ isAvailable()1*

Step 5 of 13Practice · Match the pairs

Match each UML notation to its meaning.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Hollow triangle on a solid line
  2. Filled diamond
  3. Hollow diamond
  4. 0..5 at one end of a line
  5. A - before a field name

Step 6 of 13Learn

Designing objects you can test

Good object-oriented design and easy testing go hand in hand. A unit test checks one class in isolation: create an object, call a method, check the result.

// A tiny test without any framework
const loan = new Loan({ dueDate: day(21) });
console.assert(loan.fineOn(day(30)) === 2.25);
console.assert(loan.fineOn(day(20)) === 0);

Some classes are hard to test because they reach out to the world: they read the system clock, call a web API, or write to a database. The fix uses the ideas from this course:

  1. Inject collaborators. Instead of calling new Date() inside Loan, pass the current date in, or inject a clock object. Tests pass a fixed date; production passes the real one.
  2. Depend on interfaces. A NotificationService that receives any object with send() can be tested with a fake that just records messages.
  3. Keep logic in plain objects. Put rules (fines, limits, discounts) in classes with no network or database code, so tests are instant and reliable.

A test double is any stand-in for a real collaborator. Common kinds:

  • a stub returns canned answers ("the price is always 10");
  • a fake is a working lightweight version (an in-memory repository);
  • a mock records how it was called so the test can check, for example, that send() was called once.

If a class is painful to test, treat that as design feedback: it usually has too many responsibilities or hidden dependencies.

Step 7 of 13Practice · Sort into groups

Which test double is being described?

Tap an item, then tap its group (or drag it there).

Step 8 of 13Compare

Stub, fake and mock

AspectStubFakeMock
What it doesReturns canned answersA working lightweight versionRecords how it was called
ExamplePrice service that always says 10In-memory repositorySender that counts send() calls
Test checksThe result your code computesBehavior across several callsThat the right calls happened

Step 9 of 13Practice · Code challenge

Write a class Loan whose constructor takes dueDay (a day number, such as 21). Add a method fineOn(returnDay) that returns the late fine: 0.25 per day late, and 0 if the copy is returned on or before the due day.

Runs in a sandbox in your browser.
  • new Loan(21).fineOn(30)
  • new Loan(21).fineOn(21)
  • new Loan(21).fineOn(5)
  • new Loan(14).fineOn(18)

Step 10 of 13Practice · Put in order

Put these steps for turning requirements into a working object model in a sensible order.

Drag the items, or use the arrow buttons, to put them in order.

  1. Write a class with unit tests for its rules, injecting any collaborators
  2. Read the requirements and list the nouns and verbs
  3. Assign each rule to the class that owns the data it needs
  4. Choose which nouns become classes and which become fields
  5. Sketch the classes and their relationships, with multiplicities

Step 11 of 13Learn

Common modeling mistakes

A few mistakes appear in almost every first object model.

  • The god class. One class, often called System, Manager or App, ends up holding most of the data and logic. Other classes become empty data holders. If one class appears in nearly every method call, its responsibilities need splitting.
  • Modeling the user interface instead of the domain. Classes named LoginScreen and CheckoutPage describe screens, not the business. The core model should still make sense if the app later gains a mobile version or an API.
  • Booleans for states. An order with isPaid, isShipped and isCancelled flags can reach impossible combinations, such as shipped and cancelled at once. A single status field with allowed transitions, or separate state objects, prevents that.
  • Primitive obsession. Passing raw strings and numbers everywhere, such as a price as a float and an email as a plain string, means validation is repeated or forgotten. Small value objects like Money and EmailAddress fix it.
  • Inheritance for roles. A person who is both a Student and an Employee can't be modeled with Student extends Person and Employee extends Person. Roles are better held as objects the person has.

Step 12 of 13Practice · What would you do?

What would you do?

An order class has three booleans: isPaid, isShipped and isCancelled. A bug report shows an order that is both shipped and cancelled. What is the best fix?

Step 13 of 13Practice · True or false

If a class is very hard to unit test, that is often a sign that it has too many responsibilities or hidden dependencies.