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:
- decompose a workflow into focused functions;
- separate orchestration from calculation and validation;
- choose names that express domain meaning and units;
- identify and reduce hidden dependencies;
- distinguish pure calculations from side effects;
- design complete and consistent result contracts;
- apply guard clauses and invariants defensively;
- refactor repeated logic without changing behavior; and
- review a structured program for common failure modes.
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.
- Validation changes when accepted input rules change.
- Calculation changes when a formula changes.
- Policy selection changes when precedence or thresholds change.
- Formatting changes when output requirements change.
- Orchestration changes when workflow order changes.
Functions that change for one reason are easier to review and test.
3. A decomposition workflow
- State the overall outcome.
- List required inputs and outputs.
- Identify domain rules and invariants.
- Separate validation from trusted calculations.
- Extract repeated formulas or decisions.
- Name each responsibility in domain language.
- Define each function contract before implementation.
- Create one orchestration function that expresses the workflow.
- Test small functions first, then test their integration.
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.
- Include units when confusion is plausible: distance_km, timeout_seconds.
- Distinguish rates from amounts: tax_rate and tax_amount.
- Distinguish raw from validated values when both coexist.
- Use parallel names for parallel concepts.
- Avoid encoding temporary implementation details in public names.
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
- Capture current expected behavior with representative and boundary tests.
- Identify one responsibility to extract.
- Create a function with an explicit contract.
- Move the smallest coherent calculation or decision.
- Call the new function from the original workflow.
- Run the same tests and compare outputs.
- Remove the duplicated original logic only after equivalence is proven.
- Repeat one responsibility at a time.
Refactoring changes structure, not intended behavior. Small steps make regressions easier to locate.
17. Error-resistant review checklist
- Does every function have one clear responsibility?
- Do names reveal domain meaning and units?
- Are required dependencies explicit?
- Are defaults safe and documented?
- Are invalid inputs rejected before unsafe work?
- Does every reachable path return a predictable result?
- Are side effects isolated and named?
- Is mutable state minimal and local?
- Are related outputs returned together?
- Are thresholds, precedence, and pipeline order tested?
- Are invariants owned and verified?
- Can each function be tested without unrelated setup?
Common mistakes
- Creating a god function. Validation, policy, calculation, output, and host access become inseparable.
- Splitting mechanically. Tiny functions without meaningful contracts add indirection rather than clarity.
- Using vague names. Readers must inspect bodies to discover purpose.
- Omitting units. Compatible numbers with different meanings are accidentally combined.
- Reading mutable globals. Results depend on hidden state.
- Printing inside calculations. Reuse and testing become coupled to output.
- Returning partial results. Callers can construct internally inconsistent decisions.
- Ignoring null from a helper. A clear failure becomes a later secondary error.
- Duplicating policy logic. Copies drift when one is updated.
- Changing structure and behavior together. Regressions become hard to attribute.
- Extracting before understanding. The new function preserves accidental complexity rather than a domain concept.
Guided practice
- Split a function that validates, calculates, and prints into three responsibilities.
- Rename process(x, y) for a function that calculates tax from an amount and rate.
- Distinguish discount_rate, discount_amount, and discounted_total.
- Identify hidden dependencies in a function that reads three outer variables.
- Move printing out of a calculation without changing output.
- Design a complete map result for a priority decision.
- Add guard clauses to a division and percentage workflow.
- Write an invariant that links subtotal, discount, tax, and total.
- Plan a three-step refactoring that preserves existing test results.
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
- is_valid_impact(service_impact) — accepts values from 0 through 10.
- is_valid_user_count(affected_users) — rejects negative values.
- is_valid_tier(customer_tier) — accepts only approved labels.
- case_score(service_impact, affected_users, customer_tier, security_relevant) — calculates only the score.
- priority_for(score) — applies documented thresholds in descending order.
- response_minutes_for(priority) — maps each priority to one response target.
- build_decision(...) — orchestrates validation and helpers, then returns one map containing validity, score, priority, response minutes, and reason code.
- print_decision(decision) — performs the only user-facing output.
Design constraints
- Calculation functions must not print.
- Validation functions must return booleans.
- Thresholds and response targets must have named constants.
- Every invalid path must return one predictable invalid result.
- Priority and response minutes must always agree.
- The orchestration must check helper failures before continuing.
- No function may access files, HTTP, processes, secrets, or host-specific objects.
Required tests
- ordinary low, medium, high, and critical cases;
- exact score thresholds;
- invalid impact, affected-user count, and tier;
- security-relevant precedence;
- agreement between priority and response target;
- score consistency with its component rules;
- identical decisions before and after refactoring; and
- output formatting tested separately from calculation.
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
- What makes a function responsibility cohesive?
- Why should functions be split by reasons to change rather than line count?
- Which responsibilities commonly belong in separate functions?
- How should a boolean function be named?
- Why do units belong in some value names?
- What is a hidden dependency?
- Why are pure calculations easier to test?
- What belongs in an orchestration function?
- Why should related decision fields be returned together?
- Where should a function enforce the assumptions needed for its calculation?
- How should a caller handle a null helper result?
- Why should refactoring proceed in behavior-preserving steps?
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
- Each function has one domain-focused responsibility.
- Names reveal purpose, units, and result meaning.
- Dependencies are explicit and flow toward focused helpers.
- Calculations are separated from output and host concerns.
- Mutation is minimal and local.
- Failures propagate through one consistent convention.
- The returned result is complete and internally consistent.
- Refactoring tests prove that intended behavior was preserved.
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.