Would it be a good design to have multiple repositories for one entity

database-designdesigndesign-patterns

I am working on a project. I have designed the codebase all the way from the scratch. Basic thing is the project is divided in individual modules. The modules represent one complete part of a business process. For example, AnalyticsModule deals with the analytics stuff of the project, PlatformModule deals with the other processing done on the platforms.

There are repositories in the project which corresponds to their entities. You write fetching/creating/updating/deleting logic in the repositories and those repositories return the entity instance. You don't write any logic in entities, just the table column definitions and relationships.

Now there is a PlatformEntity and corresponding PlatformRepository in PlatformModule. While working in the AnalyticsModule, I need some logic to count the number of platforms and provide the number of times a platform has been visited. This can be done in the PlatformRepository as I will start fetching the platforms and count their visits, but I wanna write this logic in AnalyticsModule as this method better belongs to the analytics part of the project.

Now, I have already added the support of multiple repositories per entity from the very beginning, but I am wondering whether this approach of having multiple repositories would be good or bad. Having two repositories for PlatformEntity (one in PlatformModule and the other one in AnalyticsModule) solves my problem though.

Best Answer

Your design doesn't sound great to me.

The idea with a repository is to abstract the underlying database. With your "generic repository" design you have a repository per entity already, so more than one abstraction for the same database, segregated by table.

Now you want to add additional repositories to return reporting data, essentially a view. which would fit with the generic repo idea, but put them in different modules.

I think the danger here is if you change the database you have multiple places in your code which may be affected. It would make more sense, to me, to have the repositories in a single module per database.

That way you change the db, you have one repository or collection of repositories to update and test.

Also here you show a flaw in the Generic Repo pattern, in that tables aren't a great unit of segregation, because you have queries which will cross table boundaries, or aggregate functions which don't return entities.

Additionally, it can be bad to mix transactional and reporting functionalities on a database. Your count of Platforms could slow down CRUD operations if the table is big enough. Often you will have a database for transactional use, and a separate reporting database or "data lake" for reporting and analytics.

Related Topic