The toy library’s tracker now has a family of toys: a Toy and kinds of toy that extend it. The volunteers’ real job is lending, though. They need something that holds the toys and the members, checks whether a toy suits a child, and says when it’s due back—two weeks normally and three over the winter break.
In this lesson, you’ll decide which things in the library are kinds of each other and which are parts of each other, then build a lending desk from those parts. You’ll also swap its loan rule without touching its code. Start on paper, with the question that opened the course: What is each thing?
Sketch the Library Before You Code
Lending is new behavior, and you already have one tool for adding it to toys: extends. So a reasonable first attempt puts the loan rule in a parent class and makes every toy inherit it:
class LoanRecord {
dueText() {
return "due back in 2 weeks";
}
}
class Toy extends LoanRecord {}
Every toy, building sets included, could now call .dueText(). However, try the “is a” test on it: “a toy is a loan record.” That’s false. A wooden train set sitting on the shelf isn’t a loan of anything.
The loan rule doesn’t belong to the toys either. It’s the library’s policy, and in December the volunteers want to change it at the desk, for every toy at once. In this version, that means editing the fixed string in LoanRecord. An inherited method could read its weeks from somewhere else, but a toy still wouldn’t be a loan record.
The better sentence is “has a”. A has-a relationship means one object holds another as a part and asks it for help. Building an object from parts like this is called composition. Sketch the library with both kinds of link:
- Is a: A
BuildingSetis aToy, and so is aDressUp. These stay asextends. - Has a: The lending desk has toys, members, and a loan policy. These become parts the desk holds.
The sketch also settles which things need a class. A toy has a rule to protect, its private minimum age, so it stays a class. The desk will guard its lists, so it’s a class too.
A member is a name and an age from the sign-up sheet, with nothing to protect, so a plain object is enough. A loan policy is a rule with no data that changes, so it’s a plain object with a method. Here’s the sketch, with the building set standing in for every kind of toy: