Re: [Program design] How to manage often used objects?
Kai Schlamp wrote:
Hello!
I have a question regarding general program design.
I ask myself, what's the best way to handle for example a database
connection object or general settings object, that is accessed in many
different locations in my program.
Is it best to store those in a static class to easily access them, or
is it better to pass the instance itself through the whole program?
Kai
Recently there's has been some trends to use design patterns such as
Inversion of Control, including Dependency Injection and Aspect Oriented
Programming. Look those up with Google, the results are interesting.
I would, without knowing anything else about your system, make a single
factory object that returns a single reference to this expensive object:
class MyFactory {
private static DBC dbc;
public DBC getDBC() {
if( dbc == null)
dbc = new DBC();
return dbc;
}
}
But don't let your lower level routines call it directly. Instead,
inject either this object (or the result of its getDBC() method) into
the lower level business object by passing the dbc as a parameter. You
can do it at object creation as part of the constructor
ShoppingCart cart = new ShoppingCart( customerName,
MyFactory.getDBC() );
or create the object, then set the dbc with a setter method.
ShoppingCart cart = new ShoppingCart();
cart.setDBC( MyFactory.getDBC() );
The thing to watch for is testing. It's hard to test when there's hard
coded references to a class like MyFactory everywhere. By setting a
parameter, you can test just by making a test DB object and passing
that. Your code will automatically be more flexible and easier to
maintain as a result.