DAO package structure

dhalsim2 picture dhalsim2 · Apr 2, 2012 · Viewed 13.6k times · Source

I'm writing some simple DAOs in Java using JDBC (no Spring, Hibernate or anything else).

Is it better to put the implementation DAOs in the same package as their interfaces or to put them in a sub-package?

Example:

com.mycompany.myproject.dao.MyDao
com.mycompany.myproject.dao.MyDaoImpl

OR

com.mycompany.myproject.dao.MyDao
com.mycompany.myproject.dao.impl.MyDaoImpl

If you suggest the sub-package structure, what would you suggest as a sub-package name? .impl? .sql? .jdbc?

Realistically, I'm not going to have multiple implementations. Am I over-engineering this?

Answer

Alonso Dominguez picture Alonso Dominguez · Apr 2, 2012

When designing an application there is no standard way of structuring in packages, experience is what usually helps every one to decide what are the appropriate names for our packages.

About packaging implementations of your interfaces in the same package or in a different one just think about how Java itself is structured: usually an implementation class is packaged in the same package that its interface, but is not all the times.

If you were about to have several implementations of the same DAO's then it would make sense having them structured in .jdbc, .jpa or .jdo sub packages. If your are only going to have one implementation both of the options you enumerate make sense in some way (same package or a .impl sub package).

Regarding over-engineering I would recommend you this article. Even though you are going to have just one implementation of your DAO's, it would make sense to have them defined as an interface and implementation as that will help you in a potential future to rewrite your DAOs for other frameworks whilst the code that makes use of them keeps unchanged.

At the end it's up to you (or you and your peers) to reach a consensus and make the decision that makes more sense in your specific case.

EDIT

An application usually has one implementation per DAO interface and that isn't over-engineering at all, it simply doesn't make sense to have the same DAO interface implemented for JPA and for JDO. Some of the purposes of using the interface/implementation pattern is to ease re-factoring, testing by means of mock objects, etc..

P.S.: I usually rely on JDepend to distribute my application classes in packages avoiding cycles as most as I can.