DEV Community

Duplicate refunds from scattered status checks: fixing it with the State pattern in C#

This post was originally published in Portuguese on my blog: Status de pedido com if espalhado gera estorno duplo -> State.

Every order system has an Order class with a Status property. At first there are three or four statuses, each action checks the current status with an if, and everything is fine. The trouble shows up months later, when a new status arrives and nobody remembers all the places that needed to know about it.

In this post I'll show a very concrete case of that, a refund paid twice, and how the State pattern solves it without ceremony.

The problem

The order goes through Pending, Paid, Shipped and Delivered, and it can be cancelled before shipping. If it was already paid, cancelling issues a refund.

The Cancel() method in the "before" version is the kind of code everyone has written:

public void Cancel() {
  if (Status is OrderStatus.Shipped or OrderStatus.Delivered or OrderStatus.Cancelled)
    throw new InvalidOperationException($"Cannot cancel an order that is {Status}.");
  if (Status != OrderStatus.Pending)
    RefundCount++;
  Status = OrderStatus.Cancelled;
}

Look at the first condition: it's a list of what is not allowed. And the second one assumes that anything that isn't Pending has been paid. As long as the enum had only those statuses, both assumptions were true.

Then the business asked for returns. Someone created the Returned status and the new method, with a refund:

// Added later, when returns became a requirement.
// Nobody remembered to update Cancel().
public void Return() {
  if (Status != OrderStatus.Delivered)
    throw new InvalidOperationException($"Cannot return an order that is {Status}.");
  RefundCount++;
  Status = OrderStatus.Returned;
}

Return() is correct. The bug is in Cancel(), which nobody opened: Returned isn't in the forbidden list and isn't Pending, so a returned order can be cancelled and the customer gets refunded a second time.

No test broke, because the existing tests didn't know Returned existed. In the project I left a test, Cancelling_a_returned_order_refunds_twice, that documents exactly this behavior in the old version.

That's the real pain of the status-based if: each status's rules end up scattered across every method. To add a status you have to review every action, and the compiler doesn't warn you about any of them.

The solution: the State pattern

The idea is to flip the question. Instead of every action asking "what status am I in?", each status becomes a class that knows which actions it accepts. The order only holds the current state and delegates to it.

The base class forbids everything by default:

// Base state: every action is forbidden unless a state allows it.
public abstract class OrderState {
  public abstract OrderStatus Status { get; }
  public virtual OrderState Pay(Order order) => throw NotAllowed("pay");
  public virtual OrderState Ship(Order order) => throw NotAllowed("ship");
  public virtual OrderState Deliver(Order order) => throw NotAllowed("deliver");
  public virtual OrderState Cancel(Order order) => throw NotAllowed("cancel");
  public virtual OrderState Return(Order order) => throw NotAllowed("return");
  private InvalidOperationException NotAllowed(string action) => new($"Cannot {action} an order that is {Status}.");
}

This "forbidden by default" is the most important point of the design. A new state is born with no permissions at all, and you explicitly allow what makes sense. It's the opposite of the old Cancel()'s forbidden list.

Each state overrides only what it allows and returns the next state. The refund for a cancellation lives where it makes sense, in PaidState:

public sealed class PaidState : OrderState {
  public override OrderStatus Status => OrderStatus.Paid;
  public override OrderState Ship(Order order) => new ShippedState();
  public override OrderState Cancel(Order order) {
    order.IssueRefund();
    return new CancelledState();
  }
}

The Order class in the "after" version became trivial: a _state field that starts as PendingState, and each action is a one-liner like public void Cancel() => _state = _state.Cancel(this);. The refund is done by IssueRefund(), marked internal so that only the states, in the same assembly, can call it.

And ReturnedState? It only declares its own Status. It doesn't override Cancel, so cancelling a returned order throws InvalidOperationException with "Cannot cancel an order that is Returned." without anyone having to remember it.

What changed in practice

First, the bug goes away by construction, not by discipline. The Cancelling_a_returned_order_is_rejected test checks that the cancellation is refused, that the status stays Returned and that RefundCount stays at 1.

Second, reading the code changes. To know what a paid order can do, you open PaidState and everything is there, in a few lines. In the old version you had to read the five methods of Order and assemble the state machine in your head.

Third, extension becomes local. A new status, like "being picked" or "awaiting pickup", is a new class plus a tweak to the state that leads to it. The other states aren't touched.

Tests also get more direct: each transition has a short test, and refusals are tested by the exception message.

When NOT to use it

State has a cost, and it's not a small one. You trade one file for several, and whoever arrives at the code has to understand the pattern before finding where each rule lives. For a three-status flow that never changes, a well-written switch is more honest and easier to read.

It also isn't worth it when the transitions are basically data, with no behavior: if all you need is "from A you can go to B or C", a transition table (a dictionary, or even a database table) solves it with less code and lets you change it without a deploy. State shines when each transition carries its own behavior, like the refund here, sending an email or reserving stock.

Another thing to watch is persistence. In the database you keep storing the Status enum, and when loading the order you need to rebuild the state object from it. It's a simple mapping, but it's one more piece to maintain. And if the states start accumulating dependencies (repositories, payment gateways), stop and think: maybe the rule belongs in an application service, and the state should only say whether the transition is allowed.

My rule of thumb: if you've already fixed a bug because of a status forgotten in some if, or if the status enum got its fifth value, State is worth considering.

How to run it

The project has both versions side by side, in the Before and After folders, with tests for each. All you need is Docker installed:

cd 2026-11-order-status-state-pattern
docker compose run --rm tests

The full code is on GitHub: programero-csharp/2026-11-order-status-state-pattern.

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.