2015-10-15

Where does the Repository belong?

Historically I've always viewed repository objects as part of the storage layer fairly deep down. But I recently had an interesting discussion that made me realize I never really meant it to be that way.

Because I always considered "good" repositories to have interfaces that makes sense to the business logic (or domain model if you prefer that term) rather than being simple CRUD repositories. It is true that some repositories don't need to be more complex than simple CRUD, but there is often some more intricate search method that technically is a read, but way more complex than searching for an entity based on an id.

Another argument for considering the repository to be part of the business logic layer is that it should return business logic entities. The repository is the glue between your business logic and your data access layer (DAL). And in my opinion the DAL should not know anything about the types in the business logic layer so by definition the repository is part of your business logic even if you don't buy my first argument related to CRUD.

6 comments:

  1. Repository works data entities. If you move repositories to domain layer, won't your layer now will know about data entities which they should not know about so that to abstract data layer?

    ReplyDelete
    Replies
    1. As I state in the last paragraph; the repository does not know about the storage details but it does need to have access to the generic data access layer.

      Delete
  2. The answer to this depends on what your model looks like. There's a very detailed discussion in Domain Driven Design (chapter 6 discusses repositories and factories): http://dddcommunity.org/uncategorized/toc/

    TLDR; They are part of your model.

    ReplyDelete
  3. There's a pretty clear definition of what a repository is. It pains me to see code that has a repository for every entity, each dutifully tested with a mock because *everything* has an interface whereby the developer is dogmatically applying code to a contract, without appreciating the why fully. If you want Lots of entities with corresponding repositories just call your data access objects what they are; DataAccessObjects. If you're using an ORM just use the session / UoW.

    ReplyDelete
  4. Repositories are an implementation detail, their contracts however belong to the domain.

    ReplyDelete
    Replies
    1. That is an excellent concise way of putting it.

      Delete