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

Picture by Ryoji on Unsplash

Lately I got here throughout this wonderful video on design patterns.

The purpose made about how one can study design patterns made numerous sense to me.

Solely while you see how a sample is virtually used within the frameworks and libraries, you’ll get an intensive understanding of the sample.

I’ve learn many design sample books and on-line sources, however I nonetheless really feel a scarcity of in-depth understanding of how one can use every sample in a real-life venture.

Design patterns are arduous to use from simply studying about them. Until you’ve seen actual conditions the place they’d apply, or have utilized, it’s virtually inconceivable to grasp their true worth.

It’s like studying to trip a motorcycle or swim by studying a ebook. You’ll be able to memorize the steps — spin the wheel together with your left leg, then the proper one, and repeat this time and again — use the brakes in case you wanted to cease the bike. However when you assume you’re able to trip the bike with out practising using with coaching wheels, you’re most probably to crash right into a tree.

Placing the recommendation into follow, I made a decision to make a behavior of wanting into the internals of standard frameworks and libraries in java to grasp how totally different patterns have been used to provide nice code. And I’ll doc my learnings in a collection of blogs.

Let’s start with the template methodology sample and its utilization in JdbcTemplate. We will even see that the usages of design patterns in actual life might not be precisely just like the textbook patterns. Subsequently, that you must have a eager eye.

However first, let’s refresh our reminiscence on the fundamentals of the template methodology sample.

The template methodology defines the construction of the algorithm and permits slight variations to a number of steps by permitting subclasses to offer totally different implementations.

Let’s take a look at an instance.

Suppose you’re creating experiences in varied tabular file codecs like excel, CSV, and many others.

Right here’s the code for excel:

And now the CSV…

A lot of the code seems similar to the one which we simply applied in Excel. There’s numerous duplication.

Let’s transfer the frequent code to a typical class referred to as TabularReport.

prepareReport() within the TabularReport is the template methodology right here, the place now we have outlined the skeleton of the algorithm to organize a report. It’s declared closing as a result of we don’t need the subclasses to override it, as we wish management over the algorithm.

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

Lastly, we have to create CSV and Excel lessons. They now depend on TabularReport class to deal with creating experiences and simply want to fret about including headers and rows.

You’ll be able to see how now we have maximized code reuse.

Template methodology sample is all about making a template for an algorithm. Extra particularly, it is a methodology that defines the algorithm as a set of steps. A number of of those steps is outlined to be summary and applied by the subclasses, thus making certain that the algorithm’s construction is unchanged.

This sample is utilized in numerous libraries in Java. One such place is AbstractList/AbstractSet. This class gives some primary implementation of checklist behaviors for the varied checklist collections in Java, like ArrayList and LinkedList.

An instance of a template methodology in AbstractList is the addAll() methodology which is used so as to add a group of parts to the checklist. It depends on an summary methodology add().

The subclasses have to provide solely the implementation of the summary add(), get()and set() strategies.

If you wish to create your personal customized checklist, you are able to do that by extending AbstractList and get the fundamental checklist habits free of charge by utilizing 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 is time to take a fast tour to spring. To those that have not used JdbcTemplate, it’s a spring library that simplifies using Jdbc in java. It executes the core Jdbc workflow, leaving software code to only present the SQL question and extract outcomes. Is any sample coming to your thoughts that may be one of the best match for this use case? Sure, you guessed it proper! Template methodology sample.

The instance template methodology that we’re focused on right here is the execute methodology.

As you possibly can see, the template methodology controls the algorithm:

  1. First, it obtains a database connection.
  2. Creates a press release object.
  3. Applies the assertion settings to the assertion object.
  4. Then it calls motion.doInStatement which is equipped utilizing StatementCallback interface.
  5. Closes the assertion object
  6. Launch the database connection.

The customers of the tactic don’t should trouble in regards to the complexities of dealing with Jdbc connections and nonetheless execute SQL queries by merely implementing the StatementCallback interface.

This ensures that the algorithm’s construction is unchanged and errors are additionally prevented. Customers can execute a question with out operating into the difficulty of not closing a connection.

jdbcTemplate.replace("UPDATE Clients SET ContactName='James' the place id=7")

However does this look totally different from the template methodology sample?

You might be proper! The template sample requires implementing an algorithm construction and letting the subclasses change some elements of it. However right here we’re not subclassing JdbcTemplate. We’re passing the concrete methodology as a parameter.

This will additionally seem like a technique sample. That’s as a result of the technique sample makes use of composition to alter the habits whereas the template methodology makes use of inheritance.

However keep in mind, within the technique sample, the category that you simply compose controls the complete algorithm. However right here the formation of the algorithm continues to be with the template methodology. The algorithm of execute() is lacking a single step of doInStatement(), and all you want is to provide a category that implements it. So, in that approach, it is extra just like the Template methodology.

However there isn’t a proper or incorrect reply to that debate. And it doesn’t matter. We simply have to seize the spirit of the design.

We noticed how the template methodology sample gave us an necessary approach for code reuse. We additionally noticed that the implementation of design patterns in actual codebases may differ barely from that of textbook patterns.

The following step to whet your design expertise is to begin refactoring your present tasks utilizing the patterns. You can’t recognize them absolutely when you haven’t suffered via the issues they remedy. And please take into account that they aren’t silver bullets. Your north star needs to be basic design rules equivalent to code readability, reusability, and testability.

More Posts