The Design of Software (CLOSED)

A public forum for discussing the design of software, from the user interface to the code architecture. Now closed.

The "Design of Software" discussion group has been merged with the main Joel on Software discussion group.

The archives will remain online indefinitely.

Where to place a Database factory?

I have created a database factory that manages connections, transactions etc. Everything seems to work well, but I don't know where in my application should the factory be? Should I make the factory class static or should I create an instance when the application starts and then pass the factory instance into every form and other instances created?

Thanks for suggestions,
Petr
Petr Veit
Monday, April 14, 2008
 
 
A static class would be fine. A Singleton would be just as good - and better if you need to subclass your factory.

If your solution works, then that is good enough!

Using a singleton:
Connection conn = DatabaseConnectionFactory.getInstance().getConnection();
// do stuff with conn
conn.close();

Using a static class:
Connection conn = DatabaseConnectionFactory.getConnection();
// do stuff with conn
conn.close();
Steve McLeod Send private email
Monday, April 14, 2008
 
 
Be sure to include your unit testing strategy in this decision.  I prefer to have an instance of an object so that I can easily create a mock object for testing.  Although you can do this with a static object I've found it's usually easier with an instance.
Jamin Roth Send private email
Monday, April 14, 2008
 
 
Instantiate your factory at the highest level possible and pass it to any dependents.
Troels Knak-Nielsen Send private email
Monday, April 14, 2008
 
 
And use try/finally or using to close your connections:

Using a static class:
Connection conn;
try
{
    conn = DatabaseConnectionFactory.getConnection();
    // do stuff with conn
}
finally
{
    conn.close();
}
Joe
Monday, April 14, 2008
 
 
Or if you are using Java, consider use Spring. It has a really nifty class called JdbcTemplate. This class does all the boilerplate stuff for you.

Creating a connection? Yes

Closing the connection in a final block? Yes

Wrapping JDBC Exceptions with unchecked exceptions? Yes, I think.
Steve McLeod Send private email
Monday, April 14, 2008
 
 

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics
 
Powered by FogBugz