In most applications you need to access a database sooner or later. So you implement a generic Repository/DAO interface on top of the ORM tool of your choice to simplify your data access code. The problem is that those interfaces are most of the time abused and don’t follow their original intent as described by Martin Fowler.
A typical implementation in .NET looks like this:
1: public interface IProductRepository
2: {
3: Product GetById(int id);
4: IEnumerable<Product> FindByDescription(string template);
5: IEnumerable<Product> FindByPrice(IRange<decimal> priceRange);
6: void Add(Product product);
7: void Remove(Product product);
8: }
As more functionality is needed, this repository keeps growing and growing. Not what you should describe as a maintainable solution. Luckily there are some solutions out there:
- The Query Object pattern as described by Martin Fowler. A good example of Query Object is the NHibernate ICriteria with all its classes.
- Another possible solution is the Specifications Pattern (by Eric Evans and Martin Fowler). Specification is again very powerful especially because easy to test. In .NET we have various implementations/interpretations based on LINQ.
- The last is a repository implementing IQueryable (as proposed by Fabio Maulo here).
Which one do you prefer?