Fail Fast, Fail Early
Early Failure and Partial Updates
BOTIE
Python gives us explicit exceptions for that decision. A function can reject an unsuitable value before using it, while a caller can handle the failures it expects. Our batch example adds another requirement: validate every incoming measurement before changing the saved list. An early error message alone would not repair a partial write.
Why Did Half of the Batch Get Saved?
A program receives a batch of positive measurements and adds them to a saved list. It writes the first measurement, writes the next, then discovers that a later value is text. The request fails, but the saved list has already changed.
We can stop that partial update before it happens. First establish which inputs the operation accepts. Check the entire batch against those requirements. Only then perform the write. Failing early means placing that decision before the work that relies on it.
This shows the resulting list without changing the source. It does not save a file or provide a database transaction.
Step 1 of 1
Put Validation Before the First Write
The same batch is examined in two orders. The saved list begins empty.
| Order | What happens | Saved state after failure |
|---|---|---|
| Write while checking | Save 5, then discover that the next value is invalid | [5] |
| Check the complete batch first | Find the invalid value before starting any write | [] |
Write while checking
- What happens
- Save 5, then discover that the next value is invalid
- Saved state after failure
- [5]
Check the complete batch first
- What happens
- Find the invalid value before starting any write
- Saved state after failure
- []
State What the Operation Accepts
The whole incoming batch is checked before anything is appended. When its last value fails, the earlier valid values stay out too.
Save a Batch without Leaving Half an Update
The saved readings are [2]. Adding [4, 8] should produce [2, 4, 8]. A request containing zero, a negative number or text must leave the saved readings unchanged.
BOTIE
The saved readings after the request
- 02
- 14
- 28
Follow the operations
1. Saved readings
- 02
2. Incoming batch
- 04
- 18
3. Check each reading
- 0ready
- 1ready
4. Append a complete batch
- 02
- 14
- 28
5. Result
- 02
- 14
- 28
This shows the resulting list without changing the source. It does not save a file or provide a database transaction.
1. State What the Operation Accepts
An error check needs a rule to check against. Here a valid batch is a list of finite, positive numbers. Zero is outside this example’s contract, even though another application might allow it. Text that looks numerical is also outside the contract; conversion, if wanted, belongs in a separate step.
A contract describes the inputs an operation accepts and the result or failure it promises. It also needs to say which effects are allowed. Our batch operation promises that a rejected batch leaves the saved list unchanged. That statement is more useful than saying the function is robust.
Accepted: [5, 8, 2]
Rejected: [5, "eight", 2]
Rejected: [5, 0, 2]
On rejection: do not add any item to the saved list.Choose requirements that fit the actual problem. Failing early is only useful when the condition being enforced is correct.
2. Validate Before Changing State
A side effect is an observable change outside the result a function returns. Appending to a caller’s list is a side effect. Writing a file or updating a database is another. If a later check fails, an earlier effect does not automatically undo itself.
Separate the validation loop from the write. The first loop inspects every item without changing the destination. If it raises an exception, the function exits before reaching the write. If every item passes, the function can apply the batch.
This structure also makes the policy visible to someone reading the code. They can locate the point where the program moves from checking a request to changing state.
For this local list, checking first prevents the declared partial-write problem. Concurrent database changes still need a transaction and appropriate constraints.
Check yourself
Questions on Parts 1 and 2
Question 1 of 2
Which action matches the contract?
Question data
A batch contract accepts positive numbers only. The incoming batch is [5, "six", 2]. No conversion step is part of the contract.3. Distinguish Representation from Allowed Values
The text "4" and the number 4 are different Python objects. A type hint can describe which one a function expects, but Python does not enforce that annotation by itself. An explicit runtime check can reject the wrong representation.
After establishing that a value is numeric, we still need to ask whether its value is acceptable. A negative number has the right general representation and fails the positive-value rule. A nonfinite floating-point value also needs an explicit decision.
Python’s bool is a subclass of int. An isinstance(value, int) check therefore accepts True. If a measurement contract excludes booleans, make that choice explicit. The small check below deliberately accepts only the built-in int and float types; it is not a general rule for NumPy scalars or every numerical class.
Representation checks and domain checks answer different questions. A number can be well typed and still be unusable.
Reject the Value Where It Enters
Run the same validator on a measurement, a negative value, and a boolean.
import math
def require_positive(value):
if type(value) not in (int, float):
raise TypeError('A reading must be a number')
if (type(value) is float and not math.isfinite(value)) or value <= 0:
raise ValueError('A reading must be finite and positive')
return value
for reading in [4, -2, True]:
try:
print(require_positive(reading))
except (TypeError, ValueError) as error:
print(type(error).__name__, str(error))4
ValueError A reading must be finite and positive
TypeError A reading must be a numberNo fallback value is invented. The caller sees which declared condition failed.
4. Use Exceptions That Explain the Failure
TypeError is appropriate when an argument has an unsuitable type. ValueError describes an argument of an appropriate type whose value violates the operation’s requirements. Those categories let a caller distinguish a representation problem from a value problem.
An error message should identify the failed requirement. “Bad input” gives little help. “Every incoming value must be finite and positive” tells us which condition to inspect. A batch validator can also include a row number or field name, provided it avoids disclosing private input in logs or public responses.
Do not catch an exception merely to return a plausible-looking zero. A zero can be a real result. Silently substituting it hides the failure from later code.
The calling layer decides whether to ask for corrected input, reject a request, or stop a task. The validation function should preserve that choice.
5. Keep Required Checks out of Assertions
An assertion documents an internal condition the programmer expects to hold. Python can omit assert statements when code is compiled with optimization. That makes assert unsuitable for a required check on a file, an API request, or another caller’s data.
Use an ordinary conditional followed by raise for a validation rule that must run. Assertions can still be useful in tests and for internal debugging assumptions. The distinction concerns whether the program depends on the check always being present.
A required boundary check must not disappear because the interpreter was started differently.
6. Decide What Can Recover
Failing early does not require shutting down an entire application whenever one request is invalid. A web handler might reject that request while continuing to serve other people. A data-import tool might collect invalid rows for correction, if partial acceptance is an explicit part of its contract.
Our first batch policy is all-or-nothing: any invalid item prevents the whole write. Another policy could accept valid records and return errors for the rest. Those are different operations and need different tests. Do not drift from one to the other by putting a broad exception handler around a loop.
Input validation also has limits. It cannot prove that a measurement was taken correctly, that a user is authorized, or that a resource will remain available. Keep those responsibilities visible rather than calling a validated request safe in every sense.
A reliable failure policy says what stops, what remains unchanged, and what information reaches the caller.
7. Test the Failure Before the Effect
A test that only checks whether an exception was raised can miss a partial update. Keep a copy of the destination, send a batch whose final item is invalid, and compare the destination after failure. The last item matters because it lets earlier valid values tempt a write-while-checking implementation.
Also test an empty batch, changed batch lengths, a boolean, and a nonfinite number. Decide the empty-batch rule in the contract: the total function below requires at least one reading, while the append function permits an empty incoming list as a no-op. Neither rule should be inferred from a convenient implementation.
The test needs to observe the state that could have been damaged, as well as the error.
Check yourself
Questions on Parts 1 to 7
Question 1 of 5
Why does isinstance(value, int) need care here?
Question data
The contract accepts only built-in int and float measurements, excluding booleans. The input is True.Try it with Botie
Build with Botie
Write and run Python