Design Patterns interview question · Most asked
What is the Repository pattern, and when is it worth using?
Summary
A repository is a collection-like interface (add, get, overdue_invoices()) that hides how domain objects are stored. It's worth using when business logic is mixed with queries and you want it testable with in-memory implementations or decoupled from the storage technology.
Longer Answer
Repositories come from Martin Fowler's Patterns of Enterprise Application Architecture and are central to Domain-Driven Design and hexagonal architecture. Spring Data repositories are a framework version.
They add little in simple CRUD apps where an Active Record ORM already provides query methods, and generic repositories that just mirror the ORM (find_by(any_field)) are a common anti-pattern. Make methods domain-specific.
Key Points
- Collection-like interface over storage.
- Business logic testable with in-memory repos.
- Domain-specific methods, not generic wrappers.
- Often unnecessary for simple CRUD.
Deep dive: Design Patterns, Explained Simply: Repository and Unit of Work
Explanation
What interviewers look for
Benefits plus the generic-repository and CRUD caveats.
Follow-up questions
- How does a repository relate to a Unit of Work?
- Do you need repositories with Eloquent or Django ORM?
More most-asked Design Patterns questions
- What problem does the Builder pattern solve? Show an example.
- Explain the SOLID principles.
- What is a design pattern, and why are they useful?
- What is the difference between dependency inversion, dependency injection and inversion of control?
- Why is composition often preferred over inheritance?
- What is dependency injection, and what forms does it take?
- Explain the Factory Method pattern and how it differs from a simple factory.
- How do you implement a Singleton, and why is it often considered an anti-pattern?