PeaBox Lab › PeaLang › Learn › Chapter 4 › Lesson 4

Part I — Foundations · Chapter 4 · Lesson 4 of 5 · 10 min read

Lesson 4: Decomposition, Naming, and Error-Resistant Design

Lesson level: Foundation

Purpose: Structure programs as small, intention-revealing functions whose contracts, dependencies, and failure behavior are easy to verify.

Learning objectives

By the end of this lesson, you should be able to:

1. Decomposition controls complexity

Decomposition divides one broad problem into functions with distinct responsibilities. A well-decomposed program lets a reader understand one decision or calculation at a time, test it independently, and change it without disturbing unrelated behavior.

A useful function usually does one of four things: validate an input, calculate a value, select a policy outcome, or coordinate smaller functions. Combining all four in one large body makes errors harder to isolate.

2. Start from responsibilities, not line counts

Do not split a function merely because it is long, and do not keep unrelated work together merely because it is short. Ask which parts change for different reasons.

Functions that change for one reason are easier to review and test.

3. A decomposition workflow

4. Worked refactoring: pricing workflow

A monolithic pricing function may validate inputs, calculate a subtotal, choose a discount, add tax, add delivery, and print a report. Split those responsibilities:

function is_valid_order(unit_price, quantity) { return unit_price >= 0 and quantity > 0 } function line_subtotal(unit_price, quantity) { return unit_price * quantity } function discount_rate_for(subtotal, customer_tier) { if customer_tier == "gold" and subtotal >= 500 { return 0.1 } if subtotal >= 1000 { return 0.05 } return 0 } function amount_after_discount(subtotal, discount_rate) { return subtotal - (subtotal * discount_rate) } function tax_amount(amount, tax_rate) { return amount * tax_rate }

Each function expresses one concept. The orchestration function can now read like the business process rather than a collection of formulas.

5. Name functions by the promise they make

A function name should communicate its result or observable action. Prefer names such as calculate_subtotal, is_valid_quantity, select_priority, and format_quote. Avoid vague verbs such as handle, process, manage, or do_work unless the domain supplies a precise meaning.

Boolean functions should read like questions: is_valid_order, has_discount, or requires_review. Functions with side effects should use action verbs such as print_summary.

6. Name values by meaning and units

Names should distinguish concepts that share the same underlying value category. response_minutes is safer than response; discount_rate is safer than discount when the value is a fraction rather than a monetary amount.

7. Keep contracts visible

For every reusable function, document or make evident its inputs, units, accepted ranges, result meaning, failure behavior, and side effects. A strong contract lets callers use the function without reading its implementation.

Example contract

# Inputs: subtotal_amount >= 0; customer_tier is an approved label # Returns: discount rate from 0 through 1, or null for invalid input # Side effects: none function discount_rate_for(subtotal_amount, customer_tier) { if subtotal_amount < 0 { return null } if customer_tier != "standard" and customer_tier != "gold" { return null } if customer_tier == "gold" and subtotal_amount >= 500 { return 0.1 } return 0 }

8. Avoid hidden dependencies

A hidden dependency is a value or capability a function uses without exposing that reliance through its contract. Reading an unrelated mutable global, printing unexpectedly, or depending on a caller's previous actions makes behavior harder to predict.

Prefer explicit parameters for values that vary between calls. Captured immutable configuration can be appropriate when a factory clearly documents it. Host access should remain behind narrow approved functions rather than appearing inside ordinary calculations.

9. Separate pure calculations from side effects

A pure calculation derives a result from its inputs without printing, changing outer state, or accessing external resources. The same inputs therefore produce the same result. Pure functions are easier to test, compose, and reuse.

Keep output near the program boundary:

function calculate_total(subtotal, discount_amount, tax_amount) { return subtotal - discount_amount + tax_amount } function print_total(total) { print "Final total: {total}" }

The calculation can be tested independently of text formatting. The printing function clearly advertises its effect.

10. Minimize mutation

Mutation is appropriate for counters, accumulators, and deliberate state transitions, but unnecessary reassignment makes functions harder to reason about. Prefer a sequence of named calculated values when each step has one meaning.

function quoted_total(subtotal, discount_rate, tax_rate) { let discount_amount = subtotal * discount_rate let discounted_amount = subtotal - discount_amount let tax_amount = discounted_amount * tax_rate return discounted_amount + tax_amount }

Each binding explains one stage. Reusing a single variable named value for every stage would hide the progression.

11. Orchestration should read like the workflow

An orchestration function coordinates smaller functions, checks intermediate failures, and returns one complete result.

function build_quote(unit_price, quantity, customer_tier, tax_rate) { if not is_valid_order(unit_price, quantity) { return null } let subtotal = line_subtotal(unit_price, quantity) let discount_rate = discount_rate_for(subtotal, customer_tier) if discount_rate == null { return null } let discounted = amount_after_discount(subtotal, discount_rate) let tax = tax_amount(discounted, tax_rate) return {"subtotal": subtotal, "discount_rate": discount_rate, "tax": tax, "total": discounted + tax} }

The orchestration expresses sequence and failure propagation. The smaller functions retain focused responsibilities.

12. Return complete results

When several values form one decision, return them together so callers cannot accidentally combine fields from different evaluations. A pricing result might contain subtotal, discount rate, tax, total, validity, and reason code in one string-keyed map.

Define required keys and their meanings. A map is flexible, but missing or inconsistently named fields still create fragile contracts.

13. Guard clauses protect assumptions

Validate conditions required for safe execution before the main work. Early returns keep invalid paths short and prevent calculations from using untrusted assumptions.

function ratio(numerator, denominator) { if denominator == 0 { return null } return numerator / denominator }

Do not scatter the same guard across several callers. Place an invariant close to the calculation that depends on it, while retaining broader external validation at the host boundary.

14. Preserve invariants across functions

An invariant is a relationship that must remain true throughout a workflow. Examples include a total never becoming negative, a priority matching its response target, or component amounts summing to the reported total.

Assign ownership for each invariant. A small function protects its local postconditions; the orchestration function verifies relationships that span multiple components.

15. Propagate failures deliberately

If a lower-level function returns null for invalid input, its caller must check that result before continuing. Ignoring failure converts a clear boundary error into a later, less useful calculation failure.

let subtotal = line_subtotal(unit_price, quantity) if subtotal == null { return null }

Use one consistent failure convention within a layer. Later chapters introduce exceptions and Result types for richer error information.

16. Refactor with behavior-preserving steps

Refactoring changes structure, not intended behavior. Small steps make regressions easier to locate.

17. Error-resistant review checklist

Common mistakes

Guided practice

Design exercise: Function responsibility map

For a selected workflow, draw a responsibility map with four columns: function name, inputs, returned result, and failure behavior. Add a fifth column only for observable side effects. If a row contains several unrelated effects or more than one primary result, reconsider the boundary.

Then draw arrows showing calls. The resulting dependency direction should flow from orchestration toward focused helpers, not from calculations toward printing, global state, or host infrastructure.

Hands-on lab: Refactor a support-priority service

Scenario. Refactor a single large support-case function into a structured program that validates inputs, scores a case, selects a priority, creates a result, and prints a report.

Required functions

Design constraints

Required tests

Deliverable. Submit the original and refactored designs, responsibility map, function contracts, dependency diagram, source, behavior-equivalence test table, invariant checks, and a short explanation of each boundary.

Review questions

Applied challenge: Modular eligibility engine

Take an eligibility workflow from your domain and design it as a structured program. Separate input validation, named conditions, scoring or policy selection, result construction, and presentation. Define every contract and return one complete portable result.

Create a baseline implementation and tests, then refactor one responsibility at a time. Demonstrate behavior equivalence after every extraction. Add invalid, boundary, overlap, and invariant tests, and document any side effect or captured configuration.

Success criteria

Lesson summary

Structured programs manage complexity through cohesive functions, explicit contracts, intention-revealing names, and clear dependency direction. Reliable decomposition separates validation, calculation, policy, orchestration, and presentation. Error-resistant design minimizes mutation and hidden state, isolates side effects, checks guard conditions early, returns complete results, preserves invariants, and refactors in small behavior-preserving steps.

Next: Chapter 4 Checkpoint — Modular Pricing Rules Library

Lesson status: Approved.

← Previous Next →