Sub topic 11
Mistake-proofing in software: types, states, and confirmations
This chapter assumes you know the earlier ideas in this tutorial: prevention versus detection, control versus warning devices, and Shingo's contact, fixed-value, and motion-step methods. You should also be able to read short Python snippets. The aim is to apply those ideas to code, so that a developer or operator cannot make a given error, or finds out about it at once.
Why software needs poka-yoke
Software teams often respond to errors with documentation, code review, and "be careful" reminders. In the effectiveness ranking from earlier chapters, these sit near the bottom: they detect or mitigate, and they rely on a person remembering to act. Software has an advantage physical workplaces lack. The same medium that holds the process also holds the device, so you can often remove the error entirely at little cost.
The mapping from physical poka-yoke is direct:
| Physical idea | Software equivalent | Shingo method |
|---|---|---|
| A part that only fits one way | A type or enum that only admits valid values | Fixed-value / contact |
| A fixture that blocks the wrong sequence | A state machine that rejects illegal transitions | Motion-step |
| A guard that makes the operator pause | A confirmation that requires deliberate input | Motion-step |
| A sensor that checks conditions before a cycle starts | Validation at the boundary, before work begins | Source inspection |
Restrict the values: types and enums
Most data errors are slips: a typo in a status string, a negative quantity, an account ID passed where an order ID was expected. A free-form string accepts all of these. A restricted type does not.
An enum limits a field to a fixed set of values. A misspelled "shiped" cannot exist, because no such member exists. This is the fixed-value method applied to data.
Some values are not a short list but still have a valid range. Wrap them in a type that refuses to be constructed with a bad value:
from dataclasses import dataclass
@dataclass(frozen=True)
class Percent:
value: int
def __post_init__(self) -> None:
if not 0 <= self.value <= 100:
raise ValueError(f"Percent must be 0-100, got {self.value}")
discount = Percent(15) # fine
# Percent(150) raises ValueError at the moment of creationThe error is stopped where it is made. Every function that accepts a Percent can trust the value without re-checking it. This is source inspection: the check happens once, at the source, and nothing downstream needs to inspect.
Distinct types also help with swapped arguments of the same underlying type:
from typing import NewType
AccountId = NewType("AccountId", str)
OrderId = NewType("OrderId", str)
def refund(account: AccountId, order: OrderId) -> str:
return f"Refunding order {order} to account {account}"
refund(AccountId("A-100"), OrderId("O-7"))
# refund(OrderId("O-7"), AccountId("A-100")) is rejected by a type checker such as mypyNewType has no effect at runtime in Python. The protection comes from running a type checker in your build.
Restrict the sequence: state transitions
Some errors are not about a single value but about order. An order must be paid before it ships. If any code can set the status to any value, a bug or a hurried manual fix can ship an unpaid order.
Replace "set the status" with "request a transition" and keep a table of legal moves:
from enum import Enum
class OrderStatus(Enum):
DRAFT = "draft"
PAID = "paid"
SHIPPED = "shipped"
ALLOWED_TRANSITIONS = {
OrderStatus.DRAFT: {OrderStatus.PAID},
OrderStatus.PAID: {OrderStatus.SHIPPED},
OrderStatus.SHIPPED: set(),
}
def change_status(current: OrderStatus, new: OrderStatus) -> OrderStatus:
if new not in ALLOWED_TRANSITIONS[current]:
raise ValueError(f"Cannot move from {current.value} to {new.value}")
return new
status = OrderStatus.DRAFT
status = change_status(status, OrderStatus.PAID) # allowed
# change_status(status, OrderStatus.DRAFT) would raise ValueErrorThis is a control device in the sense used earlier: the process stops at the illegal step instead of recording it. It is also a motion-step method, because it enforces that step B follows step A.
The diagram and the table say the same thing. Keeping the table as data, not as scattered if statements, matters for two reasons. You can read the whole rule set in one place, and you can test it exhaustively (see below).
The single-entry-point rule
A transition table is only a poka-yoke if code cannot go around it. If other modules can still write order.status = OrderStatus.SHIPPED, the table is a warning label. Make the field private to the module, or expose only change_status, so the guarded path is the only path. In a database, add a constraint or trigger so direct SQL updates face the same rule.
Restrict the call: keyword-only arguments and sanity checks
Swapped arguments are a classic slip when two parameters share a type. Positional order is invisible at the call site: transfer("A-100", "B-200", 2500) looks identical whichever way you meant it.
def transfer(*, source_account: str, destination_account: str, amount_cents: int) -> str:
if source_account == destination_account:
raise ValueError("Source and destination must differ")
if amount_cents <= 0:
raise ValueError("Amount must be positive")
return f"Moved {amount_cents} cents from {source_account} to {destination_account}"
# Keyword-only arguments make a swapped-argument slip visible at the call site.
transfer(source_account="A-100", destination_account="B-200", amount_cents=2500)
# transfer("A-100", "B-200", 2500) raises TypeErrorThe bare * forces every argument to be named, so the reader and the writer both see which account is which. The two checks reject inputs that cannot be valid. Amounts in integer cents, not floats, remove a whole class of rounding errors, which is the "eliminate" rung of the effectiveness ladder.
Slow the dangerous action: confirmation by typing
Many tools ask "Are you sure? (y/n)". Operators learn to press y without reading, so this is a weak warning device. A stronger design makes confirming require the information that distinguishes the right target from the wrong one:
def delete_environment(name: str, confirm_name: str) -> str:
if confirm_name != name:
raise ValueError("Confirmation does not match the environment name; nothing was deleted")
return f"Deleted {name}"
delete_environment("staging", "staging") # proceeds
# delete_environment("production", "staging") raises ValueErrorRetyping the name forces the operator to look at the name. This is a motion-step style check: it breaks the habit of confirming automatically. It does not remove the error, since a person can still type the wrong name twice, but it catches the common case where the target in mind and the target on the screen differ.
Choosing among these devices
Use the error type to pick the tool:
- Slips with bad values (typos, out-of-range numbers): enums and validating types.
- Slips with swapped inputs: keyword-only arguments or distinct types.
- Lapses where a step is skipped: state transitions that refuse to proceed without the earlier step.
- Mistakes caused by acting on the wrong target: typed confirmation, and showing the target's identity (environment, account, region) prominently.
Check where the device sits on the effectiveness ladder. Can you eliminate the error by removing the choice, for example by deriving a value instead of asking for it? Prefer that to a validation that rejects it. Prefer rejection to a warning. Prefer a warning to a note in a runbook.
Verifying software devices
A device you have not tried to defeat is an assumption. Software gives you cheap ways to verify, and the transition table is a good example, because you can check every pair:
from enum import Enum
from itertools import product
class Step(Enum):
DRAFT = 1
PAID = 2
SHIPPED = 3
ALLOWED = {(Step.DRAFT, Step.PAID), (Step.PAID, Step.SHIPPED)}
def try_move(current: Step, new: Step) -> bool:
return (current, new) in ALLOWED
for current, new in product(Step, repeat=2):
expected = (current, new) in ALLOWED
assert try_move(current, new) == expected, (current, new)
print("All", len(Step) ** 2, "transitions behave as specified")In a real project the expected set should come from a source independent of the code under test, such as the written process, so the test does not simply repeat the implementation's own mistake. Also test the bypass: search the code base for direct assignments to the guarded field, and add a test or lint rule that fails if one appears.
Common failures in software
- Bypass flags. A
force=Trueparameter added "for emergencies" tends to become the normal path. If you need an override, require a reason, log it, and review its use. - Validation in the wrong place. Checking only in the user interface leaves the API and batch jobs unprotected. Validate at the lowest layer that every path goes through.
- Catching and ignoring. Wrapping a guarded call in a broad
exceptthat logs and continues turns a control device into a warning device nobody reads. - Over-reliance. A
Percenttype guarantees range, not correctness. A discount of 100 percent is valid and may still be wrong, so keep the other safeguards your risk analysis calls for.
Exercise
A support tool lets agents change a ticket's status by choosing any value from a free-text field. Agents sometimes close tickets that were never assigned. Name two poka-yoke devices from this chapter that would address this, say which error type each targets, and name one way a developer could accidentally defeat them.
Show answer
First, replace the free-text field with an enum, which stops typos and invented values (a slip). Second, add a transition table so that "closed" is reachable only from "assigned" or "in progress", which stops the skipped step (a lapse). Both can be defeated if other code, such as a script or direct database update, can still write the status field without going through the transition function. The fix is to make the guarded function the only write path and, where possible, to enforce the rule in the database too.