All lessons in Software Engineering: Programs, Systems, and Maintainable Software

Modules, Interfaces, and Dependency Direction

Separate domain decisions from storage and presentation using small explicit interfaces.

35 minutes · Free lesson

What you will learn

  • Separate domain policy from storage and presentation concerns.
  • Design a small interface around a caller's actual needs.
  • Evaluate a module boundary using change scenarios and tests.

A borrow handler can parse a form, calculate dates, inspect eligibility, build SQL, update the interface, and send a receipt. It may work today, but every change passes through the same block of code. A new storage engine, eligibility rule, or interface can accidentally disturb an unrelated behavior.

Modularity gives changes a place to belong. The purpose is not to maximize the number of files or introduce an abstraction for every line. It is to make the reasons for change visible and limit how far each change must spread.

Group behavior by the decisions it owns

The domain owns rules such as whether a date interval is valid and what a successful return means. Storage owns how records are read and written atomically. Presentation owns how a person supplies inputs and sees results. Application orchestration connects those responsibilities for one use case.

These responsibilities are related but not identical. A database constraint can enforce a domain invariant without making every display decision a database concern. A screen can explain a rejection without deciding that a second active loan is allowed.

A module has high cohesion when its contents support a coherent responsibility. Coupling describes dependencies between modules. Some coupling is necessary: a borrow operation needs persistence. Prefer a narrow dependency that states what the operation needs over a dependency on every capability of a database client or user-interface framework.

Design interfaces from the caller inward

Start with the use case. The borrowing service needs to read eligibility, verify the copy, and create a loan under one transaction. A collection of unrelated get and save calls may hide an important problem: who owns the transaction boundary?

One option is a storage operation that atomically attempts to create a valid loan. Another is a unit-of-work interface exposing a bounded transaction in which the service invokes smaller repository methods. Both can work. The interface must make it impossible to mistake several independent commits for one atomic operation.

Do not promise more than an implementation can preserve. A memory-backed fake and a database adapter should agree on observable success and conflict behavior. A fake that allows two active loans cannot stand in for the persistent implementation when testing the one-active-loan rule.

BoundaryAcceptsReturns or guarantees
Input adapterRaw text or form valuesParsed identifiers and date values, or input errors
Lending serviceA validated borrow commandA loan result or a named domain rejection
Persistence boundaryLoan facts and invariant-sensitive operationAtomic commit or no partial change
Output adapterResult valuesHuman-readable status without changing the domain result

Control dependency direction

If the domain imports a concrete web framework, it becomes harder to exercise without a running web environment. If a user-interface widget directly edits loan rows, it can bypass the service rules. Keep the domain's vocabulary independent and supply environment-specific behavior at the boundary.

Dependency inversion means depending on a suitable abstraction rather than forcing high-level policy to depend directly on a low-level detail. It does not require a formal interface keyword. A small callable, protocol, or constructor parameter can express the dependency.

A clock is a useful example. A rule using today's date should receive that date or a clock function so a test can state the observation date. It should not require changing the machine clock or waiting overnight. The same principle applies to identifier generation and filesystem access when they affect observable behavior.

Worked example

Locate a change without spreading it

  1. The original service calculates a fixed fourteen-day due date inside a form handler and writes SQL from the same function.
  2. Move the due-date decision to a loan-policy function accepting the borrowing date and member category.
  3. Keep parsing in the input adapter. Invalid date text is an input error; an unacceptable date interval is a domain rejection.
  4. Let one persistence boundary own the atomic loan insertion and conflict behavior.
  5. Test the policy with fixed date values, the persistence operation against a real disposable database, and the adapter's error mapping separately.
  6. When a new member category receives a different duration, change the policy and its cases. No report query or button component needs to learn the calculation.

Recognize abstraction costs

An interface is a promise to future callers. Every additional method increases the behavior implementations must support. A generic repository with arbitrary query strings may provide little separation because callers still know the database schema. A narrow loan operation can communicate more meaning with fewer methods.

Avoid speculative flexibility. If there is one implementation and no costly dependency to isolate, another layer may only obscure the flow. Introduce a boundary when it protects an invariant, makes a real change easier, or enables meaningful testing of behavior that otherwise depends on an external resource.

Duplication also requires judgment. Two similar-looking calculations may represent different rules and should change independently. Combining them prematurely can couple unrelated product decisions. Ask whether the behavior has the same reason to change, not only whether its text looks similar.

Review with change scenarios

Test a proposed design by walking through plausible changes: a different eligibility rule, a new report, another input adapter, and a storage failure. Identify which modules should change and compare that expectation with the actual dependencies.

A design diagram should show who calls whom and who owns a transaction or resource. It should not hide every interesting behavior behind boxes named manager and service. Precise names such as LoanPolicy and LoanRepository convey useful responsibilities, but names are only helpful when the code follows them.

Exercise

A domain object formats HTML and executes database queries in its return method. Identify two different reasons this object changes and propose boundaries that preserve the return rule.

Check your answer

Presentation changes can alter HTML while storage changes can alter SQL. Keep the state transition and date rule in the domain or service, persist the transition through an atomic repository operation, and format the result in an output adapter. Tests should assert the transition independently of HTML and verify persistence separately.

Exercise

A fake repository returns success for every insert. Why can a service unit test pass while the real system mishandles duplicate active loans?

Check your answer

The fake omits the repository's conflict contract. It cannot reveal whether the service maps a conflict correctly or preserves prior state. Add a fake capable of returning the specified conflict for service tests and an integration test that creates real competing or duplicate inserts against the database constraint.

Summary

Useful boundaries isolate decisions and make resource ownership explicit. Design interfaces around caller needs, including failure and transaction semantics. Introduce abstractions for concrete reasons and evaluate them with plausible changes, not only diagram aesthetics.

Next action

Sketch the input adapter, lending service, policy, repository, and output adapter for your capstone. Mark the transaction owner and show where each failure becomes a user-visible result.

Choose another lesson