I had to query a set of tables and add the data to a search index.

So, I created a base class which had DB properties as follows:

public class DBConnection {
  protected Connection connection;
  private String url = <from properties file>;
  private String user = <from properties file>;
  private String password = <from properties file>;
  private String driver = <from properties file>;

  public void init(String url, String user, String password, String driver) throws ClassNotFoundException, SQLException {
    Class.forName(driver);
     connection = DriverManager.getConnection(url, user, password);
  }
	
}

Then I coded up a class for each table which extends DBConnection and does the indexing work. It was all fine until I had to unit test the table classes using an embedded HSQL db(Actual DB was postgreSQL). There was no way for me to specify the database parameters from the unit test other than to change the properties file every time. Suddenly it crept to me that this was the simplest case for dependency injection. Let not DBConnection decide it’s database parameters. Let the person who calls it decide it’s parameters.

so I changed it to

public class DBConnection {

 protected Connection connection;
	
  public void init(String url, String user, String password, String driver) throws ClassNotFoundException, SQLException {
    Class.forName(driver);
       connection = DriverManager.getConnection(url, user, password);
    }
	
}

And I was on my way to unit testing my code.

Advertisements