views:

117

answers:

4

Is it better to encapsulate the connection inside a DAO, ie have the DAO create or retrieve the connection and then close, or is better to pass the connection into the DAO and handle the details in code external to the DAO?

Follow-up: How do you mange closing connections if you encapsulate the connection inside the DAO?

+3  A: 

The DAO should do CRUD operations and hide those operations from the callers. So you should encapsulate the connection.

On the other hand, if the upper levels are coordinating the DAOs (e.g. transactions) then you also could pass the connection into the DAOs (and close it at the same level you opened it, not in the DAOs).

Bottom line is... it really depends on the responsibility that each layer of your application has. Should the callers care where the DAOs are retrieving the data or not? If not, then encapsulate the connections.

dpb
I was thinking of creating a factory and having the DAO call that, which is essentially encapsulation.
James McMahon
The DAO factories are used to produce concrete DAOs (implementations). I'm not sure I understand what you mean by "creating a factory and having the DAO call that"!
dpb
Sorry, I meant a connection factory, not a DAO factory.
James McMahon
+3  A: 

Coming at this from a pure usability and standards viewpoint I think that you want the DAO to take care of the connections. That is after all a main function of Data access.

Consider your use, would you want the presentation/business layer code that uses the DAO to know enough about the database to create a connection to pass to the DAO? What if you need to move the database or re-name it, at that point its very nice to have the connections encapsulated.

Using a DAO that manages its own connections also makes for a more terse use of the objects in the calling code, boosting the overall readability, IMO.

Tj Kellie
+3  A: 

I think you've answered your own question. The basic design pattern explains the DAO should be creating/retrieving the Connection (say via a Factory) and hide those from any callers like Service tier classes.

http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

Do you see any merits in keeping this external?

JoseK
A: 

I think the key point of a DAO is that you can swap out the implementation without the rest of the application knowing or caring. I've actually done this on a project. The DAO interface remains the same but connection details change so you CAN'T have it visible externally.

bgiles