3. Row processors revisited

In Example 7.7, “Our row processor”, we used a simple row processor, that takes rows from the database and appends the information as blocks in a template.

Row processors can be used in a more powerful way than that. A nice pattern that can be useful if you need to reuse a processor in various places in different ways, is to do as following: Create an abstract row processor class that implements the processRow method and gets the data from the result set as usual. Then it calls an abstract method, that you can be overridden in a subclass, to perform the actual work.

Example 10.3. An abstract row processor

public boolean processRow(ResultSet resultSet)
throws SQLException
{
  String name = resultSet.getString("name");

  if (name != null)
  {
    gotName(name);
  }
}

protected abstract gotName(String name);

This allows you to reuse the row processor and change its behavior instead of writing a new one every time. Since the actual logic of accessing the resultset and column names is isolated in one worker method, any class that extends this abstract row processor doesn't have to know the slightest single bit about the actual structure of the database itself.

You could even make the abstract row processor implement an interface that only declares the abstract methods and make your application completely independent of the fact that the data is provided through a database.