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
- State a module contract: inputs, outputs, failure behavior, and invariants.
- Arrange modules in layers with dependencies pointing one way.
- Recognize and remove circular dependencies.
- Use adapters and passed-in values to keep core logic independent of infrastructure.
- Test a module against its contract in isolation.
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 element | Example for a quote function |
|---|---|
| Inputs | A non-negative number of units and a tier string |
| Output | A map with total, discount, and reason code |
| Failure | Returns a map with an error reason code; never raises for invalid input |
| Invariants | Total is never negative; reason code is from a fixed list |
| Side effects | None; 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
| Layer | Contains | May depend on |
|---|---|---|
| Main / entry | Wiring, sample values, printing | All lower layers |
| Adapters | File, HTTP, and logging access | Core, constants |
| Core rules | Validation, decisions, calculations | Constants only |
| Constants | Thresholds, codes, labels | Nothing |
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.
- Extract shared code: move what both need into a third, lower module.
- Invert the dependency: have the lower module accept a function or value from the higher one as a parameter.
- Merge: if two modules cannot be separated, they may be one responsibility.
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
- Adding an optional field or a new export is compatible.
- Renaming or removing an export or field is breaking.
- Changing the meaning of a reason code is breaking even if its name is unchanged.
- Record breaking changes in the module's documentation and update importers in the same change.
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
| Mistake | Effect | Correction |
|---|---|---|
| Importing upward (core imports an adapter) | Core needs capabilities to run or test | Pass the adapter in or reverse the import |
| Circular imports | Order-dependent loading and unclear ownership | Extract shared code or invert the dependency |
| Undocumented contract | Callers rely on accidents | Write inputs, outputs, and failures above each export |
| Returning internal structures | Callers depend on private details | Return stable portable shapes |
| Reusing a reason code for a new meaning | Silent breakage | Add a new code |
| Tests that reach into private helpers | Tests break on refactoring | Test through exports only |
2.11 Diagnostic workflow
- Draw the import graph for the failing modules as arrows from importer to imported.
- Look for a cycle or an upward arrow.
- Check whether the failing call matches the written contract.
- Compare the data shape produced with the shape expected.
- Fix the contract or the caller, not both at once, and rerun the smallest test.
2.12 Guided practice
- Write the contract for an eligibility function: inputs, output, failure codes, and invariants.
- Place four modules into the layers from section 9.2.4.
- Find the cycle in a pair of modules that import each other and remove it.
- Rewrite a function that imports a logger so that it accepts a logging function.
- Classify three changes as compatible or breaking.
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.
- No cycles remain and every dependency points downward.
- Core modules import no adapter.
- Every export has a written contract.
- Tests call only exported functions.
2.14 Review questions
- What does a module contract include?
- Why should dependencies point toward stable modules?
- What problems do circular dependencies cause?
- Name three ways to remove a cycle.
- How does passing a function in keep a core module capability-free?
- Which kinds of change break a contract?
- Why test only through exports?
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
- A contract states what callers may rely on; everything else is private.
- Dependencies should point downward from entry points to adapters to core rules to constants.
- Remove cycles by extracting shared code or inverting a dependency.
- Pass behavior in to keep the core free of capabilities and easy to test.
- Version contracts: add compatibly, and treat renames and meaning changes as breaking.
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.