The belief goes like this: put a repository class between your service and the database, so that one day you can replace Oracle with PostgreSQL, or SQL with MongoDB, and the business code will not notice. Teams have built thousands of IRepository interfaces on that promise. How many have ever swapped the database? Very few. How many have a wrapper that adds nothing except one more file per table? Nearly all.

The pattern is useful. The usual justification is the weak one. Let us rebuild it from its actual purpose.

What the original idea says

Martin Fowler’s catalogue describes a repository as something that mediates between the domain and data-mapping layers, acting like an in-memory collection of domain objects. Eric Evans, in Domain-Driven Design, sharpened it: you have one repository per aggregate root, and its interface speaks the language of the domain. Notice what this does not say. It does not say “a class per table”, and it does not say “hide the database brand”.

Take an insurance claims application in Bhopal (invented). The domain talks about a Claim, with its line items and assessments. A good repository offers methods like findOpenClaimsAssignedTo(assessor) and save(claim). The calling code reads like the business: it asks for claims, not rows. How those are fetched, joined or cached is the repository’s private problem. That is the real benefit: the domain model stays free of persistence concerns, and query logic lives in one named place rather than being rewritten in five services.

Unit of Work: tracking what changed

Now suppose approving a claim changes the claim, adds an audit entry, and updates the assessor’s workload. Three objects, possibly in three repositories. Either all three changes persist or none must.

A Unit of Work keeps a list of objects loaded, new, modified or removed during one business operation, then writes the whole set out together in a single transaction at the end. Repositories register what they touch; the unit of work commits. It also helps with consistency inside the operation: ask for the same claim twice in one unit and you get the same object, not two diverging copies (the identity map idea).

Here is the part that surprises many people: if you use Hibernate or JPA, the Session or EntityManager is already a unit of work with an identity map. In .NET, Entity Framework’s DbContext is one too, and its DbSet properties are repository-like. Django’s ORM is more direct and has no unit of work in this sense, though transaction.atomic covers the commit-together need. So wrapping them in your own IUnitOfWork and IRepository<T> often means putting an abstraction on top of an abstraction that already does the job.

The generic repository anti-pattern

The most common form is IRepository<T> with GetById, GetAll, Add, Update, Delete. It looks tidy. Problems appear within weeks.

  • The first real requirement is a filtered, joined, paged query. So the interface grows a method that accepts an expression, or returns a queryable object. Now the ORM leaks straight through the “abstraction”, and callers write persistence logic after all.
  • GetAll invites someone to load 400,000 rows and filter them in memory.
  • It exposes operations the domain does not allow. Can a claim really be deleted? Perhaps it can only be withdrawn.
  • Loading and saving whole aggregates is poor for reports and list screens, which want a few columns from many rows. Forcing those through the same repository is wasteful.

The healthier design has a small, specific interface per aggregate, with only the operations the domain needs, and a separate read path (a query class, a plain SQL projection, a view) for screens and reports. This is the basic idea behind CQRS, without needing the heavy machinery.

The testing argument

Another claim: repositories make unit tests easy because you can substitute a fake. True, and it is a good reason when the business logic is rich and worth testing without a database. But a fake repository does not behave like a database. It does not enforce unique keys, does not apply collation rules, and does not fail on a deadlock. Tests that pass against the fake can fail on the real thing. A sound balance: unit-test domain rules with in-memory fakes, and test the repository implementation itself against a real database, spun up in a container for the test run.

When to skip the pattern

My view, stated as an opinion: for a CRUD-heavy service with thin business rules, call the ORM directly from a service or handler layer. Adding repositories there creates ceremony and no protection. Reach for the pattern when:

  • you have a real domain model with invariants, where aggregates are loaded and saved whole;
  • the same queries are repeated across several places and deserve a name;
  • you need a clean seam to test business rules fast;
  • persistence is genuinely awkward (several stores, a legacy system, an external API) and you want that mess behind one door.

Back in Bhopal: the claim aggregate with its approval rules deserves a repository with three or four well-named methods. The “list of states” dropdown does not need one.

Figures and names in the examples are illustrative.

Leave a Reply

Trending