java DB entity object HAS-A DAO?

Say you have an Account.java representing one row in Account table. You have an AccountDAO.java that read/write the table.

Q: Shall Account.java HAS-A AccountDAO instance?
A: I feel Account.java should not import AcountDAO at all. Acocount.java should be compilable without AccountDAO.java. Assumption is, Account.java is a more generic class. It should be usable in other projects (web, xml serialization, file-based …) without database.

Bottom line — If you want AccountDAO to be compile-time dependent on Account.java, then don’t have the reverse-dependency. DAO is one layer above the DB entity objects.

If Account table relates to Customer and Branch tables, it’s perfectly legitimate and perhaps best practice to use HAS-A between these classes. I think Hibernate and many ORM systems do that. These classes exist on the same “layer” so compile-time dependency is perhaps tolerable. To reduce compile-time dependency, use interfaces rather than classes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s