Skip to main content

Understanding the Template Method Design Pattern in C#

 



The Template Method design pattern is a behavioral pattern that defines the skeleton of an algorithm in a base class but allows subclasses to override specific steps of the algorithm without changing its structure. This pattern promotes code reuse, flexibility, maintainability, and ensures a consistent algorithm structure.

Understanding the Strategy Design Pattern in C#

Example Without Template Method Pattern

Let's consider a scenario where we have different types of data processors (e.g., CSV, XML, JSON). Each processor follows a similar sequence of steps: reading the data, processing it, and writing the results. However, the details of these steps vary for each data type. The Template Method pattern is ideal for this scenario.

using System;

namespace WithoutTemplateMethodPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            // Processing CSV data
            ProcessCsvData();

            // Processing XML data
            ProcessXmlData();

            // Processing JSON data
            ProcessJsonData();
        }

        static void ProcessCsvData()
        {
            Console.WriteLine("Reading CSV data...");
            Console.WriteLine("Processing CSV data...");
            Console.WriteLine("Writing CSV data...");
        }

        static void ProcessXmlData()
        {
            Console.WriteLine("Reading XML data...");
            Console.WriteLine("Processing XML data...");
            Console.WriteLine("Writing XML data...");
        }

        static void ProcessJsonData()
        {
            Console.WriteLine("Reading JSON data...");
            Console.WriteLine("Processing JSON data...");
            Console.WriteLine("Writing JSON data...");
        }
    }
}

Problems in the Non-Pattern Approach

  1. Code Duplication:Each method (ProcessCsvData, ProcessXmlData, ProcessJsonData) contains repeated steps (Read, Process, Write). This leads to code duplication and makes maintenance harder.

  2. Lack of Consistency:If the processing steps change (e.g., adding logging or error handling), you need to update each processing method individually. This can lead to inconsistent behavior and increased chances of errors.

  3. Difficulty in Extension:Adding a new data format requires creating a new method with similar code, leading to further duplication. Extending or modifying behavior requires changes in multiple places.

  4. Poor Encapsulation:The individual methods mix the specific processing logic with the sequence of steps. This can lead to a tangled design where the sequence of operations is not clearly separated from the specific operations.
How the Template Method Pattern Solves These Problems
  1. Eliminates Code Duplication:The DataProcessor base class defines the sequence of steps in the ProcessData method. Each concrete class (CsvDataProcessor, XmlDataProcessor, JsonDataProcessor) only provides the specific implementation for the abstract methods (ReadData, Process, WriteData). This reduces code duplication.

  2. Ensures Consistency:The ProcessData method in the base class ensures that the sequence of steps is consistent. Any changes to the sequence need to be made in just one place, ensuring that all subclasses follow the same sequence.

  3. Simplifies Extension:To add a new data format, you only need to create a new subclass and provide implementations for the abstract methods. The ProcessData method remains unchanged, promoting a more maintainable and scalable design.

  4. Encapsulates Sequence Logic:The base class encapsulates the common sequence of operations, while the concrete classes focus solely on the specific implementation details. This separation of concerns makes the design clearer and more modular.

Revisited Code with Template Method Pattern

Here is how we can implement this pattern :

using System;

namespace TemplateMethodPattern
{
    // Abstract base class
    abstract class DataProcessor
    {
        // Template method
        public void ProcessData()
        {
            ReadData();
            Process();
            WriteData();
        }

        // Abstract methods to be overridden by subclasses
        protected abstract void ReadData();
        protected abstract void Process();
        protected abstract void WriteData();
    }

    // Concrete class for CSV data processing
    class CsvDataProcessor : DataProcessor
    {
        protected override void ReadData()
        {
            Console.WriteLine("Reading CSV data...");
        }

        protected override void Process()
        {
            Console.WriteLine("Processing CSV data...");
        }

        protected override void WriteData()
        {
            Console.WriteLine("Writing CSV data...");
        }
    }

    // Concrete class for XML data processing
    class XmlDataProcessor : DataProcessor
    {
        protected override void ReadData()
        {
            Console.WriteLine("Reading XML data...");
        }

        protected override void Process()
        {
            Console.WriteLine("Processing XML data...");
        }

        protected override void WriteData()
        {
            Console.WriteLine("Writing XML data...");
        }
    }

    // Concrete class for JSON data processing
    class JsonDataProcessor : DataProcessor
    {
        protected override void ReadData()
        {
            Console.WriteLine("Reading JSON data...");
        }

        protected override void Process()
        {
            Console.WriteLine("Processing JSON data...");
        }

        protected override void WriteData()
        {
            Console.WriteLine("Writing JSON data...");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DataProcessor csvProcessor = new CsvDataProcessor();
            csvProcessor.ProcessData();

            DataProcessor xmlProcessor = new XmlDataProcessor();
            xmlProcessor.ProcessData();

            DataProcessor jsonProcessor = new JsonDataProcessor();
            jsonProcessor.ProcessData();
        }
    }
}

Why Can't We Use Other Design Patterns Instead?

  • Strategy Pattern: The Strategy pattern could be used if the steps of the algorithm were completely independent of each other. However, the Template Method pattern is more appropriate when the steps are part of a fixed sequence.
  • Factory Method Pattern: The Factory Method pattern focuses on object creation, not the sequence of steps in an algorithm.
  • Decorator Pattern: The Decorator pattern is used to add responsibilities to objects, not to define a sequence of steps in an algorithm.

Steps to Identify Use Cases for the Template Method Pattern

  1. Identify Common Algorithm Structure: Look for scenarios where multiple subclasses share a common sequence of steps in an algorithm.
  2. Separate Invariant and Variant Steps: Determine which parts of the algorithm are invariant (common) and which are variant (specific to each subclass).
  3. Enforce a Consistent Sequence: Ensure that the overall sequence of steps should remain consistent while allowing variations in individual steps.
  4. Promote Code Reuse and Maintainability: Consider the Template Method pattern when you want to promote code reuse and enhance maintainability by separating common and specific parts of an algorithm.

By following these steps and implementing the Template Method pattern, you can create flexible, reusable, and maintainable code for scenarios that involve a common sequence of steps with specific variations.

Comments

Popular posts from this blog

C# : How can we access private method outside class

Introduction In object-oriented programming, encapsulation is a fundamental principle that restricts direct access to the internal implementation details of a class. Private methods, being part of this internal implementation, are designed to be accessible only within the confines of the class they belong to. However, there might be scenarios where you need to access a private method from outside the class. In this blog post, we'll explore several techniques to achieve this in C#. 1. Reflection: A Powerful Yet Delicate Approach Reflection is a mechanism in C# that allows inspecting and interacting with metadata about types, fields, properties, and methods. While it provides a way to access private methods, it should be used cautiously due to its potential impact on maintainability and performance. using System ; using System . Reflection ; public class MyClass { private void PrivateMethod ( ) { Console . WriteLine ( "This is a private method."

C# : Understanding Types of Classes

In C#, classes serve as the building blocks of object-oriented programming, providing a blueprint for creating objects. Understanding the types of classes and their applications is crucial for designing robust and maintainable software. In this blog, we’ll delve into various types of classes in C#, accompanied by real-world scenarios and code snippets for a practical understanding. 1. Regular (Instance) Classes Definition: Regular classes are the most common type and are used to create instances or objects. They can contain fields, properties, methods, and other members. Example Scenario: A Person class representing individual persons with properties like Name and Age. public class Person { public string Name { get ; set ; } public int Age { get ; set ; } } 2. Static Classes Definition: A static class cannot be instantiated and can only contain static members (methods, properties, fields). It’s often used for utility functions. Example Scenario: A MathUtility cla

C# : 12.0 : Primary constructor

Introduction In C# 12.0, the introduction of the "Primary Constructor" simplifies the constructor declaration process. Before delving into this concept, let's revisit constructors. A constructor is a special method in a class with the same name as the class itself. It's possible to have multiple constructors through a technique called constructor overloading.  By default, if no constructors are explicitly defined, the C# compiler generates a default constructor for each class. Now, in C# 12.0, the term "Primary Constructor" refers to a more streamlined way of declaring constructors. This feature enhances the clarity and conciseness of constructor declarations in C# code. Lets see an simple example code, which will be known to everyone. public class Version { private int _value ; private string _name ; public Version ( int value , string name ) { _name = name ; _value = value ; } public string Ve