What is a good way to use modules that have related entities?

43 Views Asked by At

I've been coding for some time and always looking for improvement! That's why I am learning about how to structure my modules in code well.

And now I am facing a dilema based on my experience with module dependecy I can't solve myself. I was facing this often and found out that in large applications this can become really huge problem. I think to formulate my question better I can show small example:

Lets say we have 2 modules: User, Photo. This modules also have User and Photo entities respectively, where User can have many Photos. Both of those modules also have services and repositories for basic operations with entities.

Here's when the issue begins: What if I need to get User with all of his Photos? There are multiple solutions to this that I know and use:

  1. Make service method to find User and another one to find all Photos of User and let our client deal with mapping and all stuff. Client can be another service or our frontend. With this approach modules User and Photo are as independed as possible, they don't use each other's methods and only Photo entity knows a little bit about User since it has ManyToOne relation to it storing userId. Also JOIN's are not used in this case, which may make relational db's a questionable choice.
  2. Make method in User service which will call repository method for specifically searching for User with his Photos i.e. findUserWithHisPhotos(). This is not very comfortable, now on repository level one entity can interfere with another one, which makes this two modules coupled. And in big applications it becomes difficult to track every change. Also when we have a lot of related entities, creating separate method for each case of relations required for operation makes a lof of methods as result. So this is not ideal approach.
  3. Make simple methods on repositories to find record while allowing to passing parameters of query and required relations, while exposing this method in services i.e. findOne() method. In our example this would be findOne() method on service which calls repository, and for our need to get User with all of his Photos we would pass our query to this method. This should be the most comfortable method of doing the work, yet a lot of service methods become highly dependant on entity structure, and when something changes in entities it often causes need to go through all calls of this common methods of services to fix possible issues. So with this approach modules (services) become tightly coupled, with entity structure and ORM or just repositories.

Are there any other approaches or ways to make modules in this cases not tightly coupled but still easy to use? I found myself using 3rd solution recently, but in really big applications at some point it may cause a disaster.

Thank you for this long reading!

0

There are 0 best solutions below