Part I — Foundations · Chapter 4 · Lesson 2 of 5 · 9 min read
Lesson 2: Parameters, Return Values, Defaults, and Reusable Contracts
Lesson level: Foundation
Purpose: Design function interfaces that accept clear inputs, return predictable results, support justified defaults, and remain safe to reuse.
Learning objectives
By the end of this lesson, you should be able to:
- distinguish required parameters from parameters with defaults;
- match positional arguments to parameters accurately;
- explain when a default value is evaluated and used;
- design consistent return paths;
- use null deliberately to represent an invalid or absent result;
- write preconditions, postconditions, and invariants for a function;
- preserve compatibility when evolving a function interface; and
- test a reusable contract at normal, boundary, omitted, and invalid inputs.
1. Parameters define the input interface
A parameter names one input expected by a function. Its position, meaning, accepted values, and default behavior are part of the function's public contract. A caller should not need to inspect the body to understand how to use the function correctly.
Example 1 — Required parameters
function calculate_fee(amount, rate) { return amount * rate } let fee = calculate_fee(500, 0.02)
The first argument binds to amount, and the second binds to rate. Reversing them changes the result, so parameter order should follow a natural reading and remain stable after callers begin depending on it.
2. Required parameters and arity
A function's arity is the number of arguments its interface requires for a call. If a declaration contains two required parameters, the caller must provide both. Too few arguments leave a required input unavailable; too many arguments have no declared destination.
Keep required parameter lists focused. If a function needs many unrelated inputs, that often indicates that the responsibility is too broad or that related values should be organized behind a clearer boundary.
3. Parameters with default values
A default value lets a caller omit an optional argument while preserving predictable behavior. Place required parameters before defaulted parameters so calls remain unambiguous.
Example 2 — A justified default
function shipping_cost(weight, rate = 2.5) { if weight < 0 { return null } return weight * rate } print(shipping_cost(4)) print(shipping_cost(4, 3))
The first call omits rate, so the default 2.5 is used. The second supplies 3, which overrides the default for that call. A default should represent an approved, unsurprising policy—not a convenient guess that hides missing data.
4. Choosing safe defaults
- Use a default only when omission has one clear meaning.
- Prefer explicit arguments for security, permissions, money, destructive actions, and compliance-sensitive policy.
- Document the default in the contract.
- Do not use a default to conceal invalid or unavailable required data.
- Test both omitted and explicitly supplied cases.
- Change an established default only as a deliberate compatibility decision.
5. Return values define the output interface
A reusable function returns a result whose meaning is stable across calls. The contract should state the result category, units, valid range, and failure representation. Callers can then use the value without depending on internal implementation details.
Example 3 — Consistent value-producing paths
function percentage(part, whole) { if whole == 0 { return null } return part * 100 / whole } let completion = percentage(18, 24)
Every reachable path returns either a percentage or null. The caller can check the result before using it. This is clearer than allowing an invalid division or returning an unrelated sentinel such as -1.
6. Early returns and guard clauses
A guard clause checks an invalid or exceptional case near the beginning of a function and returns immediately. This keeps the main calculation at a shallow nesting level.
Example 4 — Validate before calculation
function unit_price(total, quantity) { if total < 0 { return null } if quantity <= 0 { return null } return total / quantity }
Each guard rejects one broken precondition. Once execution reaches the final line, the calculation can rely on a nonnegative total and a positive quantity.
7. Avoid mixed return meanings
Do not return a number on one successful path, a descriptive string on another, and a boolean on a third unless that variation is an intentional documented interface. Mixed meanings force every caller to rediscover the function's internal branches.
Within foundational code, use one predictable success shape and one explicit failure convention. Later chapters introduce Option and Result types for stronger typed contracts.
8. Preconditions, postconditions, and invariants
A reusable contract can be described with three kinds of statement:
- Preconditions specify what must be true of inputs, such as quantity being positive.
- Postconditions specify what the function guarantees on return, such as a total never being negative.
- Invariants specify relationships preserved throughout the operation, such as subtotal equaling unit price multiplied by quantity.
Example contract
# Preconditions: amount >= 0; rate is between 0 and 1 # Postcondition: returns amount after discount, or null for invalid input # Invariant: returned value is never greater than amount function discounted_total(amount, rate = 0) { if amount < 0 { return null } if rate < 0 or rate > 1 { return null } return amount - (amount * rate) }
9. Validation ownership
The caller and callee have complementary responsibilities. A host or outer layer validates external shape, authorization, and broad domain constraints. A reusable function still protects assumptions necessary for its own safe calculation.
Do not duplicate every validation mechanically. Validate at the boundary where the rule is best understood, and keep function-local guards for conditions without which the function cannot produce a trustworthy result.
10. Evolving a function without surprising callers
A published function interface creates dependencies. Changing parameter order, removing a parameter, changing a default, or altering the meaning of a returned value can break correct callers even when the new body works internally.
A safer additive change often appends a new defaulted parameter:
function final_price(amount, discount_rate = 0, tax_rate = 0) { if amount < 0 { return null } if discount_rate < 0 or discount_rate > 1 { return null } if tax_rate < 0 or tax_rate > 1 { return null } let discounted = amount - (amount * discount_rate) return discounted + (discounted * tax_rate) }
Existing calls that pass only an amount still behave predictably. New callers may supply discount and tax rates. Compatibility still requires tests because even an additive parameter can change semantics if its default is inappropriate.
11. Contract-focused test matrix
Test the interface, not just the formula. For each reusable function, include:
- an ordinary valid call;
- the lowest and highest accepted boundary values;
- a call omitting each defaulted argument;
- a call explicitly supplying the default value;
- an override of each default;
- too few or too many arguments where diagnostics are relevant;
- invalid values for every precondition; and
- checks for every promised postcondition and invariant.
12. Trace argument binding and return flow
For each call, record the evaluated argument values, parameter bindings, defaults selected, guard clauses tested, returned value, and caller binding that receives it. This trace exposes both call-site errors and contract defects.
Guided trace
let quoted = final_price(100, 0.1)
The arguments evaluate to 100 and 0.1. They bind to amount and discount_rate; tax_rate receives its default 0. All guards pass, discounted becomes 90, and the function returns 90 to quoted.
Common mistakes
- Giving a required input a misleading default. Omission then appears valid while producing the wrong policy result.
- Placing required parameters after defaulted parameters. Positional calls become difficult or ambiguous to interpret.
- Changing parameter order after adoption. Existing calls may still run but bind values to the wrong meanings.
- Returning different result categories without a contract. Callers cannot use the result predictably.
- Allowing one path to fall through accidentally. The caller receives null even though the function is intended to produce a value.
- Using a magic failure number. A valid calculation may eventually produce the same number.
- Validating too late. Unsafe calculations or side effects may occur before an invalid input is rejected.
- Documenting the formula but not its units. Numerically correct values can still be misused.
- Testing only explicit arguments. Default behavior remains unverified.
- Changing a default silently. Omitted calls change behavior without changing source.
Guided practice
- Write greeting(name, prefix = "Hello") and trace calls with and without the prefix.
- Design a safe interface for calculating tax. Identify which inputs must be required and whether any default is justified.
- Rewrite a function that returns a number, false, or a string so it has one consistent success result and one failure convention.
- State preconditions and postconditions for average(total, count).
- Add guard clauses to prevent a negative amount and a rate outside 0 through 1.
- Create a test that proves omitting a defaulted argument behaves the same as supplying the documented default explicitly.
- Explain why appending a defaulted parameter is often safer than inserting a required parameter at the beginning.
- Trace every return path in a function and identify any accidental fall-through.
Mini design review
Review this proposed interface: approve_payment(amount, force = false). The default looks convenient, but approval is a consequential action and the meaning of force is unclear. A safer contract separates validation from authorization and requires the caller to supply any privileged decision through an explicit, verified boundary.
When evaluating a default, ask not only whether it makes calling easier, but whether omission remains safe, auditable, and obvious to a reviewer.
Hands-on lab: Build a reusable quotation library
Scenario. A sales tool needs reusable functions for item totals, discounts, tax, and delivery. The library must support ordinary quotations while rejecting invalid inputs consistently.
Functions to implement
- line_total(unit_price, quantity) — both parameters are required; reject negative price and nonpositive quantity.
- discounted_amount(amount, discount_rate = 0) — default to no discount; reject rates outside 0 through 1.
- tax_amount(amount, tax_rate = 0.18) — document the default tax rate; reject negative amounts and invalid rates.
- delivery_charge(subtotal, expedited = false) — use a documented ordinary charge, an expedited charge, and a free-delivery threshold.
- quotation_total(unit_price, quantity, discount_rate = 0, tax_rate = 0.18, expedited = false) — coordinate the smaller functions and return null if any required result is invalid.
Contract worksheet
For every function, record its purpose, required parameters, defaulted parameters, units, preconditions, returned value, failure result, postconditions, and whether it has side effects.
Required tests
- ordinary valid quotation;
- all defaults omitted;
- all defaults supplied explicitly;
- each default overridden separately;
- zero and boundary discount or tax rates;
- negative price, zero quantity, and invalid rates;
- subtotal exactly at the free-delivery threshold;
- ordinary and expedited delivery; and
- postcondition checks that totals and component values are nonnegative.
Compatibility exercise. Add an optional service-fee rate to the final quotation interface. Append it with a safe documented default, then rerun every existing test to prove that prior calls retain their behavior.
Deliverable. Submit the source, contract worksheet, argument-binding traces for three calls, test matrix, observed results, and a short compatibility note.
Review questions
- What information about a parameter belongs in a function contract?
- How are positional arguments matched to parameters?
- When is a defaulted parameter used?
- What makes a default safe and unsurprising?
- Why should security-sensitive choices usually be explicit?
- How does a guard clause simplify the main calculation?
- What is the danger of mixing several return meanings?
- How do preconditions differ from postconditions?
- Why must omitted and explicit-default calls both be tested?
- Which interface changes are most likely to break existing callers?
- Why can appending a defaulted parameter preserve compatibility better than reordering existing parameters?
- What should a caller do before using a result that may be null?
Applied challenge: Policy-aware service quote
Design a function named service_quote(hours, hourly_rate, urgency = "standard", discount_rate = 0). Define approved urgency values, reject invalid hours and rates, calculate an urgency multiplier, apply a validated discount, and return one predictable result. State units and every contract condition before implementing the function.
Create tests for omitted defaults, explicit defaults, each urgency value, exact validation boundaries, invalid category values, and overlapping exceptional inputs. Then evolve the interface by adding a defaulted travel charge without changing existing call results.
Success criteria
- Required and optional inputs are clearly separated.
- Every default is documented and safe.
- Guard clauses protect all calculation assumptions.
- Every reachable path returns a predictable result.
- The result has explicit monetary meaning and units.
- Existing calls retain their behavior after the additive change.
- The test matrix proves preconditions, postconditions, defaults, and compatibility.
Lesson summary
Parameters and return values form a function's reusable interface. Required parameters make essential inputs explicit, while defaults reduce repetition only when omission has a safe and obvious meaning. Guard clauses enforce preconditions, consistent returns establish predictable outputs, and documented postconditions and invariants make behavior testable. Stable parameter order, cautious default changes, and contract-focused tests protect callers as an interface evolves.
Next lesson: Local Scope, Closures, and Higher-Order Patterns
Lesson status: Approved.