Part I — Foundations · Chapter 4 · Lesson 5 of 5 · 7 min read
Chapter 4 Checkpoint: Modular Pricing Rules Library
Checkpoint level: Foundation
Purpose: Integrate function declarations, parameters, defaults, returns, scope, closures, higher-order behavior, decomposition, naming, and defensive contracts in one reusable pricing library.
Checkpoint outcomes
By completing this checkpoint, you will demonstrate that you can:
- decompose a pricing workflow into cohesive functions;
- define required and defaulted parameters;
- return complete portable results;
- use closures for validated pricing configuration;
- pass pricing behaviors into higher-order orchestration;
- isolate output from calculations;
- propagate invalid results consistently;
- preserve pricing invariants; and
- test functions independently and as an integrated library.
Project scenario
A commerce application needs a pricing library that calculates line subtotals, tier discounts, promotional adjustments, tax, delivery, and a final quote. The library must keep policy logic reusable and free of external capabilities. A host application may later supply validated values, but this checkpoint uses source-defined scenarios.
4C.1 Pricing policy
- Unit price must be zero or greater.
- Quantity must be greater than zero.
- Approved customer tiers are standard, silver, and gold.
- Standard customers receive no tier discount.
- Silver customers receive 5 percent when subtotal is at least 500.
- Gold customers receive 10 percent when subtotal is at least 500.
- A promotional rate may add a further discount from 0 through 5 percent.
- The combined discount rate must never exceed 15 percent.
- Tax defaults to 18 percent and may be overridden with a rate from 0 through 1.
- Standard delivery costs 40; expedited delivery costs 90.
- Delivery is free when the discounted amount is at least 1500.
- Tax is calculated after discount and before delivery is added.
4C.2 Required quote inputs
- unit_price — required monetary amount;
- quantity — required positive count;
- customer_tier — required approved string;
- promotion_rate — optional, default 0;
- tax_rate — optional, default 0.18; and
- expedited — optional, default false.
4C.3 Required result
A valid quote must return a string-keyed map containing:
- valid;
- subtotal_amount;
- tier_discount_rate;
- promotion_rate;
- combined_discount_rate;
- discount_amount;
- discounted_amount;
- tax_rate;
- tax_amount;
- delivery_amount;
- final_total; and
- reason_code.
An invalid quote must return a predictable invalid result with valid = false and a stable reason code. Do not calculate downstream monetary fields after validation fails.
4C.4 Required functions
- is_valid_unit_price(unit_price) — returns a boolean.
- is_valid_quantity(quantity) — returns a boolean.
- is_valid_customer_tier(customer_tier) — returns a boolean.
- is_valid_rate(rate) — accepts values from 0 through 1.
- line_subtotal(unit_price, quantity) — returns null when inputs violate its contract.
- tier_discount_rate(subtotal_amount, customer_tier) — applies tier thresholds.
- combined_discount_rate(tier_rate, promotion_rate = 0) — rejects invalid rates and caps the combination at 0.15.
- discount_amount(subtotal_amount, combined_rate) — returns a monetary amount.
- tax_amount(discounted_amount, tax_rate = 0.18) — validates its rate and amount.
- delivery_amount(discounted_amount, expedited = false) — applies free-delivery and service policies.
- make_promotion(promotion_rate) — validates the configuration and returns a closure that applies the promotion to an amount.
- apply_adjustment(amount, adjustment) — accepts a compatible function value and invokes it.
- build_quote(...) — orchestrates all calculations and returns one complete map.
- print_quote(quote) — performs the only user-facing output.
4C.5 Contract requirements
For every function, document purpose, parameter meanings, defaults, units, accepted ranges, returned value, failure result, and side effects. For higher-order functions, also document the required callable arity and result meaning. For closures, document captured values and whether captured state can change.
4C.6 Dependency direction
The intended direction is:
- validation helpers;
- focused calculations and policy functions;
- closure factories and higher-order helpers;
- quote orchestration; and
- presentation.
Validation and calculation functions must not call presentation functions. Presentation must not recalculate policy. No layer may depend on files, HTTP, processes, secrets, or host-specific objects.
4C.7 Core invariants
- All monetary components are nonnegative.
- subtotal_amount = unit_price × quantity.
- combined_discount_rate is between 0 and 0.15.
- discount_amount = subtotal_amount × combined_discount_rate.
- discounted_amount = subtotal_amount − discount_amount.
- tax_amount = discounted_amount × tax_rate.
- final_total = discounted_amount + tax_amount + delivery_amount.
- Free delivery produces a delivery amount of zero.
- An invalid result never presents itself as a valid quote.
4C.8 Reference structure
Attempt the project independently before using this outline. It demonstrates responsibility boundaries rather than every line of the final submission.
function is_valid_rate(rate) { return rate >= 0 and rate <= 1 } function line_subtotal(unit_price, quantity) { if unit_price < 0 or quantity <= 0 { return null } return unit_price * quantity } function tier_discount_rate(subtotal_amount, customer_tier) { if subtotal_amount < 0 { return null } if customer_tier == "gold" and subtotal_amount >= 500 { return 0.1 } if customer_tier == "silver" and subtotal_amount >= 500 { return 0.05 } if customer_tier == "standard" or customer_tier == "silver" or customer_tier == "gold" { return 0 } return null } function make_promotion(promotion_rate) { if promotion_rate < 0 or promotion_rate > 0.05 { return null } function apply(amount) { if amount < 0 { return null } return amount - (amount * promotion_rate) } return apply } function apply_adjustment(amount, adjustment) { return adjustment(amount) }
The final build_quote function should validate required inputs, compute each named stage, check every nullable helper result, verify invariants, and return a complete map. It should not print.
4C.9 Failure codes
Use stable reason codes such as:
- INVALID_UNIT_PRICE;
- INVALID_QUANTITY;
- INVALID_CUSTOMER_TIER;
- INVALID_PROMOTION_RATE;
- INVALID_TAX_RATE;
- CALCULATION_FAILED; and
- QUOTE_OK.
Return the most specific applicable validation failure before attempting later stages.
4C.10 Required scenario matrix
- standard tier below the discount threshold;
- silver tier exactly at 500;
- gold tier exactly at 500;
- gold tier above the free-delivery threshold;
- valid maximum promotion rate;
- combined discount that reaches the 15 percent cap;
- tax override of zero;
- ordinary and expedited delivery;
- negative unit price;
- zero quantity;
- unknown tier;
- promotion below zero and above 5 percent;
- tax below zero and above 1; and
- all defaults omitted versus all defaults supplied explicitly.
4C.11 Closure and higher-order tests
- Create promotions at 0, 0.02, and 0.05.
- Prove that each closure preserves its own captured rate.
- Apply each closure to the same subtotal and compare results.
- Confirm that an invalid factory configuration returns null.
- Pass a named adjustment function and a closure through apply_adjustment.
- Demonstrate the difference between passing a function and invoking it before the call.
- Verify that pricing closures are stateless across repeated calls.
4C.12 Function-level tests
Test each helper independently before integration. Cover ordinary inputs, exact boundaries, invalid inputs, and every documented default. For pure calculations, call the function twice with identical inputs and confirm identical results.
4C.13 Integration and invariant tests
For every valid quote, recompute each invariant from returned fields and compare it with the stored value. Verify that priority rules—tier discount, promotion cap, free delivery, and order of tax calculation—produce the documented outcome.
For every invalid quote, confirm that no downstream success fields are trusted and that the correct specific reason code is returned.
4C.14 Refactoring requirement
Begin with a baseline implementation or reference result table. Extract responsibilities one at a time. After each extraction, rerun the same scenario matrix and record whether behavior remained equivalent.
Introduce one temporary regression, such as calculating tax before discount or using a strict greater-than comparison at the 500 threshold. Show which test detects it, restore the approved rule, and rerun the full matrix.
4C.15 Command-line validation workflow
- Run pea fmt pricing_rules.pea.
- Run pea fmt --check pricing_rules.pea.
- Run pea check pricing_rules.pea.
- Run the scenario driver with pea run pricing_rules.pea.
- Compare actual and expected fields for every scenario.
- Record invariant and closure-test results.
- Confirm that process execution was not enabled.
4C.16 Submission package
- pricing_rules.pea in canonical formatting;
- a responsibility map and dependency diagram;
- a contract sheet for every function;
- the complete scenario matrix with predictions and results;
- function-level, closure, integration, and invariant evidence;
- a behavior-equivalence refactoring record;
- a note describing the temporary regression and correction;
- captured format, check, and run results; and
- a security statement confirming that no external capability was required.
4C.17 Assessment rubric
- Correctness: formulas, thresholds, defaults, and order of operations are accurate.
- Contracts: every function has explicit inputs, results, failures, units, and effects.
- Decomposition: validation, calculation, policy, orchestration, and presentation are separated coherently.
- Naming: function and value names reveal domain meaning and units.
- Closures: captured configuration is validated, independent, and traceable.
- Higher-order design: callable expectations are documented and tested.
- Defensive design: invalid inputs stop unsafe downstream calculation.
- Invariants: returned components form a complete, internally consistent quote.
- Testing: boundaries, defaults, invalid cases, integration, and regressions are covered.
- Security: no unnecessary capability, secret, host object, or process permission is used.
Completion standard: Every required scenario passes, every invariant holds, closure instances remain independent, and the learner can explain the dependency direction and failure behavior without inspecting trial output.
4C.18 Reflection questions
- Which responsibility was hardest to isolate?
- Which name most improved understanding of the pricing flow?
- Which default required the most careful justification?
- How did the closure simplify repeated promotion calls?
- Which invariant detected the most subtle defect?
- Which behavior-equivalence test gave the strongest refactoring confidence?
- Where would typed contracts improve this design later?
- What validation would remain in a host application?
4C.19 Optional extensions
- Add a configurable delivery strategy as a closure.
- Add a higher-order pipeline that receives discount, tax, and delivery behaviors explicitly.
- Add a maximum absolute discount while preserving the rate cap.
- Add a reason-code trail showing which pricing rules applied.
- Add a second currency scenario while making units explicit and avoiding conversion assumptions.
- Return a list of validation errors only after later error-handling lessons introduce a suitable contract.
Chapter 4 summary
You can now declare and call functions, design parameters and defaults, return predictable results, reason about local scope, create closures, pass functions as values, decompose workflows, name domain concepts, isolate effects, propagate failures, and preserve invariants. The modular pricing-rules checkpoint integrates those skills into a reusable library.
Transition to Chapter 5
Chapter 5 examines core data and collections in depth. The next lesson covers null, booleans, numbers, strings, lists, and string-keyed maps, including their operations, behavior, and role at portable boundaries.
Checkpoint status: Approved.