3 ms·
I've found the repository pattern (http://martinfowler.com/eaaCatalog/repository.html http://martinfowler.com/eaaCatalog/repository.html) quite useful in large
by stevenwei 16y ago
I've found the repository pattern (http://martinfowler.com/eaaCatalog/repository.html http://martinfowler.com/eaaCatalog/repository.html) quite useful in large projects to abstract away some of the detail of the ORM. Using this technique has the added benefit of being able to mock out the repository during unit testing (so you're not tied to having to setup/teardown your database between every run, which if you have a large project, can take quite a bit of time). It also helps with maintainability because all of your ORM related code is basically in one place.
I do think this is overkill for smaller projects as you're just adding another layer of indirection. In most projects, I think it's best to start out by keeping things simple, and refactor towards these additional abstractions as the need grows.
One thing I've always found when using an ORM, (especially in web projects although really in anything with a user interface) is that the abstraction is always leaky, especially as you start to optimize for performance.
You might start out with a simple query for Books, but then realize for this specific page, you're only rendering Book.name and Book.price, so you should limit your query to those fields. Or you realize that for another page you should be eager loading Book.authors and lazy loading something else.
If you don't pay attention to the fact that your data is ultimately backed by the database you could end up doing things that cause your ORM to issue more queries or request more data than is really necessary. But once you do start paying attention and customizing/optimizing those queries, your queries can end up very specific to the page that they're being rendered on.