<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by A Mahboubi on Medium]]></title>
        <description><![CDATA[Stories by A Mahboubi on Medium]]></description>
        <link>https://medium.com/@a.mahboubi.dana?source=rss-18ee584f0860------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*eA0ZMQaOSvs-Kzie</url>
            <title>Stories by A Mahboubi on Medium</title>
            <link>https://medium.com/@a.mahboubi.dana?source=rss-18ee584f0860------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:26:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.mahboubi.dana/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Implementing Observability in Production for ASP.NET]]></title>
            <link>https://medium.com/@a.mahboubi.dana/implementing-observability-in-production-for-asp-net-0edcf6fe37c8?source=rss-18ee584f0860------2</link>
            <guid isPermaLink="false">https://medium.com/p/0edcf6fe37c8</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[aspnet]]></category>
            <dc:creator><![CDATA[A Mahboubi]]></dc:creator>
            <pubDate>Fri, 06 Jun 2025 19:02:09 GMT</pubDate>
            <atom:updated>2025-06-06T19:02:09.368Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementing Observability in Production for ASP.NET with Grafana Stack (Grafana, Tempo, Loki, Alloy, Prometheus)</h3><h3>Introduction</h3><p>In today’s microservices world, understanding what’s happening in your distributed systems is crucial. As applications grow more complex and distributed, traditional monitoring approaches fall short. This is where observability comes in — providing insights into the health, performance, and behavior of your systems through the three pillars: metrics, logs, and traces.</p><p>In this post, I’ll walk through a complete observability implementation using OpenTelemetry for instrumentation and the Grafana LGTM stack (Loki, Grafana, Tempo, Mimir/Prometheus) for storage and visualization. You can find the complete example in my <a href="https://github.com/alimahboubi/Observability-Example">Observability-Example repository</a>.</p><h3>What We’ll Build</h3><p>We’ll create a distributed system with two ASP.NET services:</p><ul><li><strong>WebServiceA</strong>: Main API service that fetches products with discounts</li><li><strong>WebServiceB</strong>: Discount service that provides discount rates</li></ul><p>Both services will be fully instrumented with OpenTelemetry and monitored using the complete Grafana observability stack.</p><h3>Architecture Overview</h3><p>Our observability stack consists of:</p><ul><li><strong>OpenTelemetry</strong>: Instrumentation and data collection</li><li><strong>Grafana Alloy</strong>: Data collection and routing</li><li><strong>Prometheus</strong>: Metrics storage and querying</li><li><strong>Loki</strong>: Log aggregation and storage</li><li><strong>Tempo</strong>: Distributed tracing storage</li><li><strong>Grafana</strong>: Unified visualization and dashboards</li></ul><h3>Setting Up the ASP.NET Services</h3><h3>WebServiceA: The Main API Service</h3><p>Let’s start with the main service that handles product requests:</p><pre>// WebServiceA/Controllers/ProductsController.cs<br>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class ProductsController : ControllerBase<br>{<br>    public readonly ILogger&lt;ProductsController&gt; _logger;<br>    private readonly IProductService _productService;<br>[HttpGet]<br>    public async Task&lt;IActionResult&gt; GetAllProducts(CancellationToken cancellationToken)<br>    {<br>        _logger.LogInformation(&quot;Fetching all products&quot;);<br>        var products = await _productService.GetProductsAsync(cancellationToken);<br>        return Ok(products);<br>    }<br>}</pre><p>The service layer demonstrates inter-service communication and custom span creation:</p><pre>// WebServiceA/Services/ProductService.cs<br>public class ProductService : IProductService<br>{<br>    private HttpClient _httpClient;<br>    private readonly Tracer _tracer;<br>    private ILogger&lt;ProductService&gt; _logger;<br>public async Task&lt;List&lt;Product&gt;&gt; GetProductsAsync(CancellationToken cancellationToken = default)<br>    {<br>        using var span = _tracer.StartActiveSpan(&quot;GetProducts&quot;);<br>        _logger.LogInformation(&quot;Fetching products from external service&quot;);<br>        <br>        var response = await _httpClient.GetStringAsync(&quot;/discounts&quot;, cancellationToken);<br>        var discount = decimal.Parse(response);<br>        <br>        _logger.LogInformation(&quot;Fetched discount: {Discount}&quot;, discount);<br>        <br>        // Simulating product retrieval with discount applied<br>        var products = new List&lt;Product&gt;<br>        {<br>            new Product { Id = 1, Name = &quot;Product A&quot;, Price = 100 * (1 - discount) },<br>            new Product { Id = 2, Name = &quot;Product B&quot;, Price = 200 * (1 - discount) }<br>        };<br>        return products;<br>    }<br>}</pre><h3>WebServiceB: The Discount Service</h3><p>The second service provides discount information:</p><pre>// WebServiceB/Controllers/DiscountsController.cs<br>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class DiscountsController : ControllerBase<br>{<br>    [HttpGet]<br>    public async Task&lt;IActionResult&gt; GetActiveDiscount(CancellationToken cancellationToken)<br>    {<br>        _logger.LogInformation(&quot;Fetching active discount&quot;);<br>        var discount = await _discountService.GetActiveDiscountAsync(cancellationToken);<br>        return Ok(discount);<br>    }<br>}</pre><h3>OpenTelemetry Configuration</h3><h3>Comprehensive Instrumentation Setup</h3><p>Both services use identical OpenTelemetry configuration for consistency:</p><pre>// Program.cs for both services<br>builder.Services.AddOpenTelemetry()<br>    .ConfigureResource(resourceBuilder =&gt; resourceBuilder.AddService(&quot;WebServiceA&quot;)) // or &quot;WebServiceB&quot;<br>    .WithTracing(providerBuilder =&gt;<br>    {<br>        providerBuilder<br>            .AddSource(&quot;WebServiceA&quot;) // Service-specific source<br>            .AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation()<br>            .AddOtlpExporter(options =&gt; { <br>                options.Endpoint = new Uri(&quot;http://localhost:4317&quot;); <br>            });<br>    })<br>    .WithLogging(providerBuilder =&gt;<br>    {<br>        providerBuilder<br>            .AddOtlpExporter(options =&gt; { <br>                options.Endpoint = new Uri(&quot;http://localhost:4317&quot;); <br>            })<br>            .AddConsoleExporter();<br>    })<br>    .WithMetrics(providerBuilder =&gt;<br>    {<br>        providerBuilder<br>            .AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation()<br>            .AddOtlpExporter(options =&gt; { <br>                options.Endpoint = new Uri(&quot;http://localhost:4317&quot;); <br>            });<br>    });</pre><h3>Key Configuration Points</h3><ol><li><strong>Resource Attribution</strong>: Each service identifies itself with a unique service name</li><li><strong>Multi-Signal Export</strong>: Traces, logs, and metrics all go to the same OTLP endpoint</li><li><strong>Automatic Instrumentation</strong>: ASP.NET Core and HTTP client calls are automatically traced</li><li><strong>Custom Tracing</strong>: Manual span creation for business logic</li></ol><h3>Grafana Alloy: The Data Collection Hub</h3><p>Grafana Alloy acts as our OpenTelemetry collector, receiving data from applications and routing it to appropriate backends:</p><pre>// Infrastructure/config.alloy<br>otelcol.receiver.otlp &quot;otlp_receiver&quot; {<br>  grpc {<br>    endpoint = &quot;0.0.0.0:4317&quot;<br>  }<br>  http {<br>    endpoint = &quot;0.0.0.0:4318&quot;<br>  }<br>output {<br>    traces = [otelcol.processor.batch.default.input]<br>    logs = [otelcol.processor.batch.default.input]<br>    metrics = [otelcol.processor.batch.default.input]<br>  }<br>}<br>// Batch processor for performance<br>otelcol.processor.batch &quot;default&quot; {<br>  output {<br>    traces = [otelcol.processor.attributes.default.input]<br>    logs = [otelcol.processor.attributes.default.input]<br>    metrics = [otelcol.processor.attributes.metrics.input]<br>  }<br>}y</pre><h3>Data Processing and Routing</h3><p>Alloy processes and enriches the telemetry data before sending it to storage backends:</p><pre>// Attributes processor for traces and logs<br>otelcol.processor.attributes &quot;default&quot; {<br>  output {<br>    traces = [otelcol.exporter.otlp.tempoexporter.input]<br>    logs = [otelcol.exporter.loki.lokiexporter.input]<br>  }<br>}<br>// Separate processor for metrics<br>otelcol.processor.attributes &quot;metrics&quot; {<br>  action {<br>    key = &quot;service_name&quot;<br>    from_attribute = &quot;service.name&quot;<br>    action = &quot;insert&quot;<br>  }<br>  action {<br>    key = &quot;service_instance_id&quot;<br>    from_attribute = &quot;service.instance.id&quot;<br>    action = &quot;insert&quot;<br>  }<br>  output {<br>    metrics = [otelcol.exporter.prometheus.prometheusexporter.input]<br>  }<br>}</pre><h3>Tempo: Distributed Tracing Storage</h3><p>Tempo stores and queries distributed traces. Our configuration supports a distributed deployment:</p><pre># Infrastructure/tempo-distributed.yaml<br>server:<br>  http_listen_port: 3200<br>distributor:<br>  receivers:<br>    otlp:<br>      protocols:<br>        grpc:<br>          endpoint: &quot;0.0.0.0:4317&quot;<br>memberlist:<br>  abort_if_cluster_join_fails: false<br>  bind_port: 7946<br>  join_members:<br>  - tempo-ingester-0:7946<br>  - tempo-ingester-1:7946<br>  - tempo-ingester-2:7946<br>metrics_generator:<br>  registry:<br>    external_labels:<br>      source: tempo<br>      cluster: docker-compose<br>  storage:<br>    path: /var/tempo/generator/wal<br>    remote_write:<br>      - url: http://prometheus:9090/api/v1/write<br>        send_exemplars: true<br>storage:<br>  trace:<br>    backend: s3<br>    s3:<br>      bucket: tempo<br>      endpoint: minio:9000<br>      access_key: observability<br>      secret_key: supersecret<br>      insecure: true</pre><h3>Tempo Architecture Components</h3><p>The Docker Compose setup includes multiple Tempo components for scalability:</p><pre># Infrastructure/docker-compose.yaml (Tempo section)<br>services:<br>  tempo-distributor:<br>    image: grafana/tempo:latest<br>    command: &quot;-target=distributor -config.file=/etc/tempo.yaml&quot;<br>    ports:<br>      - &quot;3200&quot;<br>tempo-ingester-0:<br>    image: grafana/tempo:latest<br>    command: &quot;-target=ingester -config.file=/etc/tempo.yaml&quot;<br>  tempo-query-frontend:<br>    image: grafana/tempo:latest<br>    command: &quot;-target=query-frontend -config.file=/etc/tempo.yaml&quot;<br>    ports:<br>      - &quot;3200:3200&quot;<br>  tempo-querier:<br>    image: grafana/tempo:latest<br>    command: &quot;-target=querier -config.file=/etc/tempo.yaml&quot;</pre><h3>Loki: Log Aggregation and Storage</h3><p>Loki provides scalable log aggregation similar to Prometheus but for logs:</p><pre># Infrastructure/loki-distributed.yaml<br>auth_enabled: false<br>server:<br>  http_listen_address: 0.0.0.0<br>  grpc_listen_address: 0.0.0.0<br>  http_listen_port: 3100<br>  grpc_listen_port: 9095<br>  log_level: info<br>storage_config:<br>  aws:<br>    endpoint: minio:9000<br>    insecure: true<br>    bucketnames: loki-data<br>    access_key_id: observability<br>    secret_access_key: supersecret<br>    s3forcepathstyle: true<br>memberlist:<br>  join_members: [&quot;loki-read&quot;, &quot;loki-write&quot;, &quot;loki-backend&quot;]<br>  dead_node_reclaim_time: 30s<br>  gossip_to_dead_nodes_time: 15s<br>ingester:<br>  lifecycler:<br>    join_after: 10s<br>    observe_period: 5s<br>    ring:<br>      replication_factor: 3<br>      kvstore:<br>        store: memberlist<br>  chunk_idle_period: 1m<br>  wal:<br>    enabled: true<br>    dir: /loki/wal</pre><h3>Loki Load Balancing with Nginx</h3><p>An Nginx gateway distributes requests across Loki components:</p><pre># Infrastructure/nginx.conf<br>upstream read {<br>    server loki-read:3100;<br>}<br>upstream write {<br>    server loki-write:3100;<br>}<br>server {<br>    listen 80;<br>    listen 3100;<br>    location = /loki/api/v1/push {<br>        proxy_pass       http://write$request_uri;<br>    }<br>    location ~ /loki/api/.* {<br>        proxy_pass       http://read$request_uri;<br>    }<br>}</pre><h3>Prometheus: Metrics Storage and Alerting</h3><p>Prometheus configuration includes service discovery for our applications:</p><pre># Infrastructure/prometheus.yaml<br>global:<br>  scrape_interval:     15s<br>  evaluation_interval: 15s<br>scrape_configs:<br>  - job_name: &#39;prometheus&#39;<br>    static_configs:<br>      - targets: [ &#39;localhost:9090&#39; ]<br>      <br>  - job_name: &#39;tempo&#39;<br>    static_configs:<br>      - targets:<br>        - &#39;tempo-compactor:3200&#39;<br>        - &#39;tempo-distributor:3200&#39;<br>        - &#39;tempo-ingester-0:3200&#39;<br>        - &#39;tempo-ingester-1:3200&#39;<br>        - &#39;tempo-ingester-2:3200&#39;<br>        - &#39;tempo-querier:3200&#39;<br>        - &#39;tempo-query-frontend:3200&#39;<br>        - &#39;tempo-metrics-generator:3200&#39;</pre><h3>Grafana: Unified Observability Dashboard</h3><p>Grafana ties everything together with pre-configured data sources:</p><pre># Infrastructure/grafana-datasources.yaml<br>datasources:<br>  - name: Prometheus<br>    type: prometheus<br>    uid: prometheus<br>    url: http://prometheus:9090<br>    isDefault: false<br>- name: Tempo<br>    type: tempo<br>    uid: tempo<br>    url: http://tempo-query-frontend:3200<br>    jsonData:<br>      nodeGraph:<br>        enabled: true<br>      serviceMap:<br>        datasourceUid: prometheus<br>      tracesToLogsV2:<br>        datasourceUid: loki<br>        spanStartTimeShift: -15m<br>        spanEndTimeShift: 15m<br>        filterByTraceID: true<br>  - name: Loki<br>    type: loki<br>    uid: loki<br>    url: http://loki-gateway:3100<br>    jsonData:<br>      derivedFields:<br>        - name: TraceID<br>          matcherRegex: &#39;&quot;TraceId&quot;:\s*&quot;([a-zA-Z0-9]+)&quot;&#39;<br>          url: &#39;$${__value.raw}&#39;<br>          datasourceUid: tempo</pre><h3>Key Grafana Features</h3><ol><li><strong>Correlation</strong>: Logs link to traces, traces show metrics</li><li><strong>Service Maps</strong>: Visual representation of service dependencies</li><li><strong>Node Graphs</strong>: Detailed trace visualization</li><li><strong>Derived Fields</strong>: Automatic linking between data types</li></ol><h3>Docker Compose: Orchestrating the Stack</h3><p>The complete stack runs with a single Docker Compose command:</p><pre><br>  alloy:<br>    image: grafana/alloy:latest<br>    volumes:<br>      - ./config.alloy:/etc/alloy/config.alloy<br>    ports:<br>      - &quot;12345:12345&quot;<br>      - &quot;4317:4317&quot; <br>      - &quot;4318:4318&quot;<br>  grafana:<br>    image: grafana/grafana:latest<br>    volumes:<br>      - ./grafana-datasources.yaml:/etc/grafana/provisioning/datasources/datasources.yaml<br>    environment:<br>      - GF_AUTH_ANONYMOUS_ENABLED=true<br>      - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin<br>    ports:<br>      - &quot;3000:3000&quot;<br>  prometheus:<br>    image: prom/prometheus:latest<br>    command:<br>      - --config.file=/etc/prometheus.yaml<br>      - --web.enable-remote-write-receiver<br>      - --enable-feature=exemplar-storage<br>    ports:<br>      - &quot;9090:9090&quot;</pre><h3>Running the Complete Stack</h3><h3>Prerequisites</h3><ul><li>.NET 9.0 SDK</li><li>Docker and Docker Compose</li><li>8GB+ RAM (for the full Grafana stack)</li></ul><h3>Launch Commands</h3><pre># Clone the repository<br>git clone https://github.com/alimahboubi/Observability-Example.git<br>cd Observability-Example<br># Start the entire stack<br>cd Infrastructure<br>docker-compose up --build<br># Access the services<br># WebServiceA: http://localhost:5001<br># WebServiceB: http://localhost:5002<br># Grafana: http://localhost:3000<br># Prometheus: http://localhost:9090</pre><h3>Testing the Observability</h3><ol><li><strong>Generate Traffic</strong>: Make requests to WebServiceA</li></ol><pre>curl http://localhost:5001/products</pre><p><strong>2. View Traces</strong>: Open Grafana → Explore → Tempo</p><p><strong>3. Check Logs</strong>: Grafana → Explore → Loki</p><p><strong>4. Monitor Metrics</strong>: Grafana → Explore → Prometheus</p><h3>What You’ll See in Production</h3><h3>Distributed Traces</h3><ul><li>Complete request flow from WebServiceA → WebServiceB</li><li>Timing information for each operation</li><li>Error propagation and root cause analysis</li></ul><h3>Structured Logs</h3><ul><li>Correlated logs with trace IDs</li><li>Structured JSON logs with contextual information</li><li>Log-to-trace navigation</li></ul><h3>Application Metrics</h3><ul><li>HTTP request rates and latencies</li><li>Custom business metrics</li><li>Service health indicators</li></ul><h3>Service Maps</h3><ul><li>Visual representation of service dependencies</li><li>Performance bottleneck identification</li><li>Error rate visualization</li></ul><h3>Best Practices Implemented</h3><h3>OpenTelemetry Configuration</h3><ol><li><strong>Consistent Resource Attribution</strong>: Each service properly identifies itself</li><li><strong>Batch Processing</strong>: Efficient data transmission</li><li><strong>Sampling Strategies</strong>: Production-ready sampling configuration</li></ol><h3>Infrastructure Design</h3><ol><li><strong>Scalable Architecture</strong>: Distributed components for high availability</li><li><strong>Data Persistence</strong>: Object storage for long-term retention</li><li><strong>Load Balancing</strong>: Proper request distribution</li></ol><h3>Monitoring Strategy</h3><ol><li><strong>Three Pillars</strong>: Comprehensive metrics, logs, and traces</li><li><strong>Correlation</strong>: Seamless navigation between data types</li><li><strong>Alerting</strong>: Prometheus-based alerting rules</li></ol><h3>Conclusion</h3><p>This implementation provides a production-ready observability solution that scales with your applications. The combination of OpenTelemetry for instrumentation and the Grafana stack for storage and visualization gives you complete visibility into your distributed systems.</p><p>Key benefits of this approach:</p><ul><li><strong>Unified Observability</strong>: Single pane of glass for all telemetry data</li><li><strong>Vendor Neutral</strong>: OpenTelemetry ensures no vendor lock-in</li><li><strong>Scalable</strong>: Distributed architecture supports high-throughput applications</li><li><strong>Cost Effective</strong>: Open-source stack reduces operational costs</li></ul><p>The complete example is available in the <a href="https://github.com/alimahboubi/Observability-Example">Observability-Example repository</a> with detailed setup instructions and additional configuration examples.</p><p>Start with this foundation and customize it based on your specific requirements. The modular architecture allows you to add or remove components as needed while maintaining comprehensive observability across your systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0edcf6fe37c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the State Design Pattern in Real-World Scenarios with C#]]></title>
            <link>https://medium.com/@a.mahboubi.dana/mastering-the-state-design-pattern-in-real-world-scenarios-with-c-963c46525d44?source=rss-18ee584f0860------2</link>
            <guid isPermaLink="false">https://medium.com/p/963c46525d44</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[A Mahboubi]]></dc:creator>
            <pubDate>Thu, 03 Apr 2025 14:55:12 GMT</pubDate>
            <atom:updated>2025-04-03T15:10:31.094Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Design patterns are proven solutions to common problems in software design. They provide templates or blueprints that developers can adapt to solve recurring design challenges​ (<a href="https://en.wikipedia.org/wiki/Software_design_pattern#:~:text=In%20software%20engineering%20%2C%20a,a%20software%20application%20or%20system"><em>en.wikipedia.org</em></a>).</p><p>One such pattern is the <strong>State</strong> pattern, a behavioral design pattern that allows an object to alter its behavior when its internal state changes (<a href="https://refactoring.guru/design-patterns/state#:~:text=Intent"><em>refactoring.guru</em></a>).</p><p>In simple terms, the State pattern helps you avoid long if-else or switch statements by encapsulating state-specific behavior into separate classes. This approach is extremely useful in real-world applications where an object can behave differently based on its status or mode.</p><p>In this post, we’ll explore what the State design pattern is and why it’s valuable. We’ll use a <strong>real-world analogy</strong> to clarify the concept and then dive into a <strong>C# example</strong> inspired by a marketplace website’s order processing workflow. By the end, you will understand how to implement the State pattern in C#, know when to use it (and when not to), and see how it improves flexibility, readability, and testability in complex applications.</p><h3>What is the State Design Pattern?</h3><p>The <strong>State design pattern</strong> is a behavioral pattern that <strong>encapsulates the varying behavior of an object based on its internal state into separate state classes</strong>. The object (called the <em>context</em>) delegates state-specific work to an instance of a state class, and can replace that instance to change its behavior at runtime​ (<a href="https://refactoring.guru/design-patterns/state#:~:text=Intent"><em>refactoring.guru</em></a>).</p><p><em>In other words, as an object’s state changes, it appears to change its class</em> because different state objects may exhibit different behavior for the same operations.</p><p><strong>Problem it solves:</strong> The State pattern addresses the problem of an object that has many conditional branches (e.g. huge switch or if-else blocks) to handle different behaviors based on its current state​(<a href="https://refactoring.guru/design-patterns/state#:~:text=State%20machines%20are%20usually%20implemented,code%20structure%20ring%20a%20bell"><em>refactoring.guru</em></a>)(<a href="https://medium.com/@merodyyy/state-design-pattern-af47a2dcc61a#:~:text=Traditionally%2C%20programmers%20used%20to%20implement,is%20in%20a%20particular%20state"><em>medium.com</em></a>).</p><p>This often occurs in finite-state machines or workflows, such as an order that can be new, processed, shipped, etc., each requiring distinct logic. Without the State pattern, adding a new state or modifying behavior means altering the core class and all the conditional logic, making the code hard to maintain and extend ​(<a href="https://medium.com/@merodyyy/state-design-pattern-af47a2dcc61a#:~:text=What%20happens%20if%20we%20want,specific%20behaviour"><em>medium.com</em></a>).</p><p>State pattern solves this by localizing state-specific logic in separate classes and switching between them, adhering to the <em>Open/Closed Principle</em> (open for extension, closed for modification).</p><p><strong>When to use it:</strong> Use the State pattern when an object’s behavior depends on its state and it has to change behavior at runtime depending on that state (<a href="https://neatcode.org/state-pattern/#:~:text=1,When%20different%20states%20require%20specific"><em>neatcode.org</em></a>).</p><p>It’s especially helpful if you have:</p><ul><li>Multiple conditional statements in an object that switch behavior based on a status or state field​ (<a href="https://neatcode.org/state-pattern/#:~:text=different%20state%20objects%2C%20promoting%20clean,This%20helps%20in%20achieving"><em>neatcode.org</em></a>).</li><li>A need to add new states or change transitions in the future, as the pattern makes it easier to extend.</li><li>Complex state-specific logic that would otherwise clutter a single class.</li></ul><p>On the other hand, if an object only has <strong>a couple of states with simple logic</strong>, applying the State pattern might be overkill.(<a href="https://softwareengineering.stackexchange.com/questions/283117/should-i-use-the-state-design-pattern-for-only-two-states-also-what-if-one-obj#:~:text=If%20the%20logic%20for%20changing,put%20holes%20in%20your%20house"><em>softwareengineering.stackexchange.com</em></a>)</p><p>In those cases, a simple conditional check might suffice to keep the design simpler.</p><h3>Real-World Analogy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJQK33b4FFtBCYnTvV7x5Q.png" /></figure><p>To better grasp the State pattern, let’s consider a <strong>marketplace</strong> that sells products from various stores, with a logistics provider handling shipping. Each <strong>customer order</strong> in this system goes through multiple stages:</p><ul><li><strong>Pending (awaiting payment):</strong> When a customer places an order, it initially has not been paid for or processed.</li><li><strong>Processed (payment confirmed):</strong> After the customer’s payment is confirmed, the order can proceed to the logistics step.</li><li><strong>Shipped (in transit):</strong> Once the logistics provider picks up the package, the order transitions to a shipped state.</li><li><strong>Delivered (completed):</strong> Eventually, the package arrives at the customer’s address, and the order is marked as delivered.</li><li><strong>Cancelled (terminated):</strong> At any point (before certain cutoffs), a customer or the seller might cancel the order, putting it into a cancelled or closed state.</li></ul><p>In <strong>each of these states</strong>, the same action (e.g., “cancel order”) can yield different outcomes. A pending order might simply get flagged as cancelled, whereas a shipped order might require initiating a return process instead. The marketplace “context” decides which behavior to invoke by referencing the order’s current state.</p><p>This separation is what the <strong>State design pattern</strong> formalizes. You’d define classes like PendingState, ProcessedState, ShippedState, DeliveredState, and CancelledState, each handling state-specific behavior (e.g., whether cancellation is allowed). The marketplace order object (the <strong>context</strong>) delegates tasks—like transitioning to the next state—to whichever state object it’s currently holding. When the customer completes payment, the order switches to the PaidState; when shipping is initiated, it transitions to the ShippedState, and so on. This design isolates each state’s behavior into its own class, making the code easier to manage and extend.</p><h3>Core Components of the Pattern</h3><p>Like many design patterns, the State pattern consists of a few core pieces working together. In the context of our <strong>marketplace order</strong> scenario, we can break it down as follows:</p><ol><li><strong>Context</strong> — The main object whose behavior changes based on its current state.</li></ol><ul><li>In our example, this is the <strong>order</strong> object. It holds a reference to a state object (e.g., PendingState or ShippedState) and delegates state-specific operations to that object.</li></ul><ol><li><strong>State Interface</strong> — An interface or abstract class that defines the operations common to all states.</li></ol><ul><li>For instance, an IOrderState might include methods like Next(), Prev(), and PrintStatus(). Each state will implement these differently.</li></ul><ol><li><strong>Concrete State Classes</strong> — Implementations of the State interface, each representing a distinct state.</li></ol><ul><li>In a marketplace scenario, these classes would be PendingState, PaidState, ShippedState, DeliveredState, and CancelledState. They determine what should happen when certain actions occur (e.g., can we move forward to the next state, go back, or print a certain status message?).</li></ul><p>By having an interface with clear contracts and multiple state classes, we avoid cluttering our <strong>Order</strong> (context) class with complex if-else or switch statements for all possible states. This way, each concrete state class has only the logic relevant to its particular state, and <strong>the context interacts with the state interface</strong> without needing to know the specific implementation details.</p><p>Next, let’s see how to implement this pattern in C# with a code example that further demonstrates the <strong>State</strong> pattern’s usefulness and clarity in managing an order’s lifecycle.</p><h3>Implementing the State Pattern in C#</h3><p>To demonstrate the State pattern in action, we’ll implement a <strong>simplified order processing workflow</strong> for a sample marketplace website. Consider a customer order that can go through various stages: Pending, Processed, Shipped, Delivered, or Cancelled. Each state will define what the next possible state is (for instance, an order must be processed before it can be shipped) and what happens in that state. Using the State pattern will make our design cleaner and more adaptable than using giant conditional statements.</p><p><strong>Step-by-step breakdown:</strong></p><ol><li><strong>Define a State interface:</strong> This interface will declare actions that depend on state. In our case, we’ll have methods for moving to the <em>next</em> or <em>previous</em> state, and maybe an action to print the current status.</li><li><strong>Implement Concrete States:</strong> For each order status, we create a class (state) that implements the interface. These classes will handle the state-specific behavior and state transitions. For example, the Pending state will move to Processed when advancing to next, whereas the Delivered state might not allow any further transition.</li><li><strong>Create the Context class:</strong> The context (here, Order) will have a reference to the current state (an IOrderState). It will delegate calls to this state object. The context might provide helper methods like NextState() or CancelOrder() that internally use the state object to change state.</li><li><strong>Perform state transitions:</strong> We’ll illustrate how an order instance can transition through states by swapping out its state object. This will show the pattern’s benefit of changing object behavior at runtime.</li></ol><p>Let’s write the C# code for this scenario step by step:</p><pre>// 1. State interface - defines actions for state transitions and behavior<br>public interface IOrderState<br>{<br>    void Next(Order order);<br>    void Prev(Order order);<br>    void PrintStatus();<br>}</pre><pre>// 2. Concrete State classes for each order status:<br><br>// Pending state: initial state of an Order<br>public class Pending : IOrderState<br>{<br>    public void Next(Order order)<br>    {<br>        // Transition from Pending to Processed<br>        order.SetState(new Processed());<br>    }<br>    public void Prev(Order order)<br>    {<br>        Console.WriteLine(&quot;Order is in its initial Pending state; no previous state.&quot;);<br>    }<br>    public void PrintStatus()<br>    {<br>        Console.WriteLine(&quot;Order is currently *Pending*.&quot;);<br>    }<br>}<br><br>// Processed state: payment confirmed, ready to ship<br>public class Processed : IOrderState<br>{<br>    public void Next(Order order)<br>    {<br>        // Transition from Processed to Shipped<br>        order.SetState(new Shipped());<br>    }<br>    public void Prev(Order order)<br>    {<br>        // Go back to Pending if needed<br>        order.SetState(new Pending());<br>    }<br>    public void PrintStatus()<br>    {<br>        Console.WriteLine(&quot;Order has been *Processed* (payment received).&quot;);<br>    }<br>}<br><br>// Shipped state: order is on the way<br>public class Shipped : IOrderState<br>{<br>    public void Next(Order order)<br>    {<br>        // Transition from Shipped to Delivered<br>        order.SetState(new Delivered());<br>    }<br>    public void Prev(Order order)<br>    {<br>        // Go back to Processed (e.g., shipment canceled or delayed)<br>        order.SetState(new Processed());<br>    }<br>    public void PrintStatus()<br>    {<br>        Console.WriteLine(&quot;Order is *Shipped* and in transit.&quot;);<br>    }<br>}<br><br>// Delivered state: final state if not canceled<br>public class Delivered : IOrderState<br>{<br>    public void Next(Order order)<br>    {<br>        Console.WriteLine(&quot;Order is already delivered; no further transition.&quot;);<br>    }<br>    public void Prev(Order order)<br>    {<br>        // Perhaps allow reverting delivery status in some systems:<br>        order.SetState(new Shipped());<br>    }<br>    public void PrintStatus()<br>    {<br>        Console.WriteLine(&quot;Order is *Delivered* to the customer.&quot;);<br>    }<br>}<br><br>// Cancelled state: final state for a called-off order<br>public class Cancelled : IOrderState<br>{<br>    public void Next(Order order)<br>    {<br>        Console.WriteLine(&quot;Order was cancelled; it cannot proceed to another state.&quot;);<br>    }<br>    public void Prev(Order order)<br>    {<br>        Console.WriteLine(&quot;Order was cancelled; it cannot go back to a previous state.&quot;);<br>    }<br>    public void PrintStatus()<br>    {<br>        Console.WriteLine(&quot;Order is *Cancelled*.&quot;);<br>    }<br>}<br><br>// 3. Context class - represents the order and its current state<br>public class Order<br>{<br>    private IOrderState _currentState;<br><br>    public Order()<br>    {<br>        // Initial state is Pending when order is created<br>        _currentState = new Pending();<br>    }<br><br>    public void SetState(IOrderState state)<br>    {<br>        _currentState = state;<br>    }<br><br>    // Helper methods to delegate behavior to the current state<br>    public void NextState()<br>    {<br>        _currentState.Next(this);<br>    }<br>    public void PrevState()<br>    {<br>        _currentState.Prev(this);<br>    }<br>    public void PrintStatus()<br>    {<br>        _currentState.PrintStatus();<br>    }<br><br>    // Optional: a method to cancel the order from any state<br>    public void Cancel()<br>    {<br>        _currentState = new Cancelled();<br>    }<br>}</pre><p>Now we have all the pieces: the IOrderState interface, five concrete state classes (Pending, Processed, Shipped, Delivered, Cancelled), and an Order context that uses them.</p><p><strong>4. Using the context and states:</strong> Let’s simulate an order moving through states to see the State pattern in action:</p><pre>// 4. Example usage of the Order context and state transitions<br>public class Program<br>{<br>    public static void Main(string[] args)<br>    {<br>        Order order = new Order();              // Starts as Pending<br>        order.PrintStatus();                   // &quot;Order is currently Pending.&quot;<br><br>        order.NextState();  // move to Processed<br>        order.PrintStatus();                   // &quot;Order has been Processed (payment received).&quot;<br><br>        order.NextState();  // move to Shipped<br>        order.PrintStatus();                   // &quot;Order is Shipped and in transit.&quot;<br><br>        order.NextState();  // move to Delivered<br>        order.PrintStatus();                   // &quot;Order is Delivered to the customer.&quot;<br><br>        // Try going back a state<br>        order.PrevState();  // back to Shipped (perhaps a correction)<br>        order.PrintStatus();                   // &quot;Order is Shipped and in transit.&quot;<br><br>        // Cancel the order at this point (just for demo; normally you&#39;d cancel earlier)<br>        order.Cancel();<br>        order.PrintStatus();                   // &quot;Order is Cancelled.&quot;<br><br>        // Try advancing after cancellation<br>        order.NextState();                    // &quot;Order was cancelled; it cannot proceed to another state.&quot;<br>    }<br>}</pre><p>Running this program would produce output tracing the order’s state changes. The Order starts in <em>Pending</em>, goes through <em>Processed</em>, <em>Shipped</em>, <em>Delivered</em>, then we simulate a step back to <em>Shipped</em> and finally cancel the order. Notice how each state&#39;s PrintStatus() and transition methods define the behavior in that state. We didn&#39;t write any complex if or switchinside Order to handle these; each state class took care of its own logic.</p><h3>Real-World Use Case: Orders in a Marketplace Web App</h3><p>Let’s put the above example into a real-world context. Imagine a marketplace web application (like an e-commerce site) handling customer orders. An order typically moves through a <strong>lifecycle</strong>: created (pending payment), paid (processed), shipped, delivered, or cancelled at some point.</p><p>Using the State pattern for such an order offers several benefits in a real app:</p><ul><li><strong>Clear structure for business logic:</strong> Each state (Pending, Processed, etc.) has its logic isolated. For instance, the Processed state might trigger charging the customer’s card or sending a confirmation email when entered, the Shipped state might initiate a shipment notification, and the Delivered state might enable a feedback request to the user. By encapsulating these in separate classes, the code for each stage is straightforward and not intertwined with others.</li><li><strong>Controlled transitions:</strong> The pattern makes it explicit which transitions are allowed. The code naturally prevents invalid sequences (you saw that Pending.Prev() simply noted it&#39;s at the initial state, and Delivered.Next() does nothing). This mirrors a real system where, say, you shouldn&#39;t ship an order that hasn’t been processed (paid) yet. Each state class enforces rules like &quot;if already delivered, you can&#39;t go to another state&quot; in one place.</li><li><strong>Ease of extension:</strong> Suppose the marketplace introduces a new order state, like Returned (for product returns) or splits Processed into more detailed states (e.g., PaymentReceived vs. Packed). With the State pattern, you can add a new Returned state class and adjust transitions without overhauling the entire order management logic. The context (Order) doesn’t need to know the details of new states – it remains unchanged. This kind of flexibility is a hallmark of the State pattern (<a href="https://cs.uwaterloo.ca/~m2nagapp/courses/CS446/1181/Arch_Design_Activity/State.pdf#:~:text=Because%20each%20state%20is%20implemented,A"><em>cs.uwaterloo.ca</em></a>). In fact, an order processing workflow is a <em>classic example</em> often used to illustrate the State pattern in action (<a href="https://dotnettutorials.net/lesson/state-design-pattern-real-time-example/#:~:text=Let%E2%80%99s%20consider%20the%20classic%20example,Design%20Pattern%20can%20be%20applied"><em>dotnettutorials.net</em></a>).</li><li><strong>Improved testability:</strong> In a large system, business logic for each state can be unit-tested in isolation. You can instantiate a Processed state and simulate what happens if an order in that state tries to go &quot;next&quot; or &quot;prev&quot;, ensuring it behaves correctly. Similarly, you can test the Order context by injecting a certain state and seeing if it delegates properly. This is much easier than setting up a complex scenario to hit a specific branch of a giant if-else.</li></ul><p>Overall, in a real web application for a marketplace, the State pattern helps manage the order’s lifecycle in a <strong>clean, modular way</strong>. It becomes simple to reason about what happens in each phase of an order, and to modify that behavior as requirements evolve.</p><h3>Common Pitfalls &amp; Tips</h3><p>While the State pattern is powerful, it’s not a silver bullet. Here are some common pitfalls to watch out for and tips to use it effectively:</p><ul><li><strong>Overusing the State pattern:</strong> If your object only ever has two states or very simple conditional logic, using the State pattern might be over-engineering​ (<a href="https://softwareengineering.stackexchange.com/questions/283117/should-i-use-the-state-design-pattern-for-only-two-states-also-what-if-one-obj#:~:text=If%20the%20logic%20for%20changing,put%20holes%20in%20your%20house"><em>softwareengineering.stackexchange.com</em></a>). For example, an object that’s either enabled or disabled probably doesn’t need the full State pattern treatment. In such cases, a simple boolean flag or enum with an if check could suffice. Use the pattern when state-specific complexity justifies it.</li><li><strong>Class explosion:</strong> By design, the State pattern introduces multiple classes (one for each state). In scenarios with many states, this means a lot of classes and files. This is a trade-off: you get cleaner separation at the cost of more classes to manage. Don’t let the number of classes discourage you, but be mindful that <strong>too many trivial states</strong>could complicate the project structure​ (<a href="https://cs.uwaterloo.ca/~m2nagapp/courses/CS446/1181/Arch_Design_Activity/State.pdf#:~:text=cohesion%20as%20behaviour%20associated%20with,with%20a%20monolithic%20if%2Felse%20statement"><em>cs.uwaterloo.ca</em></a>). One tip is to start with the most critical states; if some states are very similar, consider if they can be combined or if using an enum in a single class might be sufficient until the behavior diverges significantly.</li><li><strong>State transitions spread out:</strong> With state logic distributed across classes, it can be a bit tricky to get a holistic view of all possible transitions. In our example, the knowledge of which state comes next is coded in each state’s Next()method. To mitigate any confusion, maintain clear documentation or a state diagram of the workflow. This ensures that when you add a new state or modify transitions, you won&#39;t introduce inconsistencies. In complex scenarios, some implementations use a central transition table or a state manager to define allowed transitions (at the cost of extra complexity).</li><li><strong>Keep states focused:</strong> Ensure each <strong>state class</strong> only handles what it truly needs to. Avoid putting unrelated logic into state classes. For example, the Processed state should probably not handle how to render an order on the UI – it should stick to order-processing logic. Keeping state classes narrowly focused on state-specific behavior helps maintain the <strong>Single Responsibility Principle</strong> and makes them easier to maintain and reuse.</li><li><strong>Refactoring legacy code:</strong> If you have an existing codebase with a lot of switch/if statements on an object&#39;s state, refactoring to the State pattern can be done gradually. Start by defining a state interface for the problematic class’s behavior. Then, pick one state and create a class for it, moving the related code from the original class into the new state class. Update the context class to use this state object when appropriate. Repeat for other states. Over time, the conditional logic in the original class will shrink or disappear, replaced by polymorphic calls. Always have tests in place before and after refactoring to ensure behavior remains correct.</li></ul><h3>Benefits of Using the State Pattern</h3><p>Applying the State pattern can significantly improve a software design in the right circumstances. Here are the key benefits:</p><ul><li><strong>Improved Maintainability:</strong> By localizing state-specific logic in its own classes, the code is easier to modify. Adding a new state or changing behavior in one state doesn’t require tinkering with a monolithic method full of conditionals. This keeps modifications limited to small, focused classes, reducing the chance of side effects​ (<a href="https://cs.uwaterloo.ca/~m2nagapp/courses/CS446/1181/Arch_Design_Activity/State.pdf#:~:text=Because%20each%20state%20is%20implemented,A"><em>cs.uwaterloo.ca</em></a>).</li><li><strong>Separation of Concerns:</strong> Each state class represents a clear, singular concern (one specific mode of the object’s behavior). The context class is freed from internal state logic and simply coordinates states. This separation makes the overall system easier to understand. For example, if there’s a bug when an order is delivered, you know to look at the Delivered state class rather than wading through a giant if-else in Order.</li><li><strong>Cleaner Code and Readability:</strong> The absence of sprawling conditional logic means the code is more readable. The intent is clearer since the class names and methods (e.g., Shipped.Next()) explicitly indicate what&#39;s happening. This aligns with making code more self-documenting. Indeed, the State pattern is known to promote cleaner code and an elegant design by <strong>encapsulating states</strong>​ (<a href="https://neatcode.org/state-pattern/#:~:text=State%20design%20pattern%20is%20a,improved%20scalability%2C%20and%20increased%20flexibility"><em>neatcode.org</em></a>).</li><li><strong>Flexibility and Extensibility:</strong> The design is flexible — new states and new behaviors can be added with minimal impact on existing code (<a href="https://neatcode.org/state-pattern/#:~:text=employed%20to%20represent%20the%20different,changes%20and%20enhancements%20are%20expected"><em>neatcode.org</em></a>). If future requirements introduce an additional state, you can create a new class for it and update the context to start using it at the appropriate time. The existing states and their logic remain untouched (the Open/Closed Principle in action).</li><li><strong>Better Testability:</strong> State classes can be instantiated and tested in isolation, which is great for unit tests. You can also easily simulate sequences of state changes in tests by switching out state objects on the context, ensuring that each transition leads to the expected behavior. This modularity makes it easier to pinpoint issues and verify each piece of logic.</li><li><strong>Reduced Complex Conditional Logic:</strong> Last but not least, by replacing conditional logic with polymorphism, you reduce the cyclomatic complexity of your methods. This can lower the risk of bugs and make the codebase more approachable. Instead of one big method that handles all cases, you have smaller methods split across classes. Each of those is simpler and thus less error-prone.</li></ul><h3>Conclusion</h3><p>In this article, we introduced the <strong>State design pattern</strong> and walked through how it can be applied in real-world scenarios, specifically with a C# example of a marketplace order workflow. We learned that the State pattern allows an object to change its behavior by switching between state objects, leading to cleaner and more maintainable code when an object has multiple modes of operation. By using a simple analogy (vending machine) and a practical example (order states), we saw the clear advantages of this pattern in organizing code for flexibility and clarity.</p><p>Key takeaways are that the State pattern can eliminate messy conditional logic, enforce valid state transitions, and make your code easier to extend and test. However, we also highlighted that it’s important to use the pattern judiciously — not every scenario with an if warrants a new set of state classes.</p><p>I encourage you to identify places in your own projects where an object’s behavior changes based on its state. Try refactoring a small part of that using the State pattern. Start with a simple case (maybe a UI component that behaves differently when enabled/disabled, or a game character with different modes) to get a feel for it. Understanding this pattern will not only improve the immediate design but also sharpen your mindset for clean architecture.</p><p>Design patterns like State are tools in your developer toolbox. Mastering when and how to use them is a step towards writing more robust and elegant code. Keep an eye out for other patterns we’ll explore in future posts, and happy coding!</p><h3>Call to Action</h3><p>If you found this helpful, follow me for more deep dives into design patterns and clean code practices in C#.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963c46525d44" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>