Domain-Driven Design: Model-Driven Design, from business knowledge to code
Discover how a Domain Model guides code decisions and how it differs from a Data Model. Through TypeScript examples, learn to represent rules, recognize the responsibilities of DDD patterns, and give AI concrete criteria for implementing and reviewing changes.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
A store allows orders to be modified while they are being prepared. The backend has an orders table, a status field, and a function that updates any column. The dashboard works until someone changes the address of an order that has already left the warehouse.
The database accepts the change. The API responds successfully. The carrier, however, retains the old address. To support, the order appears headed to one place; to logistics, another.
A decision was missing from the model: after dispatch, changing an address is not an ordinary order edit. It requires a different procedure, if the business permits it.
The goal of Model-Driven Design is for important model decisions to have a recognizable expression in the software you run. To understand how it works, we will follow the connection between business rules and their implementation.
What it means for the model to guide design
A Domain Model selects concepts, relationships, and rules useful for solving a business problem. In Model-Driven Design, model and implementation develop together: what is learned changes the code, and programming experience allows the model to be revisited. Eric Evans presents this relationship in his DDD reference, Model-Driven Design section.
Drawing an order with lines and then programming an object that permits any modification is insufficient. If the model says a dispatched order cannot be canceled directly, the implementation must protect that restriction.
The Ubiquitous Language, the vocabulary shared with people who know the business, provides names and meanings. For example, “dispatch” may mean physically handing the package to the carrier, not merely generating a label. The Domain Model adds relationships and behavior: what an order can do, under which conditions, and with what result.
Nor is the model a perfect specification someone finishes before programming. It may start with three rules and evolve when an exception is discovered. What matters is correcting the explanation and implemented behavior together.
Domain Model and Data Model answer different questions
A Data Model describes how data are structured and related. In a relational database, it includes decisions such as tables, columns, keys, and constraints. A Domain Model addresses meaning and valid operations.
For our store, the Data Model could contain orders, order_lines, and shipping_address. The Domain Model must answer other questions: when can it be confirmed, what becomes fixed on confirmation, and when does cancellation stop being possible?
Both must collaborate. A uniqueness constraint or database transaction may be indispensable to uphold a rule. The difference is that knowing the columns does not, by itself, explain every business decision.
Nor do you need one class per table. An object may be composed from several tables, and a read query can return a simple structure without reconstructing all behavior. Representation depends on the operation you are solving.
The problem arises when all decisions are reduced to editing fields. Fowler calls a design presenting Domain objects but concentrating their behavior elsewhere an Anemic Domain Model. His pattern analysis distinguishes that situation from deliberately choosing a simpler solution for a simple problem.
Main example: an order with valid operations
Initial state: we can save data but cannot express intent
This partial snippet represents a solution centered on data structures. It is not a complete persistence implementation:
The type accepts known states but does not prevent incorrect transitions between them. It also permits replacing the items of an already confirmed order.
A controller could add checks. Then a scheduled task and an administrative import would need them too. The rule would end up depending on every entry point remembering to apply it.
The decision: represent the order lifecycle
For this example, we agree on four rules:
A new order is in draft, and only in that state can it receive items.
Confirmation requires at least one item and fixes its contents.
Dispatch requires the order to be confirmed.
Cancellation is allowed in draft or confirmed; after dispatch it requires another process and is rejected here.
These are decisions for this case, not universal commerce rules. We will not model charges, discounts, stock, or returns. Each item represents one unit of a product, and the same identifier may appear several times. This simplification avoids introducing quantities and prices we do not need to explain transitions.
The change: operations with rules instead of arbitrary changes
The following program is self-contained. Save it as model-driven-order.ts and run it with node model-driven-order.ts on Node.js 24.21.0. No external packages are required. Node can execute this TypeScript syntax by removing types, but does not perform static type checking during that execution.
import assert from'node:assert/strict';
typeOrderStatus = 'draft' | 'confirmed' | 'dispatched' | 'cancelled';
classOrder {
#id: string;
#status: OrderStatus = 'draft';
#items: string[] = [];
constructor(id: string) {
if (!id.trim()) thrownewError('El pedido necesita un identificador');
this.#id = id;
}
addItem(productId: string): void {
if (this.#status !== 'draft') {
thrownewError('Solo se puede modificar un pedido en preparación');
}
if (!productId.trim()) thrownewError('El producto necesita un identificador');
this.#items.push(productId);
}
confirm(): void {
if (this.#status !== 'draft') {
thrownewError('Solo se puede confirmar un pedido en preparación');
}
if (this.#items.length === 0) {
thrownewError('Un pedido vacío no puede confirmarse');
}
this.#status = 'confirmed';
}
dispatch(): void {
if (this.#status !== 'confirmed') {
thrownewError('Solo se puede despachar un pedido confirmado');
}
this.#status = 'dispatched';
}
cancel(): void {
if (this.#status !== 'draft' && this.#status !== 'confirmed') {
thrownewError('El pedido ya no admite cancelación directa');
}
this.#status = 'cancelled';
}
snapshot(): { id: string; status: OrderStatus; items: string[] } {
// Devuelve una copia para que una lectura no permita saltarse las reglas.return { id: this.#id, status: this.#status, items: [...this.#items] };
}
}
const empty = newOrder('order-empty');
assert.throws(() => empty.confirm(), /vacío/);
assert.throws(() => empty.dispatch(), /confirmado/);
assert.equal(empty.snapshot().status, 'draft');
const order = newOrder('order-1');
order.addItem('book');
order.confirm();
assert.throws(() => order.addItem('notebook'), /modificar/);
const externalCopy = order.snapshot();
externalCopy.items.push('unauthorized-item');
assert.deepEqual(order.snapshot().items, ['book']);
order.dispatch();
assert.throws(() => order.cancel(), /cancelación directa/);
assert.deepEqual(order.snapshot(), {
id: 'order-1', status: 'dispatched', items: ['book'],
});
const cancellable = newOrder('order-2');
cancellable.addItem('notebook');
cancellable.confirm();
cancellable.cancel();
assert.equal(cancellable.snapshot().status, 'cancelled');
assert.throws(() => cancellable.dispatch(), /confirmado/);
console.log('Reglas del ciclo del pedido verificadas');
Observable result: state no longer changes through any path
The first input is an empty order. Its confirmation attempt fails and it remains in draft. Then we work with an order containing book: it can be confirmed and dispatched, but accepts neither new items after confirmation nor direct cancellation after dispatch.
The program was run with Node.js 24.21.0 and completed the included assertions. Static checking with the TypeScript compiler was not performed.
The difference from updateOrder is concrete: the consumer requests an operation, and the model decides whether it is valid. Private fields prevent direct state modification; the read copy prevents changes to the internal array from outside.
An Invariant is a condition that must hold after every valid operation. In this model, a confirmed order is not empty and its contents remain fixed for the rest of its lifecycle. Assertions check both rejections and preservation of state when an operation fails.
The code uses a class because it shows identity, state, and behavior together. Model-Driven Design does not depend on that syntax: you can also express a model with functions and immutable types, provided its rules and relationships are preserved.
What is missing for use in a backend
A Use Case, the operation offered by the application, would coordinate loading the order, executing dispatch(), and saving the result. The Domain Model need not know HTTP or generate transport responses.
This example ends in memory. It does not include recovery from storage, authorization, or coordination of concurrent writes. Two processes could load the same state and make incompatible decisions if persistence does not detect the conflict. Version control or a transactional lock must be designed and tested in the real adapter.
Encapsulating a rule makes intent explicit; it does not replace the guarantees needed to uphold it when the system runs.
Second example: education and the meaning of a certificate
A platform stores progress = 100 and certificateUrl. One implementation interprets reaching one hundred percent as an instruction to create a certificate immediately.
Reviewing the process reveals another rule: finishing lessons allows taking the assessment; passing it enables certificate issuance. The consumption percentage represents neither decision on its own.
Here the change is not adding another state to the previous order. It is recognizing different concepts: progress, assessment result, and eligibility for certification. A small model could express this condition with a pure function, which calculates a result without modifying external state:
// Fragmento didáctico: recibe evidencias ya validadas y de la misma inscripción.functionisEligibleForCertificate(evidence: {
requiredLessonsCompleted: boolean;
finalAssessmentPassed: boolean;
}): boolean {
return evidence.requiredLessonsCompleted && evidence.finalAssessmentPassed;
}
The input “lessons finished, assessment not passed” produces false. With both pieces of evidence it produces true, but does not claim an issued document already exists. The model distinguishes an eligibility decision from the issuance operation.
This example teaches that a Domain Model can begin with a precise function. You need not turn every rule into a class hierarchy. You do need to ensure the evidence corresponds to the same enrollment and its current requirements; the function does not handle obtaining it.
Third example: an integration must not decide your model
A logistics company receives DELIVERED from the carrier. Its first adapter converts it to order.status = 'completed'. However, commercial closure of the order also requires reviewing a pending incident.
The external format describes a transport fact, not the complete business decision. The proposal is to translate it into “physical delivery confirmed” and let the internal model determine whether the order should close.
An Anticorruption Layer, or ACL, adapts external concepts to protect the consuming model. In this example, it can do so by querying HTTP and validating the response against a consumer-defined contract. Bounded Contexts, boundaries within which each model retains consistent meaning, keep their implementations separate, without imports between them.
The integration provides evidence; it does not require copying its states. Furthermore, querying HTTP and saving locally does not constitute a shared transaction: what happens upon failures and changes between the operations must be decided.
From this case, you can learn to distinguish exchange representation from internal meaning. Model-Driven Design also involves choosing which concepts must not enter the model directly.
DDD pieces and each one's responsibility
These patterns help express model decisions. They are not a mandatory component list. The following definitions summarize Evans's building blocks; the examples are instructional choices:
Entity: retains identity through changes. Order remains the same order when dispatched.
Value Object: is defined by its values. A monetary amount combines amount and currency, without requiring its own identity.
Aggregate: establishes a consistency boundary with an Aggregate Root controlling its changes. An order can protect its lines.
Domain Service: expresses a Domain operation that does not naturally fit an Entity or Value Object. For example, a policy comparing shipping options.
Domain Event: represents a relevant fact that occurred. OrderDispatched expresses dispatch, not a request for it.
Factory: concentrates complex creation and guarantees a valid result. It could build an order from an accepted quotation.
Repository: offers retrieval and saving of Aggregates without exposing storage details to the consumer.
These responsibilities let us choose which pieces each model needs. Order sufficed for the main example: adding empty Factories and Domain Services would have increased the path without representing new decisions. Nor does a Factory creating new objects necessarily replace rules for reconstructing historical objects from persistence.
How to know whether the model remains coherent
A model can have correct names and behave incorrectly. Look for correspondence among three elements: the agreed rule, the operation applying it, and the scenario checking it.
If the business says “after dispatch, a return must be managed,” ensure there is no administrative entry point directly changing state to cancelled. If a legitimate exception appears, modify the model to represent it instead of opening a generic door bypassing its rules.
Also review who coordinates and who decides. The Use Case can load data and save results; central rules should not be duplicated in every controller. At the same time, do not turn all data access into a complex operation: an order list may need a simple read query.
When a simpler solution is enough
An internal category catalog with a name and description may only need CRUD operations: create, read, update, and delete. Input validation, a small service, and database constraints can solve it clearly.
The data structure is not the problem. The problem is using it as a sufficient explanation when there are transition rules, exceptions, and decisions that do not fit “edit this record.”
Maintaining a model with behavior has costs: discovering rules, choosing boundaries, and reviewing tests when they change. Invest where decisions justify it. A Domain Model need not represent the whole organization or anticipate requirements that do not yet exist.
How to use the model to guide and review AI-generated code
A data schema lets you request generation of an API but leaves many decisions open. An explicit model adds valid operations, conditions, and counterexamples. That information enables evaluating the response beyond whether it compiles.
The following prompts apply to tools such as Cursor, Claude, or Codex. Share only authorized context and confirm the attached rules are current.
Analyze a field-centered design
Context: the order can be modified only in draft, confirmed if it has items, and dispatched only after confirmation. It is not canceled directly after dispatch. Analyze the attached code and locate paths allowing these rules to be bypassed. Do not edit files or invent payment policies. Return evidence, a scenario, and a minimal operation proposal. A person will validate exceptions with the business and check that the identified paths exist.
Implement a bounded model
Implement Order in TypeScript without frameworks or external packages. Express addItem, confirm, dispatch, and cancel with the attached rules. Avoid arbitrary state changes and return copies on reads. Do not add stock, payments, events, or persistence. Deliver self-contained code and assertions for an empty order, modification after confirmation, and cancellation after dispatch. A person will execute the example and verify that the rules represent the real process.
Review a model change
Requesting a return after dispatch is now permitted, but that is not equivalent to canceling or refunding. Review the attached proposal against the current model. Do not change files. Identify confusion between intent and fact, duplicated rules, and missing tests. Do not assume shared transactions over HTTP. Return open questions and observable cases. A person will decide which operation belongs to each Bounded Context and validate contracts.
AI can help detect contradictions. If implementation and tests repeat the same incorrect interpretation, both can agree while still failing the business. The model needs human scrutiny and behavioral evidence.
Three exercises with reasoned solutions
1. The address of a dispatched order
A proposal adds setAddress() and permits using it in any state. What would you review?
Reasoned solution: ask when the address becomes fixed and how a later change is requested. If it depends on the carrier after dispatch, overwriting a local field is insufficient. The operation should represent a request with a pending result or a rejection, according to the agreement. Check that updating the profile address does not rewrite the shipment's historical address either.
2. A certificate issued before passing
The AI proposes renaming progress to completionProgress but retains automatic issuance upon reaching one hundred. Does that solve the problem?
Reasoned solution: it does not change the decision. Separate consumption evidence, passing, and issuance. Add the case “all lessons completed and assessment failed”: under the example's rules, it must not enable the certificate. The name must accompany a correct rule.
3. A Factory without complex creation
The team proposes a Factory, a Domain Service, and a Repository for a category with a required name. How would you decide?
Reasoned solution: identify which real responsibility each piece needs. If creating the category only requires validating a name, a constructor or function may suffice. Persistence may justify its own separation, but does not automatically make creation complex. Introduce abstractions when they represent decisions and reduce concrete dependencies.
What to check before considering a model useful
You can recognize Model-Driven Design when important operations have shared meaning, their constraints appear in code, and scenarios exist to check them. Also when a business change requires consciously revisiting the model rather than accumulating exceptions around its fields.
Start with an operation with relevant rules. Express its inputs, conditions, and results; implement what is needed and check the behavior. That link between knowledge and code is what enables you to guide AI work and judge whether the solution represents the problem you need to solve.
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.