Secret Recipe of the Template Method: Po Learns the Art of Structured Cooking

 

Java, Design Patterns, Template Method Pattern, Functional Programming, Po and Mr. Ping, Java Lambda, Clean Code, Code Refactoring, Story-Driven Learning, JavaOnFly

Gala at the Jade Palace

A grand gala was being held at the Jade Palace. The Furious Five were preparing, and Po was helping his father, Mr. Ping, in the kitchen. But as always, Po had questions.

Po (curious): "Dad, how do you always make the perfect noodle soup no matter what the ingredients are?"

Mr. Ping (smiling wisely): "Ah, my boy, that’s because I follow the secret recipe—a fixed template!"

Mr. Ping Reveals the Template Method Pattern

Mr. Ping: "Po, the Template Method Pattern is like my noodle recipe. The skeleton of the cooking steps stays the same, but the ingredients and spices can vary!"

Po: "Wait, you mean like... every dish has a beginning, middle, and end—but I can change what goes inside?"

Mr. Ping: "Exactly! The fixed steps are defined in a base class, but subclasses—or in our case, specific dishes—override the variable parts."

Traditional Template Method in Java (Classic OOP)

Java
 
public abstract class DishRecipe {
// Template method
public final void cookDish() {
boilWater();
addIngredients();
addSpices();
serve();
}

private void boilWater() {
System.out.println("Boiling water...");
}

protected abstract void addIngredients();
protected abstract void addSpices();

private void serve() {
System.out.println("Serving hot!");
}
}

class NoodleSoup extends DishRecipe {
protected void addIngredients() {
System.out.println("Adding noodles, veggies, and tofu.");
}

protected void addSpices() {
System.out.println("Adding soy sauce and pepper.");
}
}

class DumplingSoup extends DishRecipe {
protected void addIngredients() {
System.out.println("Adding dumplings and bok choy.");
}

protected void addSpices() {
System.out.println("Adding garlic and sesame oil.");
}
}
public class TraditionalCookingMain {
public static void main(String[] args) {
DishRecipe noodle = new NoodleSoup();
noodle.cookDish();

System.out.println("\n---\n");

DishRecipe dumpling = new DumplingSoup();
dumpling.cookDish();
}
}
//Output
Boiling water...
Adding noodles, veggies, and tofu.
Adding soy sauce and pepper.
Serving hot!

---

Boiling water...
Adding dumplings and bok choy.
Adding garlic and sesame oil.
Serving hot!

Po: "Whoa! So each dish keeps the boiling and serving, but mixes up the center part. Just like kung fu forms!"

Functional Template Method Style

Po: "Dad, can I make it more... functional?"

Mr. Ping: "Yes, my son. We now wield the power of higher-order functions."

Java
 
import java.util.function.Consumer;

public class FunctionalTemplate {

public static <T> void prepareDish(T dishName, Runnable boil, Consumer<T> addIngredients, Consumer<T> addSpices, Runnable serve) {
boil.run();
addIngredients.accept(dishName);
addSpices.accept(dishName);
serve.run();
}

public static void main(String[] args) {
prepareDish("Noodle Soup",
() -> System.out.println("Boiling water..."),
dish -> System.out.println("Adding noodles, veggies, and tofu to " + dish),
dish -> System.out.println("Adding soy sauce and pepper to " + dish),
() -> System.out.println("Serving hot!")
);

prepareDish("Dumpling Soup",
() -> System.out.println("Boiling water..."),
dish -> System.out.println("Adding dumplings and bok choy to " + dish),
dish -> System.out.println("Adding garlic and sesame oil to " + dish),
() -> System.out.println("Serving hot!")
);
}
}

Po: "Look dad! Now we can cook anything, as long as we plug in the steps! It's like building recipes with Lego blocks!"

Mr. Ping (beaming): "Ah, my son. You are now a chef who understands both structure and flavor."

Real-World Use Case – Coffee Brewing Machines

Po: “Dad, Now I want to build the perfect coffee-making machine, just like our noodle soup recipe!”

Mr. Ping: “Ah, coffee, the elixir of monks and night-coders! Use the same template method wisdom, my son.”

Step-by-Step Template – Java OOP Coffee Brewer 

Java
 
abstract class CoffeeMachine {
// Template Method
public final void brewCoffee() {
boilWater();
addCoffeeBeans();
brew();
pourInCup();
}

private void boilWater() {
System.out.println("Boiling water...");
}

protected abstract void addCoffeeBeans();
protected abstract void brew();

private void pourInCup() {
System.out.println("Pouring into cup.");
}
}

class EspressoMachine extends CoffeeMachine {
protected void addCoffeeBeans() {
System.out.println("Adding finely ground espresso beans.");
}

protected void brew() {
System.out.println("Brewing espresso under high pressure.");
}
}

class DripCoffeeMachine extends CoffeeMachine {
protected void addCoffeeBeans() {
System.out.println("Adding medium ground coffee.");
}

protected void brew() {
System.out.println("Dripping hot water through the grounds.");
}
}
public class CoffeeMain {
public static void main(String[] args) {
CoffeeMachine espresso = new EspressoMachine();
espresso.brewCoffee();

System.out.println("\n---\n");

CoffeeMachine drip = new DripCoffeeMachine();
drip.brewCoffee();
}
}
//Ouput
Boiling water...
Adding finely ground espresso beans.
Brewing espresso under high pressure.
Pouring into cup.

---

Boiling water...
Adding medium ground coffee.
Dripping hot water through the grounds.
Pouring into cup.

Functional & Generic Coffee Brewing (Higher-Order Zen)

Po, feeling enlightened, says:

Po: “Dad! What if I want to make Green Tea or Hot Chocolate too?”

Mr. Ping (smirking): “Ahhh... Time to use the Generic Template of Harmony™!”

Functional Java Template for Any Beverage

Java
 
import java.util.function.Consumer;

public class BeverageBrewer {

public static <T> void brew(T name, Runnable boil, Consumer<T> addIngredients, Consumer<T> brewMethod, Runnable pour) {
boil.run();
addIngredients.accept(name);
brewMethod.accept(name);
pour.run();
}

public static void main(String[] args) {
brew("Espresso",
() -> System.out.println("Boiling water..."),
drink -> System.out.println("Adding espresso grounds to " + drink),
drink -> System.out.println("Brewing under pressure for " + drink),
() -> System.out.println("Pouring into espresso cup.")
);

System.out.println("\n---\n");

brew("Green Tea",
() -> System.out.println("Boiling water..."),
drink -> System.out.println("Adding green tea leaves to " + drink),
drink -> System.out.println("Steeping " + drink + " gently."),
() -> System.out.println("Pouring into tea cup.")
);
}
}
//Output
Boiling water...
Adding espresso grounds to Espresso
Brewing under pressure for Espresso
Pouring into espresso cup.

---

Boiling water...
Adding green tea leaves to Green Tea
Steeping Green Tea gently.
Pouring into tea cup.


Mr. Ping’s Brewing Wisdom

“In code as in cooking, keep your recipe fixed… but let your ingredients dance.”

  • Template Pattern gives you structure.

  • Higher-order functions give you flexibility.

  • Use both, and your code becomes as tasty as dumplings dipped in wisdom!


Mr. Ping: "Po, a great chef doesn't just follow steps. He defines the structure—but lets each ingredient bring its own soul."

Po: "And I shall pass down the Template protocol to my children’s children’s children!


Other Articles in this Series.

================================

1.Kung Fu Code: Master Shifu Teaches Strategy Pattern to Po – the Functional Way!

2. Code of Shadows:Mastering Decorator Pattern in Java – Po & Shifu’s Thriller Story of Clean Code

Clean code Tip : SRP is the MEDUSA of Clean code family.

While we are hearing tips on Clean code, the most common tip is maintaining SRP while writing class or methods, in a broader scope Module/Package/Service/API.

But Irony is, SRP is the most powerful but obscured principle in the Design toolbox, this throws a web of confusion and you are stoned by thinking should I use it in the right way or not? That's why I like to call SRP Medusa. Most of the time it succumbs us and we are ending up with anti-KISS code but If we use it in the right proportion, then we can create a cohesive and robust architecture.


It is time to quickly recap the definition of SRP.


“The single-responsibility principle (SRP) is a computer-programming principle that states that every module, class, or function in a computer program should have responsibility over a single part of that program's functionality, which it should encapsulate. All of that module, class, or function's services should be narrowly aligned with that responsibility.”


Let’s demystify the Confusions

  1. What does it mean by SIngle responsibility?

  2. How to define a single responsibility in the Class/Orchestrator method./Package level?

  1. How SRP can be maintained in method level/ Class level/Service level/, isn't it contradictory? If a module/Service maintains SRP then what multiple Classes/methods inside it maintains?


1. What does it mean by SIngle responsibility?

 According to Robert C Martin, Single responsibility means each component has one reason to change, if you have to modify the component for multiple reasons then it breaks SRP. but the question is, what does it mean by reason, how do I find the reason? How can we restrict components to serve just one reason?

let me take an example code snippet to discuss it more, I keep this example confined to the method level.


public void displayEvenNumberfromInput(){

List <Integer> numberList = CommandLine.getNumberInputAsList();

List<Integer> evenList = new ArrayList<Integer>();

for(Integer number : numberList){

if(number %2 ==0){

evenList.add(number);

}

}

System.out.println(“Even List :: ” + evenList );

}

Now read the method carefully and ask yourself, in which reason, you have to edit the method, those will be the reason and we need to separate them out by wrapping by a class/method according to the needs.

The above example invoked a method on an associated class called CommandLIne, but think If requirement changes and we do not want to read from Command line but from JSON, so you have to modify your code. So this is one reason to change.

If I want to change the algorithm, then also I need to change the method, so this is the second reason to change.

At last, rather than print in the console If I want to save the output in File so, this is another reason for the change.

So, I can see the above method has three reasons to change, a small method but doing so much.


2. How to define a single responsibility in the Class/Orchestrator method/Package level?

Take away from the above paragraph is, by asking questions finding the reason for the change. If you are new I would suggest writing a method then checking for the algorithm steps, extracting out the non-related steps, do not separate related step to achieve granular level SRP, it will create Code smell and increase coupling, 

Now for architecting service or class study the acceptance criteria and encapsulate non-related acceptance criteria.

Another approach is trying to find out commit which classes are often committed together pay a closer look at them any find dependency you can extract out from them, or in a class change the field name and found what are the methods gives you the error, probably they are very related and closed, so avoid to segregate them in a separate class, again these are just strategy but to use SRP in the right proportion, not making code too granular, maintaining KISS and achieving cohesion need well-versed knowledge in the domain, and architecting.

 sometime you will see some methods/Class are breaking SRP but if you pay closer look reasons are strangled together so no need to separate them out it will increase the overhead of maintainability cost,

Example::  Like if the minimum balance is over some amount then do the debit operation, here validation and debit operation are linked together so let it be in the same class.


So, domain knowledge and what context you are writing the class/methods is important, initially while architecting a class/module may be wrong in the long run but next time when you need to touch the component try to understand why you need to touch that component and separate out that concern. So Refactor is a must - to get a proper SRP, you have to do multiple refactoring, so take time, take a buffer in your story point. Refactor is a first-class citizen while you doing code


Let see How we can curb out the responsibility from the last example?


  public void displayEvenNumberFromInputSource(){         

          List<Integer> numberList = processFactory. processInputSource();

          List<Integer> evenList = algoFactory.findEven(numberList)

          displayable.display(evenList);

     }

Now I abstract the three reasons and separate them out into different classes, I am assuming there are multiple Inputs Source we need to support so I separated it into a different class, If that is not the case only we have to read from the command line, I will separate them in a separate method in Same class, Now the hardest question comes, you may say my class breaks SRP as it handles three concerns even the orchestrator method displayEvenNumberFromInputSource handling three separate concerns so sure breach of SRP.

With this context, I will dive deep into the most obscured part of SRP.


3. How SRP can be maintained in method level/ Class level/Service level/, isn't it contradictory? If a module/Service maintains SRP then what responsibility Classes/methods maintain?

I personally think, there is one part missing in SRP definition, the term hierarchy/Level, SRP does not make sense if you apply it to a specific point it is a range.


It is like a Pyramid, like our Food chain Pyramid. In a particular domain space if we visualize it using a bottom-up approach, it is starting from method level then responsibility merging in Orchestrator method, then Class, then package, then service/module level. It goes from more specialization to generalization in an upward direction.


So, in a top-level, it will do one responsibility which consists of multiple sub responsibilities, and each level of the SRP pyramid delegates the responsibility to the next level and it is continuously going on until it reaches the bottom level until each method handles a single responsibility.

But at the same level of the SRP pyramid, no component will perform more than one responsibility of that particular level. Each component level must not cross each other then it is breaching the SRP pyramid level and your higher-order component will know the lower order components, so against the Dependency Inversion principle. Only the upper-level talks to the next level through encapsulation.


Think about the HR department, what is its job in the organization -- managing Human resource, In an organization This is one of the SRP Pyramid Tower, Payroll, Finance are the different SRP Pyramid Towers. Each tower talks to the other tower through an Organization in-house API contract and each tower specifically handles one broad responsibility of that organization.


Now if we deep down to HR SRP Pyramid, next level we can have multiple sub responsibilities like managing different geography, different policies, so each time you deep down to SRP Pyramid you are dividing the responsibilities to sub responsibilities and give it to a more specific component to do that job.


That is the main essence of SRP, Divide, and conquer the work.

In SRP Pyramid, You can not compare top-level component with bottom level and then thinking top-level component is breaking SRP, you are then comparing Apple with Oranges.





So I would like to rephrase the definition of SRP.

“The single-responsibility principle (SRP) is a computer-programming principle that states that SRP starts with a SRP Pyramid , where a module, class or function in a computer program placed in a level and in that level they have responsibility over a single part of that program's functionality, which it should encapsulate from the next level . All of that module, class or function's services should be narrowly aligned with that responsibility.”


Or in a simple 


In SRP Pyramid each component in a Level has one reason to change.