Reputation: 1497
My current design pattern includes a large number of database access methods in a single convenience class. When it's instantiated it grabs the connections it needs and waits for methods.
It was my thinking that opening a single connection when I'm about to run 10 methods with that connection would be better than opening and closing that connection for each of the 10 individual methods.
However, I've realised that I don't close any of these connections. I've come to the conclusion that I'll have to go back and refactor all calls to the method to include a closeConnections
method which will release all active connections.
My question is this:
should I open and close connections in each and every method, following good design practice (will this incur significant overhead), or should I refactor calls to the convenience class with a call to a closeConnections
method
Psuedocode
class convenience{
public contructor(){
a = new Connection();
}
public void methodA(){
/* do stuff */
}
public void methodB(){
/* do stuff */
}
public void methodC(){
/* do stuff */
//should I do this?
a = new Connection();
/* do stuff */
a.close();
}
public void close(){
//or this
a.close();
}
}
Upvotes: 0
Views: 156
Reputation: 54074
following good design practice
If you want that then don't re-invent the wheel. Use a connection pool.
Upvotes: 0
Reputation: 71
I suggest that whenever you open a connection, you should register it to a service. You can then later on check with the service if the particular connection is open or already closed to take car of the leaks in the application.
Upvotes: 0
Reputation: 108982
Maybe you should not keep the connection in this convenience class, but pass it in on each method invocation. That way you will be able to control the lifetime of the connection, and - for example - use transactions in a useful way.
Also keeping this connection inside this convenience class increases the risk of sharing a connection with multiple threads, which in general is not advisable.
Incurring the cost of opening and closing connections can be alleviated/removed by using a connection pool like c3p0, DBCP, BoneCP (and others).
Upvotes: 1