Scala Mashup Series: The Template Method in Java, Spring and Scala

Continuing the Scala Mashup Series, this post is about a quite important, often used, but also controversial pattern: The Template Method.

In general, there are great explanations of the pattern in Wikipedia and of course in Head First Design Patterns.

Criticism

A very good summary of the Template Method pattern especially in comparison to the Strategy pattern is on stackoverflow.com:

The Template pattern does compile-time algorithm selection by subclassing.
The Strategy pattern does run-time algorithm selection by containment.

Example

Imagine you want to arrange a dinner. The entire algorithm for arranging a dinner is predefined:

  1. Invite your guests
  2. Go shopping
  3. Clean your fridge to provide enough space
  4. Prepare the meal
  5. Server the meal
  6. Wash the dishes

Now, some parts of this algorithm (which in its entirety is called arrange) are fixed (invariant parts). Other parts are highly dependant on the meal you want to prepare (variant parts).
In Template Method, the algorithm itself is described in a public accessible method, eg. arrange(), which combines and calls the variant and invariant methods. The invariant methods are implemented in the abstract super class. The variant parts are implemented in the concrete classes, eg. BratwurstDinner, which implements the concrete way to do shopping for the BratwurstDinner, as well as the preparation of the Bratwurst itself.
The important part is the compile-time binding – the implementing, concrete classes cannot change their implementation during runtime.
This makes the Template Method almost ideal for framework creation, when you want to provide abstract algorithms with certain concrete implementations (think of abstract database layers, with an algorithm which cares for opening & establishing connections, handles exceptions and cleans up nicely after doing … the variant part, which is implemented in the concrete classes).

Here is the dinner example using the Template Method pattern

Here is the dinner example using the Strategy pattern

There are two clever blog posts, one about disadvantages of the Template Method pattern, and one mentioning a possible alternative in languages with first class functions like Scala.

Language comparison: Java, Scala, Spring

We will happily leave out the Java example, since it is just too obvious. In the Wikipedia article a sample is given, together with the class diagram it should be pretty obvious how Template Method is implemented in Java. The only thing to keep in mind is to set the super class abstract, as well as the variant methods – which are then implemented (using @Override) in the concrete classes.

Scala

In Scala there are is the intuitive way of implemeting the Template Method, analogous to Java:

abstract class DinnerEvent {

  def arrange: Unit = {
    makeGuestList
    doShopping
    cleanFridge
    prepareMeal
    serveMeal
    washDishes
  }

  def prepareMeal: Unit
  def doShopping: Unit

  def makeGuestList: Unit = {
    println("making guest list...")
  }

  def cleanFridge: Unit = {
    println("cleaning fridge...")
  }

  def serveMeal: Unit = {
    println("serving meal...")
  }

  def washDishes: Unit = {
    println("washing dishes...")
  }

}

trait TurkeyDinner {

  def doShopping: Unit =  {
    println("...buying turkey")
  }

  def prepareMeal: Unit =  {
    println("...preparing turkey")
  }

}

object TemplateMethod {

  def main(args:Array[String]) = {
    val dinner = new DinnerEvent with TurkeyDinner
    dinner.arrange
  }

}

However, in languages with first class functions, it is too tempting to use the Strategy pattern:

class DinnerEventWithStrategy(shoppingStrategy: => Unit, preparingStrategy: => Unit) {

  def arrange: Unit = {
    makeGuestList
    shoppingStrategy
    cleanFridge
    preparingStrategy
    serveMeal
    washDishes
  }

  def makeGuestList: Unit = {
    println("making guest list...")
  }

  def cleanFridge: Unit = {
    println("cleaning fridge...")
  }

  def serveMeal: Unit = {
    println("serving meal...")
  }

  def washDishes: Unit = {
    println("washing dishes...")
  }

}

object Closure {

  def turkeyShoppingStrategy: Unit = {
    println ("...shopping turkey strategy")
  }

  def turkeyPreparationStrategy:Unit = {
    println ("...preparing turkey strategy")
  }

  def main(args:Array[String]) = {
    val dinner = new DinnerEventWithStrategy(turkeyShoppingStrategy, turkeyPreparationStrategy)
    dinner.arrange
  }

}

So, you should choose wisely, both patterns definitely have their scope of application – just keep in mind that Strategy also uses composition over inheritance, which is always a good advise.

…and what about Spring?

This is interesting, Spring uses the Template Method a lot – and many think it is one of their greatest strengths.
But wait … the Template Method pattern? Not really. The Spring Framework templates in fact are not implementing the Template Method pattern, even if it feels this way.
Let’s examine a small usage example of Spring’s JdbcTemplate:

package com.commons.sample.dao;

import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class JdbcSimpleDao extends SimpleJdbcDaoSupport implements SimpleDao {

	final static String single	= "select id, name from test where id = ?";
	final static String list 	= "select id, name from test"; 

	public Simple getSimpleById(int id) {
		return getSimpleJdbcTemplate().queryForObject(single,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class), id);
	}

	public List<Simple> getSimples() {
		return getSimpleJdbcTemplate().query(list,
				ParameterizedBeanPropertyRowMapper.newInstance(Simple.class));
	}

}

What is happening here? Even though the class extends SimpleJdbcDaoSupport, it would not have to.
The Method query(…) takes the SQL and a ParameterizedBeanPropertyRowMapper.newInstance(Simple.class), which defines a row mapper that creates an object of class Simple – this certainly describes a strategy. So, even the so-called Spring Templates actually uses the Strategy pattern.

Summary

The Template Method is a powerful pattern. Use it if you create a framework, since you can inject certain functionality in the implementing classes at compile time, which let the user of your framework extend it easily, but in a controlled and “traceable” way. For Java, it is a natural way to enable users of your classes to extends the functionality at certain points.
In languages with first-order functions (or closures), like Scala, it might feel more natural to use the Strategy pattern instead. However, keep in mind that the patterns are not completely identical.

Scala Mashup Series

This is the first post of a series of mashup post which try to combine the following books in a Scala way:

Having completely read the Head First Design Patterns and (partly) the second edition of Effective Java, I highly recommend those two books to Java developers.
I am right now studying Programming in Scala and I am not sure if I can recommend it.

The mashup will try to find common patterns in Effective Java and Head First and try to related these patterns to the Scala world. Hopefully, this approach will represent a different way to learn Scala – highly Java focused and with mixing design patterns and effective programming style in.

Scala on stage with receiving and reacting Actors

Being quite a fan of Groovy (which also is related to Spring in some way), I nevertheless experimented with Scala a bit.
Trying not to follow the current hype about this language, I mainly wanted to check a higher-level (meaning higher than Java), typed language and like Scala, even though to me there seems to be too much magic in it to overcome the non-dynamic aspect (this might not be formally correct, but hopefully understandable).

Due to this non-dynamic aspect, many things which are highly praised in Scala seem clumsy compared to Groovy. Just compare the granted-better-than-Java XML-handling in Scala with the even-much-better XML-handling in Groovy.
Of course, my IDE will never be able to code complete the Groovy variant – however, currently, the Scala Eclipse Plugin does it neither.

So, I bought the book “Programming in Scala”, which is good, but there are certain parts which are not too well described, one being the difference between “receive” and “react”.
I did it understand only after trying out myself (see below) and reading this post.
Once again, stackoverflow.com has been very useful to me (I just know the site for about 2-3 months and found useful information there several times).

So, I wanted to try if I can validate the different behaviour (which is in short that receive blocks a Thread and react returns immediately and is not bound to a particular Thread – but there are better explanations out there).

Preparation

I wanted to check the behaviour by forcing Scala to instantiate just one thread in the thread pool. This can be done by setting two system properties:

-Dactors.maxPoolSize=1
-Dactors.corePoolSize=1

this can be concluded by the Actors sources.

Running

I used two different objects:

import scala.actors._
import scala.actors.Actor._

object Reactor extends Actor {

	def act() {
		while(true) {
			receive {
				case (x: String, actor: Actor) => println("received:" + x)
				actor ! (x, self)
			}
		}
	}
}

and the Runner:

import scala.actors._
import scala.actors.Actor._

object Runner extends Actor {

	def act() {
		while(true) {
			receive {
				case (string: String, actor: Actor) =>
					println("got: " + string)
					actor ! ("hello", self)
			}
		}
	}

	def main(args : Array[String]) : Unit = {
			Runner.start()
			Reactor.start()
			Reactor ! ("hello", Runner)
	}	

}

Starting the application with this parameters just freezes it immediately. We need at least a threadpool of two threads. With these two threads, the application starts and the result with visualvm is like this:

Switching while(true) to loop and receive to react results in one sharing thread, which means the size can be max=1, core=1 and the application runs like this:

Which look like it should – the react does not block the thread, therefore one “shared” thread is enough – the react of each actor is then “attached” to the main thread.