I have many classes that retrieve databases objects. I have implemented their methods as static, so they can be called like this:
class xxxDB {
public static method1(Connection dbcon) {
//...
method2(dbcon, ...);
}
public static method2(Connection dbcon, ....) {
//...
}
// Other specific methods for xxx
}
I like the static methods solution, but it requires passing around the Connection
object all the time to every method, and I don't find this particularly clear or elegant. So I have been evaluating different options for refactoring (and discarded the use of JPA, as I am not sure how to implement this in my specific weird database). One is to avoid static and use an immutable instance variable in each of the classes:
class xxxDB {
private final Connection dbcon;
public xxxDB(Connection dbcon) {
this.dbcon = dbcon;
}
public static method1() {
//...
method2(...);
}
// Other specific methods for xxx
}
But this creates a lot of duplicated code. For each class, and I have quite a few, I have to duplicate the instance and the constructor. My idea would be to have a super class that can be extended by all the others:
class superDB {
private final Connection dbcon;
private superDB(){}
public superDB(Connection dbcon) {
this.dbcon = dbcon;
}
}
But this still forces me to repeat this code in every class:
public xxxDB(Connection dbcon) {
this.dbcon = dbcon; // or super(dbcon);
}
My questions are:
- Is it really a good idea to refactor the
static
methods that access the database? - Is there a way/pattern for my classes to inherit the "one arg constructor" of the super class? Something like:
.
class superDB {
private final Connection dbcon;
private superDB(){}
public superDB(Connection dbcon) {
this.dbcon = dbcon;
}
}
class xxxDB extends superDB {
// no need to add duplicated code to call the super
public static method1() {
//...
}
// Other specific methods for xxx
}