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