Java Spring – Should DAO Interfaces Be Package Private?

interfacesjavaspring

I have several DAO classes that implement an interface. In the other hand, I have Service classes that use those DAO implementations.

So far all the DAO interfaces are public and I was thinking if would it be better to make them package private and to put the service classes in the same package so they are the only ones being able to use them.

The reason is because I wouldn't like that programmers could use DAO implementations in a Controller or a web service without using the service layer. A programmer could think for example that adding a new order is as simple as calling the addOrder dao method, ignoring that indeed there is a service method that does more than that.

What do you guys think?

Best Answer

First, I would suggest that you package those two independently, and just offer proper documentation as to what the purpose of each library is. It will give you more flexibility in the long run, as you might have to bypass the Service layer at some point or use the Data layer as a common-functionality library for other projects.

That being said, I agree that you should restrict access to the DAOs, specially to avoid direct manipulation of your data store. However, this applies to the concrete version of your DAOs (your question is vague on this aspect). Having the interfaces public might be useful for other developers to provide their own implementation in case they want to use another type of data storage (assuming you provide a way of injecting DAOs into your service layer). This should follow along nicely with the Open/Closed Principle.