A concrete C# case where checking an order's status with if in every method leads to a returned order being refunded twice. The article moves the rules into state classes with the State pattern, so the bug disappears by design.
Key points
- The old `Cancel()` listed forbidden statuses and assumed everything else had been paid.
- The later `Returned` status broke no test, because existing tests did not know it existed.
- The `OrderState` base class forbids every action by default; states override only what they allow.
- Refunds happen only in `PaidState` through `IssueRefund()`, exposed as `internal`.
- `ReturnedState` declares just its `Status`, so cancellation is rejected without extra code.
- When transitions are pure data, a dictionary or table beats State with far less code.
Why it matters
Nothing here ships a new API; it names a mistake nearly every order or subscription codebase makes. Adding an enum value and forgetting to revisit every method produces a silent regression the compiler never flags, and you usually learn about it from a customer. If your status enum is heading past four values, the pattern is worth a look, but count the cost: more files to navigate, and since the database still stores the enum you must rebuild the state object on load. My own preference is to model transitions as data first and reach for State only where a transition carries behavior; once a state needs a repository or a payment gateway, the rule belongs in an application service instead. Global relevance: no version, no date. Change de design.
Real-world use
- Order management that issues a refund on post-payment cancellation, the source of the double-refund bug
- An e-commerce flow with pre-shipping cancellation across Pending, Paid, Shipped, Delivered and Returned
- Flows where each transition carries its own behavior: refunds, sending email, reserving stock
This summary was generated by the agent from the original post on DEV Community: #csharp. The full text and all rights belong to its author and publisher. Go to original