Polski

Subscription lifecycle as a state machine

A SaaS subscription moves through trial, active, past-due and cancelled. Every state is a separate class that decides about transitions itself – no ever-growing switch.

medium · typescript · javascript · python · csharp · java · go · 20 XP

An online course platform sells subscriptions. Its pay() method has five switch (status) branches today, and paymentFailed() and cancel() have more, with a failed-payment counter kept in a field that only makes sense in one status. Every new rule means changes in three places. The State pattern turns statuses into objects: the subscription (the context) delegates every operation to the current state, and the state itself decides whether and where to go next.

Task

The Subscription context is almost ready: it keeps the current state, the history of entered states and the transitionTo(state) method used by the states. Delegation is missing – pay(), paymentFailed(), cancel() and hasAccess() must pass the call to the current state. Four states are to be written:

Statepay()paymentFailed()cancel()Access
trial→ active→ cancelled→ cancelledyes
activeno change→ past-due→ cancelledyes
past-due→ activecounter + 1; at 3 → cancelled→ cancelledyes (grace period)
cancellederrorerrornothing happensno
  • past-due starts with the counter at 1; the third failed payment in a row cancels the subscription. A payment resets the counter (back to active).
  • The counter belongs to one subscription – two past-due subscriptions must not share it.
  • The error in cancelled has the message Subscription is cancelled (Go: ErrCancelled).
  • "No change" means no transitionTo call – the history gets no new entry.

The tests also plug in their own state (an account freeze) via transitionTo and check that the subscription really delegates to the state object. Language differences: payment_failed, has_access(), transition_to and RuntimeError (Python); HasAccess as a property, InvalidOperationException (C#); IllegalStateException (Java); in Go the methods return error and NewSubscription() creates a subscription in the trial state.

Topics: State

Related articles