Skip to content
Back to blog
Design Patterns

State Pattern: Managing Complex State Transitions

Updated 18 min read

The State Pattern helps manage complex state-dependent behavior without scattering conditional logic throughout your codebase. Learn how to implement it in TypeScript, model valid transitions, test lifecycle rules, and decide when a state machine or simpler approach is a better fit.

Table of Contents

Introduction

Many objects behave differently depending on their current state.

An order can be confirmed only after it has been created. A payment can be refunded only after it has succeeded. A document can be published only after it has been reviewed. A background job can be retried only when it has failed.

These rules are easy to express when a system has two or three states. The difficulty grows when each state allows different operations, each operation changes the state, and every new requirement introduces additional conditions.

A common first implementation uses a collection of if statements or a large switch block. Over time, those conditions spread across services, controllers, and background workers. The result is a system where the rules governing an object's lifecycle are difficult to locate and even harder to change safely.

The State Pattern offers a way to organize this complexity.

Instead of making one object responsible for every possible state-dependent behavior, the pattern delegates that behavior to objects representing individual states.

The goal is not to eliminate every conditional statement. It is to make the lifecycle rules explicit, keep related behavior together, and reduce the number of places that must change when a state is introduced.

1. The Problem: State-Dependent Behavior Becomes Difficult to Manage

Consider an order management system with the following lifecycle:

  • pending: The order has been created but not confirmed.
  • confirmed: The order has been accepted.
  • shipped: The order has been dispatched.
  • delivered: The order has reached its destination.
  • cancelled: The order has been cancelled.

The system must enforce several rules:

  • A pending order can be confirmed or cancelled.
  • A confirmed order can be shipped or cancelled.
  • A shipped order can be marked as delivered.
  • A delivered order cannot be cancelled through the ordinary cancellation operation.
  • A cancelled order cannot be shipped.

A straightforward implementation might look like this:

typescript
type OrderStatus =
  | "pending"
  | "confirmed"
  | "shipped"
  | "delivered"
  | "cancelled";

class Order {
  constructor(
    public status: OrderStatus = "pending",
  ) {}

  confirm(): void {
    if (this.status !== "pending") {
      throw new Error(
        "Only pending orders can be confirmed",
      );
    }

    this.status = "confirmed";
  }

  ship(): void {
    if (this.status !== "confirmed") {
      throw new Error(
        "Only confirmed orders can be shipped",
      );
    }

    this.status = "shipped";
  }

  deliver(): void {
    if (this.status !== "shipped") {
      throw new Error(
        "Only shipped orders can be delivered",
      );
    }

    this.status = "delivered";
  }

  cancel(): void {
    if (
      this.status !== "pending" &&
      this.status !== "confirmed"
    ) {
      throw new Error(
        "This order cannot be cancelled",
      );
    }

    this.status = "cancelled";
  }
}

For a small domain, this implementation is perfectly reasonable. The rules are visible, the code is easy to follow, and there is no need to introduce additional abstractions yet.

The problem emerges as the domain grows.

Suppose the business adds partial shipment, payment verification, delivery failures, returns, and refunds. Each operation may need to check several conditions. Some conditions may also depend on payment status, inventory availability, or user permissions.

Soon, the code starts mixing different concerns:

  • Which operations are allowed in the current state?
  • What validation must run before an operation?
  • What side effects should happen after a transition?
  • Which state should follow a successful operation?
  • What should happen when an operation is invalid?

When these responsibilities spread across multiple classes, enforcing a consistent lifecycle becomes increasingly difficult.

The design problem is not the existence of conditionals. It is the growing amount of state-dependent behavior that must remain consistent across the system.

2. The Core Idea Behind the State Pattern

The State Pattern delegates behavior to an object representing the current state.

The main participants are:

  • Context: The object whose behavior changes according to its state.
  • State interface: Defines the operations the context can delegate.
  • Concrete states: Implement the behavior allowed in particular states.

For the order example, the Order object acts as the context. Instead of implementing every operation itself, it delegates operations to its current state object.

Conceptually:

classDiagram
  class Order {
    -state: OrderState
    +confirm()
    +ship()
    +deliver()
    +cancel()
  }
  class OrderState {
    <<interface>>
    +confirm(order)
    +ship(order)
    +deliver(order)
    +cancel(order)
  }
  Order --> OrderState : delegates operations
  OrderState <|.. PendingState
  OrderState <|.. ConfirmedState
  OrderState <|.. ShippedState
  OrderState <|.. DeliveredState
  OrderState <|.. CancelledState

When the order transitions from pending to confirmed, the context replaces its current state object with a ConfirmedState.

Subsequent operations are handled by the new state object rather than by the previous one.

This changes the structure of the code. Instead of asking a single object to inspect its state repeatedly, the system lets the current state determine which behavior is valid.

A key distinction is that the State Pattern organizes state-dependent behavior, while a state machine explicitly models states and transitions. The two approaches can be used together, but they are not identical.

3. Implementing the State Pattern in TypeScript

Let's implement a simplified order lifecycle.

The example deliberately keeps persistence and external side effects out of the state classes. Its purpose is to demonstrate the pattern's structure without introducing unrelated infrastructure.

3.1 Define the state interface

First, define the operations that an order state can handle.

typescript
interface OrderState {
  readonly name: OrderStatus;

  confirm(order: Order): void;
  ship(order: Order): void;
  deliver(order: Order): void;
  cancel(order: Order): void;
}

type OrderStatus =
  | "pending"
  | "confirmed"
  | "shipped"
  | "delivered"
  | "cancelled";

Every concrete state implements the same interface.

This allows the Order context to delegate operations without knowing the concrete class currently handling them.

3.2 Implement the pending state

A pending order can be confirmed or cancelled. Other operations are rejected.

typescript
class PendingState implements OrderState {
  readonly name = "pending";

  confirm(order: Order): void {
    order.transitionTo(
      new ConfirmedState(),
    );
  }

  ship(_order: Order): void {
    throw new Error(
      "A pending order cannot be shipped",
    );
  }

  deliver(_order: Order): void {
    throw new Error(
      "A pending order cannot be delivered",
    );
  }

  cancel(order: Order): void {
    order.transitionTo(
      new CancelledState(),
    );
  }
}

Notice that the state object contains the rules for the pending state.

It knows which operations are valid and what the next state should be.

It does not need to manage every possible order lifecycle.

3.3 Implement the confirmed state

A confirmed order can be shipped or cancelled.

typescript
class ConfirmedState implements OrderState {
  readonly name = "confirmed";

  confirm(_order: Order): void {
    throw new Error(
      "The order is already confirmed",
    );
  }

  ship(order: Order): void {
    order.transitionTo(
      new ShippedState(),
    );
  }

  deliver(_order: Order): void {
    throw new Error(
      "A confirmed order cannot be delivered",
    );
  }

  cancel(order: Order): void {
    order.transitionTo(
      new CancelledState(),
    );
  }
}

The confirmed state defines a different set of valid operations without requiring the Order context to add another branch.

3.4 Implement the remaining states

The shipped state allows delivery, but not confirmation, shipping again, or ordinary cancellation.

typescript
class ShippedState implements OrderState {
  readonly name = "shipped";

  confirm(_order: Order): void {
    throw new Error(
      "A shipped order cannot be confirmed",
    );
  }

  ship(_order: Order): void {
    throw new Error(
      "The order has already been shipped",
    );
  }

  deliver(order: Order): void {
    order.transitionTo(
      new DeliveredState(),
    );
  }

  cancel(_order: Order): void {
    throw new Error(
      "A shipped order cannot be cancelled",
    );
  }
}

class DeliveredState implements OrderState {
  readonly name = "delivered";

  confirm(_order: Order): void {
    throw new Error(
      "A delivered order cannot be confirmed",
    );
  }

  ship(_order: Order): void {
    throw new Error(
      "A delivered order cannot be shipped",
    );
  }

  deliver(_order: Order): void {
    throw new Error(
      "The order has already been delivered",
    );
  }

  cancel(_order: Order): void {
    throw new Error(
      "A delivered order cannot be cancelled",
    );
  }
}

class CancelledState implements OrderState {
  readonly name = "cancelled";

  confirm(_order: Order): void {
    throw new Error(
      "A cancelled order cannot be confirmed",
    );
  }

  ship(_order: Order): void {
    throw new Error(
      "A cancelled order cannot be shipped",
    );
  }

  deliver(_order: Order): void {
    throw new Error(
      "A cancelled order cannot be delivered",
    );
  }

  cancel(_order: Order): void {
    throw new Error(
      "The order is already cancelled",
    );
  }
}

This implementation is intentionally explicit. The repeated methods reveal a trade-off: a uniform interface makes delegation simple, but every state must implement operations that may not be meaningful for it.

For a larger lifecycle, you could use more focused interfaces, a transition map, or a state machine library instead of implementing every operation in every state class.

3.5 Build the context

The Order class holds the current state and delegates its public operations.

typescript
class Order {
  private state: OrderState;

  constructor() {
    this.state = new PendingState();
  }

  get status(): OrderStatus {
    return this.state.name;
  }

  confirm(): void {
    this.state.confirm(this);
  }

  ship(): void {
    this.state.ship(this);
  }

  deliver(): void {
    this.state.deliver(this);
  }

  cancel(): void {
    this.state.cancel(this);
  }

  transitionTo(nextState: OrderState): void {
    this.state = nextState;
  }
}

Now the context no longer contains a collection of state-dependent conditionals.

Usage remains straightforward:

typescript
const order = new Order();

order.confirm();
console.log(order.status); // confirmed

order.ship();
console.log(order.status); // shipped

order.deliver();
console.log(order.status); // delivered

order.cancel(); // Throws an error

The current state determines the behavior of each operation.

The public API remains stable even though the internal implementation changes as the order moves through its lifecycle.

3.6 What this implementation does—and does not—guarantee

This is a useful demonstration of the State Pattern, but it is not a complete production workflow engine.

In particular:

  • transitionTo() is public in this example, so callers can bypass the intended rules.
  • Each transition creates a new state object, even though the state objects contain no per-order data.
  • Invalid transitions use generic errors rather than domain-specific error types.
  • The current state exists only in memory.
  • No authorization, persistence, concurrency control, or external side effects are implemented.

A production implementation should narrow access to transition methods, use explicit domain errors, and decide how lifecycle changes are persisted.

State objects can also be shared when they are stateless. If they hold order-specific mutable data, sharing them would introduce correctness problems.

The pattern improves organization; it does not automatically make a workflow secure or transactionally correct.

4. Understanding State Transitions and Their Invariants

A state is more than a label. It represents a set of conditions that must remain true for the object.

For example, a delivered order should not be treated as an order awaiting shipment. A cancelled order should not accidentally re-enter the shipping workflow.

These expectations are called invariants: rules that must remain true throughout the object's lifecycle.

One way to make the lifecycle easier to reason about is to document its allowed transitions explicitly.

Current stateOperationNext state
PendingConfirmConfirmed
PendingCancelCancelled
ConfirmedShipShipped
ConfirmedCancelCancelled
ShippedDeliverDelivered
DeliveredAny listed transitionRejected
CancelledAny listed transitionRejected

This table gives developers, testers, and product stakeholders a shared description of the lifecycle.

It also helps identify missing requirements. For example, if a shipment fails, should the order return to confirmed, move to delivery_failed, or enter a manual review state? That is a domain decision, not something the design pattern can determine.

State transitions should be explicit

An important design choice is who owns the transition.

There are two common approaches.

Approach A: The current state chooses the next state.

This is what the preceding example demonstrates:

typescript
ship(order: Order): void {
  order.transitionTo(
    new ShippedState(),
  );
}

This approach works well when each state has a manageable set of behaviors and transitions.

Approach B: A dedicated transition mechanism validates the transition.

For example, a central transition table might define valid pairs of current state and next state:

typescript
const allowedTransitions: Record<
  OrderStatus,
  readonly OrderStatus[]
> = {
  pending: ["confirmed", "cancelled"],
  confirmed: ["shipped", "cancelled"],
  shipped: ["delivered"],
  delivered: [],
  cancelled: [],
};

function canTransition(
  from: OrderStatus,
  to: OrderStatus,
): boolean {
  return allowedTransitions[from].includes(to);
}

This is not a replacement for all state-dependent behavior. It is a useful way to centralize transition rules when the lifecycle itself is the main concern.

The two approaches can be combined, but avoid defining the same transition rules independently in multiple places. Duplicated sources of truth tend to drift.

State changes may have business consequences

A real order workflow might require several actions when shipping an order:

  1. Verify that payment is complete.
  2. Reserve or confirm inventory.
  3. Create a shipment record.
  4. Persist the new order state.
  5. Publish an event for downstream systems.

These actions introduce a more important question: what happens if one step succeeds and a later step fails?

The State Pattern does not answer this by itself.

For example, changing the in-memory state before a database update succeeds can leave the application inconsistent. Publishing an event before the transaction commits can cause another service to observe a transition that was never persisted.

For business-critical workflows, treat a transition as a domain operation with clear transaction boundaries. Depending on the architecture, this may involve a database transaction, optimistic locking, an outbox, or a workflow orchestrator.

Also consider concurrent requests. Two workers may attempt to ship the same order simultaneously. Both can read confirmed before either writes shipped. A state object alone cannot prevent that race; persistence-level concurrency control is needed.

5. Testing State-Dependent Behavior

The State Pattern makes testing more structured because each state has a defined set of valid and invalid operations.

Rather than testing only whether the final status is correct, test the lifecycle contract.

Test valid transitions

typescript
import {
  describe,
  expect,
  it,
} from "vitest";

describe("Order state transitions", () => {
  it("moves from pending to confirmed", () => {
    const order = new Order();

    order.confirm();

    expect(order.status).toBe("confirmed");
  });

  it("moves from confirmed to shipped", () => {
    const order = new Order();

    order.confirm();
    order.ship();

    expect(order.status).toBe("shipped");
  });

  it("moves from shipped to delivered", () => {
    const order = new Order();

    order.confirm();
    order.ship();
    order.deliver();

    expect(order.status).toBe("delivered");
  });
});

Test invalid transitions

typescript
it("rejects shipping a pending order", () => {
  const order = new Order();

  expect(() => order.ship()).toThrow(
    "A pending order cannot be shipped",
  );

  expect(order.status).toBe("pending");
});

The second assertion matters. A rejected operation should not accidentally change the state.

Test the transition matrix

For a more complex workflow, use table-driven tests to cover the allowed and rejected transitions systematically.

The goal is to verify every transition in the lifecycle specification, not just the happy path.

Also test important business invariants:

  • A cancelled order cannot be shipped.
  • A delivered order cannot be cancelled through the ordinary cancellation operation.
  • A failed operation does not leave partially updated state.
  • Concurrent requests cannot perform the same irreversible transition twice.
  • Side effects are emitted only when the transition is successfully committed.

The last two requirements usually need tests involving the persistence layer or application service, not merely isolated state objects.

A well-designed state model should make these rules easier to test, but it does not eliminate the need to test integration behavior.

6. State Pattern vs. Strategy Pattern vs. Finite State Machines

These approaches are related, but they solve different problems.

State Pattern

Use the State Pattern when an object's behavior changes according to its current state and those behaviors belong together.

For example, an order's available operations depend on whether it is pending, shipped, or delivered.

The state often changes as operations succeed.

Strategy Pattern

Use the Strategy Pattern when you need to select an interchangeable algorithm or policy.

For example, a checkout service might choose a payment calculation strategy based on the selected payment method.

The selected strategy does not necessarily represent the lifecycle of the checkout object.

Finite state machines

A finite state machine (FSM) explicitly defines:

  • A finite set of states.
  • Events or inputs that trigger transitions.
  • Rules determining which transitions are valid.
  • Optional actions associated with transitions or states.

An FSM is particularly useful when the workflow's transition rules need to be represented, inspected, tested, or visualized as a complete model.

A state machine can be implemented using the State Pattern, a transition table, a dedicated library, or a workflow engine. The best representation depends on the complexity of the lifecycle.

ApproachPrimary questionTypical example
StateWhat behavior is valid in this state?Order lifecycle behavior
StrategyWhich algorithm should perform this task?Payment calculation
Finite state machineWhich transitions are allowed for each event?Approval workflow
Workflow engineHow should long-running, durable processes execute?Multi-step onboarding across services

These are not mutually exclusive alternatives.

An order domain may use state objects for behavior, an FSM-style transition model for lifecycle validation, and a workflow engine for long-running operations involving external services.

The key is to choose the smallest abstraction that captures the actual complexity.

7. Common State Pattern Mistakes

7.1 Creating a class for every trivial status

Not every status requires its own class.

If an object has two states and only one behavior differs, a small conditional or a discriminated union may be easier to understand.

Introducing multiple classes too early can increase navigation and maintenance costs without improving the design.

7.2 Allowing transitions from anywhere

If every caller can directly replace the current state, the system can bypass its own lifecycle rules.

Keep state mutation behind a controlled API. Callers should request domain operations such as confirm() or ship() rather than arbitrarily assigning a new status.

7.3 Duplicating transition rules

If a state class, controller, service, and database layer each maintain separate versions of the same transition matrix, they can disagree.

Choose a clear source of truth for domain transition rules. Other layers may validate input or enforce persistence constraints, but they should not independently invent different lifecycle semantics.

7.4 Putting all business logic inside state classes

State classes should own behavior that genuinely depends on the state.

They should not automatically absorb every concern related to an operation. Database transactions, external API calls, authorization, and messaging may belong in application services or dedicated collaborators.

For example, the rule that only a confirmed order may be shipped is domain behavior. The details of calling a carrier API and retrying network requests are usually separate concerns.

7.5 Treating an in-memory state change as a durable transition

Changing this.state does not guarantee that the transition has been persisted.

This matters especially in distributed systems, where processes restart, requests are retried, and multiple workers may act on the same entity.

If state must survive restarts, persist it. If transitions must be atomic or exclusive, use the appropriate transactional and concurrency mechanisms.

7.6 Ignoring state restoration

When loading an existing order from a database, the application must reconstruct its state correctly.

A production design should decide how persisted status values map to state behavior and how to handle unknown or deprecated statuses during deployments and migrations.

A constructor that always initializes the order to pending is appropriate for creating a new order, but not for restoring an existing one.

8. When Should You Use the State Pattern?

The State Pattern is a strong candidate when:

  • Several operations behave differently depending on the current state.
  • State-dependent conditionals are repeated across methods or classes.
  • The lifecycle has enough complexity that its rules need a clear home.
  • Each state has meaningful behavior, not just a different name.
  • You expect state-specific behavior to evolve independently.

It is less compelling when:

  • The object has only a few simple states.
  • State-dependent behavior consists of one or two straightforward checks.
  • Most states behave identically.
  • A transition table expresses the domain more clearly than separate classes.
  • The complexity comes primarily from long-running orchestration across services rather than local object behavior.

Before introducing the pattern, ask three questions:

  1. Are state-dependent rules becoming difficult to locate or keep consistent?
  2. Would grouping behavior by state make changes easier to reason about?
  3. Does that benefit justify the extra classes and indirection?

If the answer to these questions is no, keep the simpler implementation.

Design patterns are tools for managing complexity, not requirements that every codebase must satisfy.

Summary

The State Pattern organizes state-dependent behavior by delegating operations to objects representing the current state.

It can make complex lifecycles easier to understand by bringing related rules together and reducing scattered conditional logic. It also creates a clearer structure for testing valid transitions, rejecting invalid operations, and evolving individual states.

However, the pattern does not automatically guarantee valid persistence, transaction safety, or concurrency correctness. Those concerns still require explicit architectural decisions.

Use the State Pattern when state-dependent behavior is a genuine source of complexity. Use a transition table or finite state machine when the lifecycle itself needs to be modeled explicitly. Use a workflow engine when the problem extends into durable, long-running orchestration.

The best design is not the one with the most patterns. It is the one that makes the system's rules easiest to understand, enforce, and change safely.

  • Design Patterns
  • State Pattern
  • OOP
  • Programing
  • Software Architecture
  • Finite State Machine
  • State Transitions
Have a similar problem?

If something here resonates with a problem you're working on, let's talk.

Let's talk
Keep reading
Design Patterns · 19 min read

When Design Patterns Become Anti-Patterns

Design patterns solve recurring software design problems, but applying them without a clear purpose can introduce unnecessary complexity. Learn how to recognize overengineering, evaluate abstractions, and choose designs that make software easier to understand, test, and change.

Design Patterns · 17 min read

Unit of Work: Coordinating Data Changes

The Unit of Work Pattern helps coordinate multiple persistence operations as one business transaction. Explore a practical TypeScript example, learn how it works with repositories, and understand the limits of rollback, transaction boundaries, retries, and distributed systems.

Design Patterns · 17 min read

Repository Pattern: Abstraction or Unnecessary Layer?

The Repository Pattern can separate application logic from persistence, but it can also become an unnecessary wrapper around an ORM. Learn how to design meaningful repository contracts in TypeScript, test them effectively, and decide when direct database access is the simpler choice.