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

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:

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

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:

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:

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

Guided practice

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

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

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

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

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.

← Previous Next →