Domain-Driven Design: Modules—cohesion and responsibilities for organizing the domain
Learn to define Modules from business responsibilities, offer public interfaces, and control their dependencies. With an executable TypeScript example, distinguish a module from a folder, layer, or Bounded Context and establish useful boundaries for working with AI.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
An academy changes how it opens enrollment for its courses. To do so, the team reviews controllers, several services files, and a repositories folder. Each location contains part of the workflow, mixed with assessment and certificate components.
The organization makes controllers easy to find, but does not readily answer who controls opening a course offering or what the enrollment process should use to query it. An AI tool finds an internal class, imports it directly, and ends up depending on how another component stores its data.
Renaming every folder does not solve the problem. We need groupings that express business responsibilities and boundaries indicating what each consumer may know. In DDD, Modules help organize the model for that purpose.
A Module should tell part of the model's story
A Module groups related concepts so you can understand them together without mentally carrying the whole system. Evans proposes seeking groupings with high cohesion and low coupling, and naming them in business language, in the Modules section of his DDD reference.
Cohesion describes how closely a grouping's internal responsibilities relate. course-planning has a coherent explanation if it brings together course offerings, dates, and opening conditions. Putting all platform email sending there simply because messages contain course names weakens that explanation.
Coupling describes dependencies between components. If Enrollments needs to know Planning's columns, internal classes, and reconstruction rules, it has more coupling than if it queries a specific public capability.
The objective is not to eliminate every dependency: the parts must collaborate. It is to make them depend on information and behavior the owner is willing to offer, without needing its internal details.
From language to a useful boundary
To propose a Module, start with real decisions and changes:
Which concepts must you understand together to explain a rule?
Who makes decisions about them?
What do business changes tend to modify together?
What information does another part need, and what should remain internal?
In our academy, Planning decides whether a course offering accepts enrollments. Enrollments records who participates and checks that no duplicate enrollment exists. Both responsibilities collaborate, but they are not identical.
This does not require separating every noun. student, course, date, and status do not automatically constitute four Modules. One class per folder can scatter a single rule just as a huge folder can mix different responsibilities.
If explaining an operation requires constantly jumping between two supposed Modules, review whether the boundary is cutting apart concepts that should stay together.
Technical and business organization can coexist
This partial structure primarily organizes by component type:
It can work for a small application. Its limitation appears as those folders grow: each responsibility is distributed across files sharing a location because of their technical function, rather than the concept they represent.
An alternative is to group first by responsibility and retain layers within each grouping. This proposed structure is illustrative; these are not files from an existing project:
A layer separates responsibility types, such as coordination and technical mechanisms. A Module names a coherent part of the model. These are compatible axes, but not equivalent ones.
Strictly speaking, a Domain Module organizes model concepts; also grouping its application and infrastructure components under the same root is a code organization choice. That does not turn every file under that root into Domain code.
You do not need to create empty folders to complete the structure. A Domain Service can live beside the Domain concepts it collaborates with; its location should help explain the responsibility it expresses.
Complete example: Planning and Enrollments collaborate
The agreements guiding imports
We will use two Modules within the same educational Bounded Context: they share a coherent model of course offerings and enrollment. Imports between them will be allowed only through their public.ts files.
Planning offers a course offering lookup. Enrollments defines the minimum contract it needs to know availability. An assembly point adapts both contracts; Enrollments does not even import Planning's public implementation.
The graph will be:
Assembly -> course-planning/public.ts
Assembly -> enrollments/public.ts
Assembly adapter:
queries Planning -> translates to Enrollments contract
Within each Module:
public.ts -> Application or own implementation -> own Domain
This dependency inversion is an example choice to demonstrate a consumer contract. It does not require introducing an adapter for every small call within a shared model.
The rules are: enrollment is accepted only if the offering exists and is open; neither the enrollment identifier nor the student–offering pair may be duplicated. We will not model capacity limits, payments, or waiting lists.
Program files
This project is self-contained and requires no external dependencies. Save the indicated files with this structure:
We will use Node.js 24.21.0, which can execute this TypeScript syntax through type stripping. That execution does not include static type checking. The example's data is constructed locally; external inputs would need structural validation at their entry boundary.
The consumer receives a description, not the CourseEdition object or internal Map. Planning could later replace the boolean with a date policy while retaining the public contract's meaning. If its meaning or synchronous behavior changes, its consumers will need review.
We do not export Enrollment or EnrollStudent from the public entry point. We offer a capability and the contract it needs to work. Explicit exports make that decision reviewable; export * over every file would expose more dependencies than necessary.
The enrollment Map belongs to this demonstration's in-memory state. It sits beside the Use Case to avoid introducing persistence unrelated to the topic; it is not a proposal for organizing a database in Application. A real implementation would separate that mechanism and define its saving guarantees.
The workflow starts by querying Planning, translates its description into availability, and records an enrollment. The second request for the same pair is rejected. Closed or nonexistent offerings do not produce an enrollment.
The four tests were run and passed with Node.js 24.21.0. They use public entry points. The last checks exports present at runtime; type contracts are removed during execution, and no static TypeScript checking was performed. None of these tests proves, by itself, that every project import respects the boundaries.
The program retains data only during execution. Checking whether enrollment is open and recording it are not an atomic operation with Planning; the example does not resolve concurrent closure, capacity limits, or coordination between processes. Those guarantees require additional agreements and implementation.
A public interface does not make every file private
A file with imports or exports is a module in the TypeScript and JavaScript system, as the TypeScript handbook explains. That technical meaning is not equivalent to the conceptual DDD Module: our Module groups several files.
In this project, public.ts establishes a convention. Another file could still write this dependency prohibited by the design:
// Fragmento que muestra una violación del límite, no una instrucción de uso.import { CourseEdition } from'./course-planning/domain/course-edition.ts';
The runtime does not prohibit it because of the name domain. Controlling that boundary requires review and, depending on the project, automated rules detecting cross-Module imports through internal paths. They must also consider reexports and type dependencies, not just runtime calls.
If you turn a grouping into a package, Node.js's exports field can limit its entry points through package resolution. The Node.js documentation also warns that this encapsulation is not an absolute barrier against direct-path access. You do not need to introduce packages now to explain access rules.
Module, folder, layer, package, and Bounded Context
A folder groups files. It can represent a Module if it reflects a responsibility and its boundaries, but does not create them merely by existing.
A layer separates types of technical or design responsibility. It can organize components within a Module without itself describing which part of the business they represent.
A package is a unit of code organization and distribution. It can contain one or several Modules; it does not need to correspond to an independent deployment.
A Bounded Context defines where a model and its language maintain consistent meaning. A Module organizes concepts within that model. Fowler explains that delineation in his article on Bounded Context.
Our example allows direct collaboration because both Modules belong to the same Bounded Context. If Planning and Enrollments belonged to different contexts, their integration would need review. In a design requiring separation between contexts, they would not import each other's implementations: they could collaborate through an HTTP Anticorruption Layer, or ACL, with consumer contracts. That query and local save do not constitute a shared transaction.
Commerce: sharing a class does not always reduce coupling
A store puts everything reusable into shared: Money, customer, order, discounts, and billing access. Initially, it avoids long imports; later, every change affects all consumers.
The important decision is distinguishing a small concept with stable meaning from responsibilities that only share a name. A common Money could be reasonable if its rules are the same for its consumers. A universal Customer with commercial, tax, and delivery attributes can force them to evolve together.
Before extracting, identify who owns the concept and what compatibility it promises. Duplicating a small representation may be preferable to creating the wrong common dependency. Reusing code is useful when you also reuse the same meaning.
This scenario teaches how to evaluate the cost of a shared Module, not to prohibit one on principle.
Logistics: an import cycle can reveal an incorrect boundary
Suppose shipments imports internal routes rules, and routes imports internal shipments statuses. A modification needs coordinated changes in both directions.
Moving types to shared or using dynamic imports does not necessarily solve it. First ask whether the rules form a single responsibility, whether a dependency can be inverted through a specific contract, or whether an Application operation should coordinate both without mixing them.
An import cycle is a signal to investigate, not automatic proof that Modules should be merged. Excessive coupling can also exist without any cycle.
This example adds another decision: control the direction of knowledge as well as reduce what each consumer needs to know.
Evolving boundaries without breaking behavior
Start with a responsibility and its scenarios. Define the public entry point, move related components, and change its consumers to use that entry point. Review remaining imports and retain behavior tests during the change.
Internal evolution can become more localized, but that is not absolute independence: changing a public contract still affects consumers. If you modify synchrony, errors, or a response's meaning, explicitly review those consequences.
Avoid a global index.ts that reexports the whole application. It can hide where each dependency comes from and facilitate cycles. One entry file per Module is useful when it expresses a deliberate selection, not when it functions as an automatic file inventory.
When simpler organization is enough
A small application with a single responsibility can start with a few files and a clear entry point. It does not need one Module per Entity or four layers repeated for every concept.
Introduce new boundaries when they let you understand rules together, isolate real changes, or control dependencies that are already problematic. If every trivial operation crosses five Modules and all change together, review whether separation is fragmenting a coherent responsibility.
Prompts for guiding AI with explicit boundaries
Proposing groupings from evidence
Analyze this structure and the three attached business changes. Propose Modules with responsibilities, included components, consumers, and boundary questions. Do not edit files or automatically divide by Entity. Distinguish groupings within a Bounded Context from possible boundaries between contexts. A person will validate the meaning of terms and check which components change together.
Implementing without exposing internal details
Add the enrollment-opening check to Enrollments. Planning is consumed only through its public entry point; Enrollments defines the availability it needs, and assembly adapts both contracts. Do not import internal classes or add packages or frameworks. Provide the change and tests for open, closed, and nonexistent offerings. A person will review every new import and run the contract tests.
Reviewing the change's coupling
Review the diff against the attached Module and dependency map. Look for cross-Module internal imports, reexports expanding the public interface, cycles, and business concepts moved to shared without an owner. Do not modify files. Return evidence, effect, and alternatives; mark uncertainties. A person will also check type imports and decide whether the boundary still represents a coherent responsibility.
Asking for “modular code” is not enough. You must provide responsibilities and permitted dependencies. Then review the implementation: a tool can respect folder names while creating imports that negate their boundaries.
Three exercises with reasoned solutions
1. Changing the representation of opening
Planning replaces #enrollmentOpen with internal dates, but still offers the same result in findEdition(). What should change in Enrollments?
Reasoned solution: nothing, if the contract's meaning stays the same and the adapter still obtains the same facts. Tests should confirm its scenarios. If opening now depends on the clock, Planning needs tests of its time boundaries; hiding the detail does not eliminate that responsibility.
2. Reexporting every Entity
AI proposes export * to prevent other Modules from needing internal paths. Is that enough?
Reasoned solution: it turns internal details into public dependencies. Review what capability each consumer really needs and export only what was agreed. Changing an import's path does not reduce that consumer's knowledge of the implementation.
3. Creating a dates Module
Two responsibilities use dates, and grouping their rules into dates is proposed. One calculates delivery deadlines; the other, certificate validity. Would you group them?
Reasoned solution: sharing a data type does not demonstrate cohesion. Logistics deadlines and academic validity involve different decisions. A formatting utility could be shared, but policies must retain their meaning and owner. If one modification requires changing both, investigate whether a real common rule exists before extracting it.
How to recognize Modules that help explain the system
A useful Module has a brief explanation in business terms, brings together concepts you need to understand together, and offers a deliberate entry point to its consumers. Its boundaries appear in structure, imports, and tests.
Choose a concrete responsibility, define what it needs to offer, and review what knowledge can stay inside. That combination of cohesion and controlled dependencies makes code organization represent decisions, not just file locations.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.