views:

269

answers:

2

Pros:

  • Repositories hide complex queries.
  • Repository methods can be used as transaction boundaries.
  • ORM can easily be mocked

Cons:

  • ORM frameworks offer already a collection like interface to persistent objects, what is the intention of repositories. So repositories add extra complexity to the system.
  • combinatorial explosion when using findBy methods. These methods can be avoided with Criteria objects, queries or example objects. But to do that no repository is needed because a ORM already supports these ways to find objects.
  • Since repositories are a collection of aggregate roots (in the sense of DDD), one have to create and pass around aggregate roots even if only a child object is modified.

Questions:

  • What pros and cons do you know?
  • Would you recommend to use repositories? (Why or why not?)
+4  A: 

A repository is really just a layer of abstraction, like an interface. You use it when you want to decouple your data persistence implementation (i.e. your database).

I suppose if you don't want to decouple your DAL, then you don't need a repository. But there are many benefits to doing so, such as testability.

Regarding the combinatorial explosion of "Find" methods: in .NET you can return an IQueryable instead of an IEnumerable, and allow the calling client to run a Linq query on it, instead of using a Find method. This provides flexibility for the client, but sacrifices the ability to provide a well-defined, testable interface. Essentially, you trade off one set of benefits for another.

Robert Harvey
+1 on returning an IQueryable from the IRepository. This allows you to write your "find" logic in the service/root layer, and test that logic by mocking up an IRepository. As for testing, the "Repository" layer is where I draw the line between Unit testing and Integration testing - I write Integration tests for my Repos and that they return the proper FetchAll() records for an IQueryable, and Unit tests for eveything else that has actual business logic in it.
eduncan911
+2  A: 

The main point of a repository (as in Single Responsibility Principle) is to abstract the concept of getting objects that have identity. As I've become more comfortable with DDD, I haven't found it useful to think about repositories as being mainly focused on data persistence but instead as factories that instantiate objects and persist their identity.

When you're using an ORM you should be using their API in as limited a way as possible, giving yourself a facade perhaps that is domain specific. So regardless your domain would still just see a repository. The fact that it has an ORM on the other side is an "implementation detail".

Justin Bozonier