PeaBox Lab › PeaLang › Learn › Chapter 9 › Lesson 1

Part II — Intermediate Development · Chapter 9 · Lesson 1 of 5 · 6 min read

Lesson 1: Module Boundaries, Imports, Exports, and Initialization

Lesson level: Intermediate

Purpose: Move from single-file programs to modules with clear responsibilities, explicit public surfaces, and predictable initialization.

Learning objectives

Release note: the keywords import, export, and as are reserved words in the language. Exact resolution rules, search paths, and error messages must be verified against the installed release's documentation. Examples below are illustrative.

1.1 Why modules

A single file works for a small rule. As programs grow, one file mixes unrelated decisions, makes tests slow to target, and hides which names other code depends on. A module is a source file treated as a unit with its own names, a deliberate public surface, and a defined place in the dependency graph.

Good module boundaries follow responsibilities, not file size. A module should be describable in one sentence, such as "validates orders" or "calculates shipping charges".

1.2 What a module owns

ElementOwned by the moduleVisible to others
Top-level constants and functionsYesOnly when exported
Helper functionsYesNo, by default
Imported namesUsed locallyNo
Initialization codeRuns once for the moduleEffects only, never raw state

Treat everything as private unless a caller needs it. A smaller public surface is easier to document, test, and change.

1.3 Exporting a public surface

Use export to mark the names that form the module's contract.

# pricing.pea
const tax_rate = 0.18

function net_price(amount) {
    return amount + tax(amount)
}

function tax(amount) {
    return amount * tax_rate
}

export net_price

Here tax and tax_rate stay private. Callers depend only on net_price, so the tax calculation can change without affecting them.

1.4 Importing from another module

Use import to bring in a module's exported names. Use as to give an import a clear local name or to avoid a collision.

# checkout.pea
import pricing as price

let total = price.net_price(100)
print "Total: {total}"

Importing with a qualified name keeps the origin of each call visible to the reader. Prefer it when a module exports several names with common words in them.

1.5 Designing the public surface

1.6 Initialization

Top-level statements in a module run when the module is loaded. Initialization should be cheap, deterministic, and free of hidden effects.

Appropriate at loadAvoid at load
Declaring constants and functionsReading files or calling services
Building small lookup tablesPrinting output
Validating the module’s own constantsDepending on the order other modules load
Computing values from other constantsStarting concurrent work

A module that needs a capability should receive it through a function call made by its caller, not acquire it implicitly while loading. That keeps permission use visible, as practiced in Chapter 8.

1.7 Load once, share state carefully

A module is normally initialized once and then reused by every importer. Mutable top-level state is therefore shared by all of them. Prefer immutable constants and pass state explicitly. If shared state is unavoidable, hide it behind exported functions so that only the owning module changes it.

1.8 Illustrative example: two modules

# validate.pea
function valid_amount(amount) {
    return amount >= 0
}
export valid_amount

# order.pea
import validate as v
import pricing as price

function quote(amount) {
    if not v.valid_amount(amount) {
        return null
    }
    return price.net_price(amount)
}
export quote

order depends on validate and pricing. Neither of those depends on order, so dependencies flow in one direction.

1.9 Common mistakes

MistakeEffectCorrection
Exporting every nameLarge, fragile contractExport only what callers need
Heavy work at load timeSlow, effectful importsMove work into functions
Mutable shared top-level stateHidden coupling between importersPass state explicitly
Importing a name that is not exportedImport errorAdd the export or change the caller
Name collisions between importsAmbiguity or overwritten namesUse qualified or aliased imports
Printing from module loadNoisy, order-dependent outputReturn values instead

1.10 Diagnostic workflow

1.11 Guided practice

1.12 Hands-on lab: split a rules file

Scenario: Take the Chapter 1 case-priority program and divide it into three modules.

Requirements. Create a module of policy constants, a module that decides priority, and a small main file that supplies sample values and prints results. Export only what is needed and give each module one responsibility.

Tests. Confirm that cases A through F from the Chapter 1 checkpoint still produce the same decisions. Add a test that imports only the decision module.

Deliverables. The three source files, a list of exports with a sentence of documentation for each, a dependency diagram in text form, and a note stating what runs at load time.

Acceptance criteria.

1.13 Review questions

1.14 Applied challenge

Choose one of your earlier checkpoint programs and restructure it into modules. Write a one-page module map listing each module, its responsibility, its exports, its imports, and anything it runs at load time. Then change one private helper and show that no importer needs to change.

1.15 Lesson summary

1.16 Transition to Lesson 2

The next lesson covers cross-module contracts and dependency direction, building on the one-way dependencies sketched here to define explicit contracts between modules.

Lesson status: Ready for review.

← Previous Next →