Monday, October 6, 2008

The DAO Class

In the project I am currently working on we have lots of objects and each object has it's own DAO class.  This is fine every class should have a DAO object.  Or I should say that there should be a DAO object that every class can use to access it's data from it's storage location. The thing is that most systems I have worked with don't do it this way.  They have a DAO object that creates objects.  Not objects that use the DAO system to create them selves.

I will give you an example.  Say you have a class called foo and you want to get an instance of it from the database. With the DAO as create system you have to do the following.

   20 foo bar = fooDAO.GetFooByID(fooID);

bar gets created in the fooDAO object so basically any place where you want to work with foo you have to have fooDAO around and visible in scope as well.  No in the way I like to see things like this done a foo object has a reference to the fooDAO in his class so when you are creating the foo object you just say:

   19 foo bar = new foo(fooID);

So some people will say you haven't accomplished all that much by pushing it down into the class.  Which is true you still have the same amount of code, but when the guy that writes the business logic is working with foo now he doesn't have to know about fooDAO or care about it. He gets to make calls like.

   22 bar.Save();

rather then calls like this.

   23 fooDAO.UpdateFoo(bar);

Then when the day comes where it is time to stop using the cheep read free database you decided to use and switch over to a more powerful database. All of your updates can be done one place for each class type, and if you designed it right and use an well defined interface for your DAO object you will be able just to change the DAO object reference in each class.


Erin said...

I actually think I am wrong on this one now.

Erin said...
This comment has been removed by the author.