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

Optional Parameters in C# — Writing Flexible and Clean Methods

Hello, .NET developers! 👋 How often have you created multiple method overloads just to handle slightly different cases? Maybe one method accepts two parameters, another three, and one more adds a flag for debugging? That’s a lot of code duplication for something that can be solved beautifully with optional parameters . Optional parameters in C# let you define default values for method arguments. When a caller doesn’t pass a value, the compiler automatically substitutes the default. This feature helps keep your APIs simple, readable, and maintainable. 🎥 Explore more on YouTube : DotNet Full Stack Dev Understanding Optional Parameters Optional parameters are defined by assigning default values in the method signature. When calling the method, you can omit those parameters if you’re okay with the defaults. Example public class Logger { public void Log(string message, string level = "INFO", bool writeToFile = false) ...

.NET 10: Your Ultimate Guide to the Coolest New Features (with Real-World Goodies!)

 Hey .NET warriors! 🤓 Are you ready to explore the latest and greatest features that .NET 10 and C# 14 bring to the table? Whether you're a seasoned developer or just starting out, this guide will show you how .NET 10 makes your apps faster, safer, and more productive — with real-world examples to boot! So grab your coffee ☕️ and let’s dive into the awesome . 💪 1️⃣ JIT Compiler Superpowers — Lightning-Fast Apps .NET 10 is all about speed . The Just-In-Time (JIT) compiler has been turbocharged with: Stack Allocation for Small Arrays 🗂️ Think fewer heap allocations, less garbage collection, and blazing-fast performance . Better Code Layout 🔥 Hot code paths are now smarter, meaning faster method calls and fewer CPU cache misses. 💡 Why you care: Your APIs, desktop apps, and services now respond quicker — giving users a snappy experience . 2️⃣ Say Hello to C# 14 — More Power in Your Syntax .NET 10 ships with C# 14 , and it’s packed with developer goodies: Field-Bac...

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...