From a problem to classes
Turn a problem statement into a first list of classes and methods.
Read for nouns and verbs
Underline the nouns in the problem: they are candidate classes or fields. Underline the verbs: they are candidate methods.
"Vehicles park in spots. A ticket is issued on entry and the fee is charged on exit." gives Vehicle, Spot, Ticket and Fee, and the actions park, issue and charge.
Keep only nouns with behaviour or rules
A noun that only holds a value (a plate number, a time) is a field, not a class. A noun with rules of its own (a spot knows its size and whether it is free) earns a class.
Put each verb on the class that has the data it needs. Charging a fee needs the time parked and the vehicle kind, so it belongs with pricing, not with the spot.
class Spot {
constructor(readonly id: string, readonly size: SpotSize) {}
private plate: string | null = null;
get isFree() { return this.plate === null; }
occupy(plate: string) { this.plate = plate; }
}
Key takeaways
- Nouns suggest classes and fields; verbs suggest methods.
- A noun becomes a class only when it has rules or behaviour.
- A method lives with the data it needs.
Hands-on coding exercise
A small library lends books. Members borrow a book by its id; a borrowed book can't be lent again until it comes back.
Book is a noun with a rule of its own (borrowed or not), so it gets a class. Library holds the books and offers the verbs.
class Book {
constructor(readonly id: string, readonly title: string) {}
}
class Library {
addBook(id: string, title: string): void {
throw new Error("Not implemented");
}
/** Lends the book to the member; throws if unknown or already lent */
borrow(bookId: string, member: string): void {
throw new Error("Not implemented");
}
giveBack(bookId: string): void {
throw new Error("Not implemented");
}
isAvailable(bookId: string): boolean {
throw new Error("Not implemented");
}
}
Run your solution against 5 automated tests in the interactive workspace:
Check your understanding
Answer these questions interactively to test what you learned and track progress on your skill map:
- In "members borrow books for 14 days", what should 14 days most likely be?
- Which class should own the method that calculates a parking fee?