Skip to main content

Understanding the State Design Pattern in C#

 

The State design pattern is a behavioral pattern that allows an object to change its behavior when its internal state changes. This pattern encapsulates state-specific behavior and transitions inside state objects, making it easy to add or modify states without altering the context object.

Understanding the Template Method Design Pattern in C#

Example without State Design Pattern

Let's consider a scenario where we have a Document class that can be in different states: Draft, Moderation, and Published. Each state defines specific behavior for the Publish and Edit actions.

using System;

namespace WithoutStatePattern
{
    // Context class
    class Document
    {
        public string State { get; private set; }

        public Document()
        {
            State = "Draft";
        }

        public void Publish()
        {
            if (State == "Draft")
            {
                Console.WriteLine("Document is in Draft state and is being sent for moderation.");
                State = "Moderation";
            }
            else if (State == "Moderation")
            {
                Console.WriteLine("Document is in Moderation state and is being published.");
                State = "Published";
            }
            else if (State == "Published")
            {
                Console.WriteLine("Document is already published.");
            }
        }

        public void Edit()
        {
            if (State == "Draft")
            {
                Console.WriteLine("Document is in Draft state and is being edited.");
            }
            else if (State == "Moderation")
            {
                Console.WriteLine("Document is in Moderation state and cannot be edited.");
            }
            else if (State == "Published")
            {
                Console.WriteLine("Document is published and cannot be edited.");
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();

            document.Edit();
            document.Publish();

            document.Edit();
            document.Publish();

            document.Publish();
        }
    }
}

Problems in the Non-Pattern Approach

  1. Complex Conditional Logic:The Publish and Edit methods contain complex conditional logic to handle the different states. As the number of states grows, the complexity of these methods will increase, making the code harder to read and maintain.

  2. Scalability Issues:Adding new states or modifying existing states requires changes to the conditional logic in multiple methods. This makes the code less flexible and harder to extend.

  3. Violation of Single Responsibility Principle:The Document class is responsible for both state management and business logic. This violates the Single Responsibility Principle, making the class harder to maintain and evolve.

  4. Lack of Encapsulation:The state management logic is not encapsulated within individual state classes. Instead, it is spread across multiple methods in the Document class, leading to code duplication and potential inconsistencies.
How State Pattern Solves These Problems
  1. Encapsulation:The State Pattern encapsulates state-specific behavior within individual state classes. This keeps the state management logic localized and prevents it from spreading across multiple methods in the Document class.

  2. Single Responsibility:The Document class is responsible only for state transitions, while each state class handles the behavior specific to that state. This separation of concerns leads to cleaner and more maintainable code.

  3. Scalability and Flexibility:Adding new states or modifying existing states requires changes only in the corresponding state classes. The Document class remains unchanged, making the system more flexible and easier to extend.

  4. Simplified Conditional Logic:The complex conditional logic in the Publish and Edit methods is replaced by polymorphism. Each state class implements the state-specific behavior, simplifying the Document class and improving readability.

Revisited Code with State Pattern

Here is how we can implement this pattern :

using System;

namespace StatePattern
{
    // Context class
    class Document
    {
        private IDocumentState _state;

        public Document()
        {
            _state = new DraftState();
        }

        public void SetState(IDocumentState state)
        {
            _state = state;
        }

        public void Publish()
        {
            _state.Publish(this);
        }

        public void Edit()
        {
            _state.Edit(this);
        }
    }

    // State interface
    interface IDocumentState
    {
        void Publish(Document document);
        void Edit(Document document);
    }

    // Concrete state for Draft
    class DraftState : IDocumentState
    {
        public void Publish(Document document)
        {
            Console.WriteLine("Document is in Draft state and is being sent for moderation.");
            document.SetState(new ModerationState());
        }

        public void Edit(Document document)
        {
            Console.WriteLine("Document is in Draft state and is being edited.");
        }
    }

    // Concrete state for Moderation
    class ModerationState : IDocumentState
    {
        public void Publish(Document document)
        {
            Console.WriteLine("Document is in Moderation state and is being published.");
            document.SetState(new PublishedState());
        }

        public void Edit(Document document)
        {
            Console.WriteLine("Document is in Moderation state and cannot be edited.");
        }
    }

    // Concrete state for Published
    class PublishedState : IDocumentState
    {
        public void Publish(Document document)
        {
            Console.WriteLine("Document is already published.");
        }

        public void Edit(Document document)
        {
            Console.WriteLine("Document is published and cannot be edited.");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();

            document.Edit();
            document.Publish();

            document.Edit();
            document.Publish();

            document.Publish();
        }
    }
}

Why Can't We Use Other Design Patterns Instead?

  • Strategy Pattern: The Strategy pattern defines a family of algorithms and allows the client to choose which algorithm to use. It does not manage state transitions and dynamic behavior changes based on state.
  • Observer Pattern: The Observer pattern defines a one-to-many dependency between objects, where one object notifies its dependents of state changes. It is not designed for managing state-specific behavior and transitions.
  • Template Method Pattern: The Template Method pattern defines the structure of an algorithm but allows subclasses to override certain steps. It does not handle dynamic state transitions.

Steps to Identify Use Cases for the State Pattern

  1. Identify State-Dependent Behaviour: Look for scenarios where an object's behaviour changes based on its state.
  2. Encapsulation of States: Ensure that state-specific behaviour can be encapsulated in separate state classes.
  3. Dynamic State Transitions: Consider the State pattern when the object needs to transition between different states dynamically.
  4. Promote Maintainability: Use the State pattern to improve maintainability by isolating state-specific behaviour.

By following these steps and implementing the State pattern, you can achieve dynamic behavior changes based on an object's state, encapsulate state-specific behavior, and improve maintainability in your system.

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