Skip to the guide

Storing data in memory: repositories, indexes and lookups

BeginnerPattern7 pages

A repository is a class that stores your objects and hides where they are kept, and an index is a second map that finds them another way. The move keeps one store with one way to write to it, passes it in to the classes that share it, and puts an interface in front when a second store is named. Interviewers listen for what keeps a map and its index agreeing, and for when a plain map is enough.

A library's card catalogue

Think of an old library. The books stand on shelves in number order, so a book is easy to find if you know its number. For everyone else, there are drawers of small cards: one drawer by author and one by subject. Each card gives only the shelf number. Only the librarian files cards, and when she corrects a book's author, she changes the book and its cards together. Visitors may read the cards but never write on them, because one pencilled change would make a drawer lie.

In code, the shelves are byId, a map from each ID to its Member. Each drawer is an index, idByEmail or idsByPlan, and it holds only IDs. The librarian is InMemoryMembers, and the visitors are FrontDesk and Renewals, which ask through MemberRepository.