Payment Command Parser and Lifecycle State Machine Design
Data Structure DesignModel answerLast updated
Design a parser for fixed-arity payment commands and an object-oriented lifecycle state machine, and identify which business rules need clarification before implementation.
You are asked to design the core of a small command-driven payment module. Commands arrive as text lines. Every command has an operation token followed by exactly four argument positions. Positions that a command does not use are filled with an empty quoted string.
CREATE id payer payee amount
APPROVE id "" "" amount
CAPTURE id "" "" amount
CANCEL id "" "" ""
The partial lifecycle you were given is:
CREATED -> APPROVED
APPROVED -> PARTIALLY_CAPTURED or SUCCEEDED
PARTIALLY_CAPTURED -> SUCCEEDED
Cancellation is described as applying to payments that have not yet been approved. The description may be incomplete or partly wrong.
Ground rules
- This is a design exercise over an incomplete specification. Do not invent undocumented behavior and present it as given.
- Always keep the four argument positions, including empty ones.
- Do not assume that the approved amount must equal the created amount, that capture amounts are increments rather than cumulative totals, or that repeated partial captures are allowed.
- It is unclear whether
CANCEL idis targeted or whether a bulk "cancel all unapproved payments" exists. Leave this open until clarified. - Money movement, balances, concurrency, currency format and output format are all unspecified. Define clean boundaries around these instead of guessing.
Part 1: Parsing. Describe a parser that preserves every argument position and produces a typed command object. Explain where syntax validation ends and payment-rule validation begins.
Part 2: States and policy boundaries. Design the payment objects and the command handler around the given transitions. List the missing rules you would need clarified before building a complete monetary state machine, and show how your design isolates those rules.
Also state the clarifying questions you would ask first.
Hints
Hint 1
Separate three layers: tokenizing text into fixed slots, converting slots into a typed command, and applying that command to a payment. Only the last layer may change state.
Hint 2
Represent the transition table as data in one place, keyed by current state and operation, so that unclear rules become small, replaceable policies instead of scattered if-statements.
Hint 3
Treat capture arithmetic, amount equality and cancel scope as injectable policies with a clearly documented default of 'reject as unspecified', and make the handler validate fully before it mutates anything.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarifying questions first
Before coding, I would ask:
- Amounts: What is the representation (integer minor units or decimal string), the valid range, and the relationship between created, approved and captured amounts?
- Capture semantics: Does
CAPTUREadd an increment or set a cumulative total? Can a payment stayPARTIALLY_CAPTUREDafter further captures? What exactly makes itSUCCEEDED? - Cancel scope: Is
CANCEL idtargeted, or is there a bulk operation? What about payments already in a terminal state? - Error cases: Duplicate
CREATE, repeatedAPPROVE, unknown ID, malformed lines, invalid transitions: what should each return? - Output: Is there a required output or error format?
Until answered, I implement only what is given and isolate the rest.
Part 1: Parser
Pipeline: raw line -> tokens -> RawCommand -> typed Command.
- Tokenizer. A small scanner that handles quoted strings, so
""becomes an empty-string token rather than being dropped. Splitting on whitespace is a common bug because it loses placeholders and shifts positions. - Arity check. Require exactly 1 operation token plus 4 argument slots. Anything else is a
MalformedCommanderror. - Per-operation schema. Each operation declares which slots are required and which must be empty:
CREATE: id, payer, payee, amount all non-empty.APPROVE/CAPTURE: id and amount non-empty, slots 2 and 3 empty.CANCEL: id non-empty, the other three empty.
- Amount conversion. Parse explicitly (for example, a non-negative integer in minor units, or a decimal parsed with a decimal type, never a float). Failure yields
InvalidAmount. The exact format is a clarification item, so the conversion lives behind oneAmountParserinterface. - Typed output. Produce immutable objects such as
CreateCommand(id, payer, payee, amount),ApproveCommand(id, amount),CaptureCommand(id, amount),CancelCommand(id).
Boundary: the parser answers "is this a well-formed command?" It must not look up payments, compare states, or mutate anything. Payment-rule validation (does the ID exist? is the transition legal? is the amount acceptable?) belongs to the handler.
Part 2: States and policy boundaries
Core types
PaymentStateenum:CREATED, APPROVED, PARTIALLY_CAPTURED, SUCCEEDED, plusCANCELEDonly if clarified as a state.Payment: id, payer, payee, created amount, state, and whatever amounts later turn out to be needed (approved, captured).PaymentStore: map from ID toPayment.CommandHandler: the only component that applies commands.
Transition table (data, not scattered code)
(CREATED, APPROVE) -> APPROVED
(APPROVED, CAPTURE) -> PARTIALLY_CAPTURED | SUCCEEDED (decided by capture policy)
(PARTIALLY_CAPTURED, CAPTURE) -> SUCCEEDED (as sketched)
(CREATED, CANCEL) -> canceled outcome (as described)
Everything not in the table is InvalidTransition. The state is separate from the operation identity: a command says what is requested, the payment says where it is, and one function next(state, command) decides.
Handler flow
- Look up the payment (
UnknownPaymentif absent, except forCREATE, which rejects duplicates). - Ask the transition table whether the (state, operation) pair is allowed.
- Ask the relevant policy to validate amounts and compute the resulting values and next state.
- Only if everything passed, apply the change in one step (build a new
Paymentvalue and replace it in the store). This gives validate-then-mutate behavior, so a failed command leaves no partial effects.
Policies as interfaces (the unresolved rules)
CapturePolicy: decides whether the amount is an increment or cumulative, whether it may exceed the approved amount, and whether the result is partial or complete. Default: reject withUnspecifiedRulerather than guess; tests can plug in a candidate rule once clarified.ApprovalPolicy: whether the approved amount must match the created amount.CancelPolicy: targeted versus bulk, and behavior for non-CREATEDpayments. I would implement targeted cancel of aCREATEDpayment as described, and keep any bulk operation out until confirmed.
Errors
Use a small typed hierarchy: MalformedCommand, InvalidAmount, DuplicatePayment, UnknownPayment, InvalidTransition, PolicyViolation. Each has a stable code so that whatever output format is eventually required can be a thin formatting layer.
Out of scope, with boundaries
- Real money movement: hide behind a
PaymentGatewayinterface, not called by the state machine. - Concurrency: handler methods are single-threaded by default; if needed, serialize per payment ID or use versioned optimistic updates. Mention but do not build.
- Idempotency and retries: a repeated command on the same state is simply an invalid transition unless clarified, so retry safety would need an idempotency key, which is not in the command format.
Complexity
Parsing is O(L) in line length. Each command is O(1) with hash-map lookup and a table lookup.
Common mistakes
- Splitting on whitespace and losing empty placeholders.
- Mixing parsing, state checks and mutation in one method.
- Using floating-point for money.
- Hard-coding guessed rules (capture adds, cancel is bulk) and presenting them as part of the spec.
- Mutating the payment before all validations pass.
- Encoding transitions as nested if-statements, which makes missing rules hard to spot.
Summary
A strong answer delivers a position-preserving parser, a table-driven transition core, validate-then-apply handling, and explicit policy seams for every rule the specification leaves open, while asking the clarifying questions above.