Skip to content
Katabench
Try free

Adopt the State That Comes Back

Hard About 35 min Free, no account needed

Move lifecycle decisions into state objects and adopt every returned successor, so state transitions remain substitutable across a whole sequence.

The brief

The publication workflow stores a state-name string and checks combinations of that string and each incoming action. Every lifecycle change reopens the workflow class, even though that class should only carry the current state and advance it.

Introduce IWorkflowState with a get-only string Name and Transition Step(string action). A sealed immutable Transition carries get-only IWorkflowState Next and string Message. Workflow accepts its initial state in the constructor. Each Apply calls the current state's Step exactly once, adopts the returned Next state, and returns its Message. StateName reads the current state's Name. The workflow must know no concrete state classes.

Implement four sealed states preserving these transitions:

Current state Action Next state Message
draft submit review submitted
review approve published published
review revise draft revised
published archive archived archived

Every unlisted action keeps the same state and returns ignored:<action>. The archived state has no outgoing transition. The root supplies DraftState.

Preserve Run(string[] actions): join action messages with |, then append ;state:<final-name>. With no actions the result is ;state:draft. Do not mutate the action array.

A decorative state interface can still leave the string switch in control. The trusted probe supplies a state that creates a uniquely named successor after every call. Its later answers depend on using the returned successor, so always calling the initial state or rebuilding a known concrete state fails.

How it is graded

Executable structural checks grade the shape of your types as well as their behavior.

SOLID principles exercises →

What it practices

State pattern
Move lifecycle decisions into state objects that return their successors.

Related katas