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

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

Lesson 2: Cross-Module Contracts and Dependency Direction

Lesson level: Intermediate

Purpose: Define explicit agreements between modules and arrange dependencies so that changes stay local and the project remains testable.

Learning objectives

Release note: import and export behavior should be verified against the installed release. Module names and functions here are illustrative.

2.1 What a contract is

A contract is the part of a module that other modules may rely on. It names each exported function and states what it accepts, what it returns, how it fails, and what it guarantees. Anything not in the contract is an implementation detail that may change without notice.

Contract elementExample for a quote function
InputsA non-negative number of units and a tier string
OutputA map with total, discount, and reason code
FailureReturns a map with an error reason code; never raises for invalid input
InvariantsTotal is never negative; reason code is from a fixed list
Side effectsNone; no files, network, or output

2.2 Writing the contract down

Place a short comment block above each export describing its contract. Keep it specific enough to test.

# quote(units, tier) -> {total, discount, reason} # units: number >= 0; tier: "standard" or "gold" # On invalid input returns {error: "bad_input"}; never raises.

A contract written this way becomes the checklist for the module's tests and the reference for its callers.

2.3 Dependency direction

If module A imports module B, then A depends on B. Choose the direction deliberately. Stable, general modules should be depended on; volatile, specific modules should depend on others. A good rule is that policy and domain rules depend on nothing external, and infrastructure depends on them.

2.4 A layered arrangement

LayerContainsMay depend on
Main / entryWiring, sample values, printingAll lower layers
AdaptersFile, HTTP, and logging accessCore, constants
Core rulesValidation, decisions, calculationsConstants only
ConstantsThresholds, codes, labelsNothing

Dependencies point downward only. A lower layer never imports from a higher one. This keeps the core testable without any capability and makes adapters replaceable.

2.5 Circular dependencies

A cycle occurs when A imports B and B imports A, directly or through other modules. Cycles make load order matter, hide responsibilities, and complicate testing. Remove a cycle by choosing one of these fixes.

2.6 Passing behavior in

Instead of importing an adapter, a core function can receive what it needs as an argument. The caller decides which adapter to supply.

function summarize(rows, log) { # core logic; calls log(event) without knowing how it is stored }

The core stays free of capabilities, and a test can pass a simple recording function in place of the real logger.

2.7 Stable data shapes

Modules often exchange maps and lists. Agree on the exact keys and value types, and keep them portable: null, boolean, number, string, list, and string-keyed map. Add fields rather than renaming them, and treat missing optional fields as absent rather than as errors. Chapter 7's annotations can document these shapes when typing is in use.

2.8 Versioning a contract

2.9 Testing a contract

Write tests that call only exported functions. Cover valid inputs, each failure code, and boundary values. When the core depends on a passed-in function, test with a fake and assert on what the fake received. A module whose tests need real files or network access is probably holding responsibilities that belong in an adapter.

2.10 Common mistakes

MistakeEffectCorrection
Importing upward (core imports an adapter)Core needs capabilities to run or testPass the adapter in or reverse the import
Circular importsOrder-dependent loading and unclear ownershipExtract shared code or invert the dependency
Undocumented contractCallers rely on accidentsWrite inputs, outputs, and failures above each export
Returning internal structuresCallers depend on private detailsReturn stable portable shapes
Reusing a reason code for a new meaningSilent breakageAdd a new code
Tests that reach into private helpersTests break on refactoringTest through exports only

2.11 Diagnostic workflow

2.12 Guided practice

2.13 Hands-on lab: untangle a project

Scenario: You are given three modules for orders, pricing, and reporting in which pricing imports reporting and reporting imports pricing.

Requirements. Draw the import graph, identify the cycle, and break it by extracting shared constants into a lower module. Move all file and logging access into one adapter module that the main file passes in. Write the contract for each exported function.

Tests. Test the core modules with no capability, using a recording fake for logging. Add one test per failure code and one test per boundary value.

Deliverables. Before and after import graphs, the contracts, the source files, the tests, and a note listing which changes would be breaking for existing callers.

Acceptance criteria.

2.14 Review questions

2.15 Applied challenge

Take the Chapter 8 permission-aware data utility and sketch its module structure. Give the layers, the imports, the contract for each export, and the adapters. Identify one place where you would pass a function in rather than import it, and explain how a test would use it.

2.16 Lesson summary

2.17 Transition to Lesson 3

The next lesson covers project layout, configuration, and documentation: where module files, tests, and configuration live, and how to document a project so others can use it.

Lesson status: Ready for review.

← Previous Next →