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
- Explain what a module is and why boundaries matter.
- Use the import, export, and as keywords to build explicit module interfaces.
- Decide what a module should expose and what it should keep private.
- Reason about when module code runs and what it may do at initialization.
- Diagnose common import, export, and initialization failures.
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
| Element | Owned by the module | Visible to others |
|---|---|---|
| Top-level constants and functions | Yes | Only when exported |
| Helper functions | Yes | No, by default |
| Imported names | Used locally | No |
| Initialization code | Runs once for the module | Effects 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
- Export behavior, not storage. Expose a function that returns a decision rather than a mutable table.
- Export stable names. Renaming an export is a breaking change for every importer.
- Keep exports small and cohesive so a reader can learn the module from its export list.
- Document each export's inputs, outputs, and failure behavior.
- Return portable values at boundaries that hosts may call.
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 load | Avoid at load |
|---|---|
| Declaring constants and functions | Reading files or calling services |
| Building small lookup tables | Printing output |
| Validating the module’s own constants | Depending on the order other modules load |
| Computing values from other constants | Starting 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
| Mistake | Effect | Correction |
|---|---|---|
| Exporting every name | Large, fragile contract | Export only what callers need |
| Heavy work at load time | Slow, effectful imports | Move work into functions |
| Mutable shared top-level state | Hidden coupling between importers | Pass state explicitly |
| Importing a name that is not exported | Import error | Add the export or change the caller |
| Name collisions between imports | Ambiguity or overwritten names | Use qualified or aliased imports |
| Printing from module load | Noisy, order-dependent output | Return values instead |
1.10 Diagnostic workflow
- Read the error and note whether it concerns resolving the module, a missing export, or a runtime failure.
- Confirm the module path and file name as the importer wrote them.
- Check that the needed name is exported and spelled identically.
- Look for a circular dependency between the modules involved.
- Check whether load-time code is failing before any function is called.
- Run pea check on the files involved, then the smallest example that imports them.
1.11 Guided practice
- Describe in one sentence the responsibility of a pricing module and a validation module.
- List which names from each should be exported and which should stay private.
- Rewrite an import to use a clear alias.
- Move a load-time file read into a function that the caller invokes.
- Draw the dependency direction among three modules.
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.
- No module prints or performs input and output at load time.
- Dependencies point in one direction.
- Private helpers are not exported.
- Results match the original program for every test case.
1.13 Review questions
- What makes a good module boundary?
- Why should modules export as little as possible?
- What is the purpose of as in an import?
- What kinds of work belong at load time, and what does not?
- Why is shared mutable top-level state risky?
- How should a module obtain a capability it needs?
- How would you recognize a circular dependency?
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
- A module is a unit with one responsibility and an explicit public surface.
- Export only what callers need and keep names stable.
- Use qualified or aliased imports to keep origins clear.
- Keep load-time code cheap and free of effects; pass capabilities in through function calls.
- Keep dependencies flowing in one direction and avoid shared mutable state.
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.