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

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...