Exploring the Template Method Pattern Through JdbcTemplate | by daleef rahman | Apr, 2022

Photo by Ryoji on Unsplash

Recently I came across this wonderful video on design patterns.

The point made about how to learn design patterns made a lot of sense to me.

Only when you see how a pattern is practically used in the frameworks and libraries, you will get a thorough understanding of the pattern.

I have read many design pattern books and online resources, but I still feel a lack of in-depth understanding of how to use each pattern in a real-life project.

Design patterns are hard to apply from just reading about them. Unless you’ve seen real situations where they would apply, or have applied, it’s almost impossible to understand their true value.

It’s like learning to ride a bike or swim by reading a book. You can memorize the steps — spin the wheel with your left leg, then the right one, and repeat this over and over again — use the brakes in case you needed to stop the bike. But if you think you are ready to ride the bike without practicing riding with training wheels, you are most likely to crash into a tree.

Putting the advice into practice, I decided to make a habit of looking into the internals of popular frameworks and libraries in java to understand how different patterns were used to produce great code. And I will document my learnings in a series of blogs.

Let’s begin with the template method pattern and its usage in JdbcTemplate. We will also see that the usages of design patterns in real life may not be exactly like the textbook patterns. Therefore, you need to have a keen eye.

But first, let’s refresh our memory on the basics of the template method pattern.

The template method defines the structure of the algorithm and allows slight variations to one or more steps by allowing subclasses to provide different implementations.

Let’s look at an example.

Suppose you are creating reports in various tabular file formats like excel, CSV, etc.

Here’s the code for excel:

And now the CSV…

Most of the code looks very similar to the one that we just implemented in Excel. There’s a lot of duplication.

Let’s move the common code to a common class called TabularReport.

prepareReport() in the TabularReport is the template method here, where we have defined the skeleton of the algorithm to prepare a report. It is declared final because we don’t want the subclasses to override it, as we want control over the algorithm.

We’ve generalized step 3 and 4 to addHeaders() and addRows(). Since excel and CSV will implement these steps in different ways these are declared as abstract.

Finally, we need to create CSV and Excel classes. They now rely on TabularReport class to handle creating reports and just need to worry about adding headers and rows.

You can see how we have maximized code reuse.

Template method pattern is all about creating a template for an algorithm. More specifically, it’s a method that defines the algorithm as a set of steps. One or more of these steps is defined to be abstract and implemented by the subclasses, thus ensuring that the algorithm’s structure is unchanged.

This pattern is used in a lot of libraries in Java. One such place is AbstractList/AbstractSet. This class provides some basic implementation of list behaviors for the various list collections in Java, like ArrayList and LinkedList.

An example of a template method in AbstractList is the addAll() method which is used to add a collection of elements to the list. It relies on an abstract method add().

The subclasses have to supply only the implementation of the abstract add(), get()and set() methods.

If you want to create your own custom list, you can do that by extending AbstractList and get the basic list behavior for free by using its templates.

int [] array = { 2, 4, 6 };
EvenNumberList mylist = new EvenNumberList(array);
mylist.addAll(Arrays.asList(8, 10, 12));
mylist.subList(2, 4);

Now it’s time to take a quick excursion to spring. To those who haven’t used JdbcTemplate, it’s a spring library that simplifies the use of Jdbc in java. It executes the core Jdbc workflow, leaving application code to just provide the SQL query and extract results. Is any pattern coming to your mind that would be the best fit for this use case? Yes, you guessed it right! Template method pattern.

The example template method that we are interested in here is the execute method.

As you can see, the template method controls the algorithm:

  1. First, it obtains a database connection.
  2. Creates a statement object.
  3. Applies the statement settings to the statement object.
  4. Then it calls action.doInStatement which is supplied using StatementCallback interface.
  5. Closes the statement object
  6. Release the database connection.

The users of the method don’t have to bother about the complexities of handling Jdbc connections and still execute SQL queries by simply implementing the StatementCallback interface.

This ensures that the algorithm’s structure is unchanged and errors are also prevented. Users can execute a query without running into the trouble of not closing a connection.

jdbcTemplate.update("UPDATE Customers SET ContactName='James' where id=7")

But does this look different from the template method pattern?

You are right! The template pattern calls for implementing an algorithm structure and letting the subclasses change some parts of it. But here we are not subclassing JdbcTemplate. We are passing the concrete method as a parameter.

This may also look like a strategy pattern. That’s because the strategy pattern uses composition to change the behavior whereas the template method uses inheritance.

But remember, in the strategy pattern, the class that you compose controls the full algorithm. But here the formation of the algorithm is still with the template method. The algorithm of execute() is missing a single step of doInStatement(), and all you need is to supply a class that implements it. So, in that way, it’s more like the Template method.

But there is no right or wrong answer to that debate. And it does not matter. We just need to capture the spirit of the design.

We saw how the template method pattern gave us an important technique for code reuse. We also saw that the implementation of design patterns in real codebases might differ slightly from that of textbook patterns.

The next step to whet your design skills is to start refactoring your current projects using the patterns. You cannot appreciate them fully if you haven’t suffered through the problems they solve. And please keep in mind that they are not silver bullets. Your north star should be fundamental design principles such as code readability, reusability, and testability.

Leave a Comment