All Your Repositories Are Belong To Us

Who would have thought that the Repository Pattern could become a battleground? I always thought it was pretty straightforward—at least, that's how I felt when I first read Domain-Driven Design a few years ago.

While I could immediately see the benefits of using a repository, there were a few things that really bothered me as I started implementing the pattern that I could never fully reconcile:

  1. How do we best query the repository to find the particular aggregates that we care about?
  2. How do we handle UI concerns such as paging within the repository?
  3. Does the repository even care about UI concerns?
  4. How do we display domain objects to the UI (this is only slightly related to the repository pattern).
  5. How do we modify our domain objects to support lazy loading?

When I first stumbled upon Greg Young's solution of Command Query Separation as an architectural pattern, I immediately knew that this was the way to go. It was as though someone turned on a light bulb—a really big light bulb. It was an idea whose time had come. Paradigm shifts are like that. The bigger the attachment to the old philosophy, the bigger the "ah ha!" when you finally see it in a new light.

CQS instantly solved all of my problems and questions with repositories. The answer is simple—you don't query the repository to perform searches. Instead, you load specific aggregates from the repository by their identity. Further, paging is purely a UI concern, therefore we query a completely different data source--or at least access the data source through another mechanism. Queries and searches are performed against this alternate mechanism as well. Lastly we don't display our domain objects. We display simple DTOs that have been queried through this alternate data access mechanism.

With all of this as introduction, it has been very amusing and informative to see Oren and Greg battle it out regarding repositories in general:

All of the posts are worth reading several times. Summing them up in a single phrase doesn't do them justice. Further, the summary I gave is a bit arbitrary as it may not accurately express the main concepts of each post.

Being a huge fan of CQS, I'm going to have to go with Greg on this one. No surprises there. Even so, I find Oren's blog inspiring to read. The frequency of his posts make me wonder if he does anything else, but the amount of tested code he cranks out is astounding. In frequency of blog posts, Oren wins hands down.

To conclude, I see this debate as a healthy thing in the DDD community and the ALT.NET community.