Design Patterns
Repository
Adding takes O(1) time (a constant amount). Finding by scanning takes O(n) time, where n is the number of stored items (a real database could do better with an index — a lookup shortcut).
The idea, in plain English
A repository works like a librarian who fetches books for you, no matter where they're actually kept: on the main shelves, in the back room, or in another building. You just ask the librarian for a book by name. You never need to know the storage details. In code, a repository sits between your app and wherever the data really lives. It offers simple methods like 'add' and 'find', so the rest of your code never touches storage details directly.
How it works
- 1You build one repository object that owns talking to the real data store. Here it's a list, but it could be a database or an API.
- 2You give it simple methods like `add`, `findByName`, and `all` that hide exactly how the data is stored.
- 3The rest of your code only ever calls those simple methods. Swap the storage underneath, and nothing else has to change.
When you'd use it
Use this when you want the rest of your app to stop caring whether data lives in a database, a file, or a plain list in memory. It also makes swapping that storage, or faking it in tests, easy.
Common beginner mistakes
- Don't let storage details, like raw database queries, leak out past the repository into the rest of the app. That defeats the point of hiding them.
- Pick one clear rule for 'not found' — always null, or always an error — instead of mixing them.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Found: Bob, age 25
Total users: 2
Missing user: yesNot sure this is the right topic? See the learning paths → or where this leads →