Data Validation Patterns
Error Collection
Collecting all validation errors lets a caller see every problem in one pass.
error collection
Instead of stopping at the first invalid field, collect each error message into a list.
Error Collection
errors.py
Replay: real traced execution (multi-file project)
def validate_order(quantity, price):
errors = []
if quantity <= 0:
errors.append("quantity")
if price <= 0:
errors.append("price")
return errors
price = 10
errors = validate_order(2, price)
print("errors=" + ",".join(errors) if errors else "errors=none")
def validate_order(quantity, price):
errors = []
if quantity <= 0:
errors.append("quantity")
if price <= 0:
errors.append("price")
return errors
price = 0
errors = validate_order(2, price)
print("errors=" + ",".join(errors) if errors else "errors=none")
price ← 10
12price→ 10 = 10 #@price=013errors = validate_order(2, price10)errors ← []
1def validate_order(quantity2, price10):2 errors→ [] = []34 if quantity <= 0:5 errors.append("quantity")6 if price <= 0:7 errors.append("price")89 return errors[]errors ← []
12price = 10 #@price=013errors→ [] = validate_order(2, price10)1415print("errors=" + ",".join(errors[]) if errors else "errors=none")outputerrors=none
price ← 0
12price→ 0 = 013errors = validate_order(2, price0)errors ← []
1def validate_order(quantity2, price0):2 errors→ [] = []errors ← ['price']
5 errors.append("quantity")6if price0 <= 0:7 errors→ ['price'].append("price")return errors
9return errors['price']errors ← ['price']
12price = 013errors→ ['price'] = validate_order(2, price0)1415print("errors=" + ",".join(errors['price']) if errors else "errors=none")outputerrors=price