Deep Modules: Evaluate the Work an Interface Leaves to Its Callers

The project screen displays a title and a status. To get those two fields, its component has become the coordinator for a small request pipeline: acquire a resource, read JSON, validate it, translate API fields, and release what was acquired. A second screen copies the sequence. A third needs the same data next week.

This illustrative application already has small functions for each step. What it lacks is an operation that completes the job its screens need. Every new caller has to learn the pipeline before it can display a project.

That is the problem module depth helps evaluate. A module is deep when it provides substantial useful functionality through an interface that asks comparatively little of its callers. Its depth depends on the work it absorbs and the knowledge it removes from ordinary use, rather than on a particular line count.

We will compare two TypeScript interfaces for loading a project summary, then follow a screen that changes selection while a request is in flight. The second part matters: moving request details behind one call should make the screen simpler without concealing the responsibilities that still belong to it.

On this page

Count the Whole Interface

A TypeScript signature tells us something about an operation:

type ProjectSummary = {
  id: string
  title: string
  status: 'active' | 'archived'
}

type LoadProject = (id: string) => Promise<ProjectSummary>

It does not explain whether the result can be stale, whether the operation checks HTTP errors, whether it validates remote data, or what happens when the caller changes projects before the promise settles.

Those questions are still part of the interface if callers must know their answers to use the function correctly.

An interface includes formal elements, such as method signatures, and informal elements, such as behavioral guarantees and sequencing requirements. In ordinary application TypeScript, the compiler can check an argument's declared type without proving that a remote payload matches it or that the caller handles the operation's lifecycle correctly.

Consequently, reducing a signature to one argument does not automatically make an operation easy to use. A realistic interface assessment includes the facts that belong in its documentation, the order of required calls, its failure behavior, and the responsibilities left with the caller.

A Resource Loader Can Expose a Pipeline Without Simplifying It

Here is the sequence the first screen has to assemble. The low-level operations are fictional, but the caller's obligations are explicit:

type RawProject = {
  project_id: string
  display_name: string
  lifecycle: 'OPEN' | 'CLOSED'
}

type ProjectRequest = {
  readJson(): Promise<unknown>
  release(): void
}

declare function beginProjectRequest(
  id: string,
  signal: AbortSignal,
): Promise<ProjectRequest>

declare function validateProject(value: unknown): RawProject

declare function toProjectSummary(value: RawProject): ProjectSummary

async function loadForScreen(
  id: string,
  signal: AbortSignal,
): Promise<ProjectSummary> {
  const request = await beginProjectRequest(id, signal)

  try {
    const payload = await request.readJson()
    return toProjectSummary(validateProject(payload))
  } finally {
    request.release()
  }
}

These declarations describe a fictional request abstraction with an explicit release requirement. They are not an assertion that ordinary browser fetch responses expose a release method.

The screen must know that validation precedes translation, that a request must be released even if decoding fails, and that the transport representation is different from the product representation.

If several screens need the same complete operation, they must either repeat this sequence or share their own coordinating helper. The low-level API has supplied capabilities without yet supplying the abstraction those screens need.

The test for shallowness is not that each function is short. It is that learning and coordinating the interfaces costs nearly as much as understanding the work they perform.

Give the Caller a Useful Operation

The next screen should not have to reconstruct that sequence. Give it an operation whose result already matches the product view it needs:

type ProjectLoader = {
  loadSummary(
    id: string,
    options: { signal: AbortSignal },
  ): Promise<ProjectSummary>
}

function createProjectLoader(): ProjectLoader {
  return {
    async loadSummary(id, { signal }) {
      const request = await beginProjectRequest(id, signal)

      try {
        const payload = await request.readJson()
        return toProjectSummary(validateProject(payload))
      } finally {
        request.release()
      }
    },
  }
}

The factory shape is just one implementation option; a plain function could provide the same operation. What matters is the responsibility it accepts.

The caller no longer coordinates resource release, validation, or transport-to-domain translation. It receives the representation it already needs, and it supplies an abort signal because the caller knows when its request becomes irrelevant.

The implementation has not become more valuable by being longer. It has become more valuable by completing a coherent operation that consumers previously had to assemble themselves.

A real implementation must define the behavior of beginProjectRequest, validateProject, and toProjectSummary. This example keeps those mechanisms abstract to make the comparison about caller work. Moving their names into another file without assuming their coordination would provide much less benefit.

A Simple Operation Still Needs an Explicit Contract

Before calling the second interface simpler, describe what it promises. For this example, a reasonable contract would include:

  • A successful result is a validated ProjectSummary, independent of the transport field names.
  • Network, HTTP, decoding, and validation failures reject the promise; failure categories and their representation must be documented.
  • The operation releases any acquired request resource after success or failure.
  • The supplied signal is forwarded to the request mechanism; cancellation follows that mechanism's documented behavior.
  • The operation neither caches results nor automatically retries failed requests.
  • The server remains responsible for authorization; a successful TypeScript call grants no additional access.

These details make the abstraction usable. They are not necessarily evidence that it has failed.

The important distinction is whether the remaining knowledge corresponds to decisions a caller actually has to make. A screen needs to know that a project cannot be loaded and whether cancellation is treated separately from a visible error. It usually does not need to choose the wire-field mapping or remember how to release an internal request handle.

Omitting a detail that affects correctness produces an apparently simple interface with a hidden cost. This creates a false abstraction: important information has disappeared from view without disappearing from the caller's responsibilities.

Keep the Remaining Lifecycle Responsibility Visible

Now let the user select a second project while the first request is finishing. The new loader can return a perfectly valid summary for the wrong selection. It cannot know which project the user currently wants to see; that information belongs to the screen or another owner of the interaction.

Cancellation alone is also insufficient protection against stale updates. An operation can complete just before it is cancelled, or some underlying work might not be interruptible. The consuming code should still check whether a result belongs to its current request.

Here is a framework-independent sketch:

let latestRequest = 0
let currentController: AbortController | undefined

declare const loader: ProjectLoader

declare function showProject(project: ProjectSummary): void

declare function showLoadFailure(error: unknown): void

async function selectProject(id: string): Promise<void> {
  const requestNumber = ++latestRequest
  currentController?.abort()

  const controller = new AbortController()
  currentController = controller

  try {
    const project = await loader.loadSummary(id, {
      signal: controller.signal,
    })

    if (requestNumber === latestRequest && !controller.signal.aborted) {
      showProject(project)
    }
  } catch (error) {
    if (requestNumber === latestRequest && !controller.signal.aborted) {
      showLoadFailure(error)
    }
  } finally {
    if (requestNumber === latestRequest) currentController = undefined
  }
}

This sketch represents one screen's selection sequence; an actual UI also needs to cancel or invalidate the current request when that screen is disposed. It does not implement a loading indicator or a complete screen state model.

Its purpose is to show the boundary honestly. The loader owns the mechanics of producing a valid summary and releasing its internal resource. The interaction owner decides which request is current and whether its result should be displayed.

A stateful data layer could take on more of that lifecycle. Doing so would require a richer contract about subscribers, ownership, cancellation, and result freshness. It would not be an improvement merely because the screen's call became shorter.

Assess Depth Against a Particular Use Case

The same interface can offer different value to different consumers.

A project screen may want one complete summary-loading operation. A diagnostic tool might genuinely need access to the raw response and separate decoding stages. Keeping low-level capabilities available for that tool does not require every screen to coordinate them.

Consider what ordinary consumers need to understand. Optional facilities do not impose their full complexity on every caller when the interface lets ordinary consumers ignore them safely. A sensible default can therefore improve effective simplicity without removing necessary control.

Conversely, an API that requires every screen to choose a decoder, wire schema, resource policy, and retry implementation makes those choices part of the common case, even when most screens want identical behavior.

Review depth using representative calls. A settings page, a server operation, and a background task may have different needs. Do not assume that the shortest demonstration covers all of them, or that the most unusual consumer should determine the ceremony required everywhere.

Avoid Turning Depth Into a Size Target

Module depth compares interface complexity with the useful functionality provided. It is a conceptual cost-benefit model, not a numerical metric or a request to maximize implementation size.

Adding speculative behavior increases maintenance costs even if callers do not see it. A loader that quietly adds retries, cross-user caching, prefetching, and background refresh has introduced substantial policy and new failure modes. Those features need real requirements and accurate contracts.

Small modules can also be useful. A tiny adapter may isolate an external dependency, make a domain conversion explicit, or enforce a required check. Its value should be evaluated in that context. A method's line count cannot settle the question.

The practical goal is to obtain useful functionality while keeping the required knowledge proportionate. Both a giant collection of unrelated responsibilities and a maze of tiny forwarding steps can make that harder.

Review the Caller Before Celebrating the Module

A useful review compares the complete work on both sides of the boundary:

QuestionEvidence to inspect
What does the caller actually need?The operation's place in a real feature
What must the caller coordinate?Required calls, ordering, and cleanup
What must the caller know?Types, guarantees, failure behavior, and limitations
What complexity does the implementation absorb?Validation, translation, resource ownership, and other justified mechanisms
Which obligations remain?Decisions requiring the caller's interaction or domain context

For the project loader, the improvement is specific: consumers can obtain a validated domain summary without reconstructing the request pipeline. Request relevance, visible error handling, and authorization expectations remain explicit.

For this application, keep request acquisition, validation, translation, and release inside the loader. Keep selection relevance with the interaction owner, backed by an explicit ownership check. Document the boundary so the next screen can use it without rediscovering the request pipeline.

Apply the same review to your next abstraction: read one complete caller before and after the change. A useful module removes work from that caller and makes the remaining decisions easier to see.