ryandlf
ryandlf

Reputation: 28555

Should DAO Classes be dependant on other dao classes?

Normally, I try to structure my DAO classes in such a way that they are completely dependent on themselves. They can interact with multiple tables but only if the data relates to the base object. For example, say I have an appointment object and the appointment DAO pulls data from an appointments table. Lets say one column if the appointments table is a service id which is a foreign key that binds an appointment to a service. The services table is completely independent of the appointments and has its own DAO where the user can add or remove services.

The appointment object has a service field which is meant to store a service object. I did this because in many circumstances in the view its necessary to reference this service object when dealing with the appointment.

In the appointment DAO I could write separate SQL statements to pull the service data from its table and remap all of this in the appointment DAO, but all of this is already being done in the service DAO and would be as simple as calling serviceDao.find(serviceId). I feel a little dirty referencing the service DAO inside my appointment DAO. Is this because I've got design problems or is it OK to do this sort of thing? I've tried researching this problem and the results are 50/50.

Upvotes: 2

Views: 1864

Answers (3)

Twilite
Twilite

Reputation: 873

I'd reference objects belonging to other DAOs by id only (a "service" id in your example) and use object caches to cleanly separate the two types of objects.

Upvotes: 0

duffymo
duffymo

Reputation: 308918

Why is having one service DAO refer to another so bad?

The one concern you need to watch for is death by latency. If your service DAO brings back N instances, and you then loop over those results to bring back other stuff, then you'll have N+1 queries - and N+1 network roundtrips - where a single roundtrip with one JOIN would bring all that data back at once.

I'd recommend that you worry less about the DAOs and more about writing the best, most efficient SQL you can.

Upvotes: 2

dispake
dispake

Reputation: 3329

I'm not sure if there's a particular "standard" but I've typically organized my DAOs in a business sense rather than by entities. So if an appointment and service are typically related in some form, I would probably end up putting them together. Perhaps something like AppointmentServicesDAO (if that's an appropriate name). To have an object per entity fits more for models rather than DAOs.

I agree with you that it feels dirty. I typically don't like calling other DAOs within a DAO either. If there does need to be some sort of separation in class, perhaps some basic inheritance is in order.

But again, I haven't studied standards hardcore. Mostly from experience so if someone has better suggestions, would love to hear them.

Upvotes: 1

Related Questions