Search code examples
javadesign-patternsjakarta-ee

What is the better: to allow Services to access several DAOs or only other Services


I haven't found any questions addressing this specific issue. What is better: to allow Services (or facades) to access several DAOs (classes which talk to the database) or only other Services?

In other words, should I introduce inter-depencencies between different Service classes or is it better to make Service classes completely independent of each other by injecting more than one DAO (if necessary) to each Service class?

I found that both strategies will do the job, but I want to be consistent and make the application as modular and maintainable as possible.


Solution

  • I feel that allowing or forbidding a service to call another service or more than one DAO is subjective. I try to avoid unnecesary code or odd couplings just to satisy some rule about layer-communication, and following basic OO principles of making simple, clear objects usually leads to a compromise.

    1. If a service B needs another functionality already comprised in a service A then it should call it. I try to reduce dependencies among services and usually end up defining a small set of "basic" services that can be called from other services.

    2. Creating a method in a service only to wrap a call to a DAO is pointless (in my opinion) and therefore I prefer to let services call as many DAOs as they need. Again, a service or a method with many DAOs indicates something that should be refactored or a data model that needs adjustment.