Domain-Driven Design: Entities—identity, behavior, and lifecycle
Learn to recognize an Entity by its identity and protect its evolution through business operations. Implement a complete TypeScript example, distinguish identity equality from reference equality, and use tests to review both your model and AI-generated code.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
Someone reports a problem to support. A ticket is created with the subject “I cannot sign in.” They later correct the text, an agent takes ownership, and finally records a resolution. The subject, assignee, and status change, but nobody considers it a different ticket.
Now imagine another ticket with exactly the same subject and assignee. It may concern a different incident. Comparing properties is not enough to decide whether we are discussing the same case.
That continuity is the starting point of an Entity: recognizing which one it is matters while it changes. The design task is deciding what identifies that continuity and which operations let it evolve validly.
An Entity is recognized by its identity
An Entity represents something whose identity must persist throughout its lifecycle even when its attributes change. Evans presents this distinction in the Entities section of his DDD reference.
Identity answers “is this the same ticket?” Its properties answer “what is it like now?” These are different questions.
An identifier such as ticket-42 can make the first answer explicit. But adding an id field to any structure does not demonstrate that the concept needs to be modeled as an Entity. The relevant question is whether the business needs to distinguish it from others and track its evolution.
You must also define identity's scope. If two organizations can each have ticket number 42, that number alone does not identify the case outside its organization. Consider the organization together with the number, or use another identifier unambiguous within the agreed scope.
The identifier need not be a business-visible property
A document may have a commercial reference; a shipment, a tracking code; a person, an email address. Some of those values can change or may not be unique in every scenario.
It is therefore useful to distinguish a stable identifier from changeable external references. Correcting a tracking code should not turn an existing shipment into another shipment.
You can generate identifiers using different strategies. Choosing a UUID or sequence is a technical decision; determining what preserves continuity is a model decision. No strategy replaces the uniqueness controls needed in the real system.
Equality by identity, reference, and state
In JavaScript, === compares references when operands are objects. Two different instances are not reference-equal even if they represent the same Entity.
An application can have a ticket in memory and reconstruct another instance from stored information. Both represent the same case if they preserve the agreed identity. Their attributes may even differ if one corresponds to an earlier read.
That is why we will implement sameIdentityAs(): its name expresses exactly what it compares. Returning true does not mean both instances contain the latest state or that either is safe to save.
This distinction matters when deduplicating results, comparing retrieved objects, or reviewing changes. Using the subject as identity would merge different tickets; using only the memory reference would separate two representations of the same ticket.
From a data structure to business operations
This partial snippet shows a class that stores data but does not protect its relationships:
classTicketData {
id = '';
subject = '';
status: 'open' | 'resolved' = 'open';
assigneeId: string | null = null;
resolution: string | null = null;
}
const ticket = newTicketData();
ticket.id = 'ticket-42';
ticket.status = 'resolved';
// No hay responsable ni explicación de la solución.
The type restricts allowed status words, but does not guarantee a resolved ticket has an assignee and explanation. A generic setter such as setStatus() can retain the same problem if it merely assigns the received value.
Fowler describes Anemic Domain Model as a design with objects that appear to represent the Domain but whose behavior is concentrated outside them. His analysis helps identify the cost of maintaining objects with identity and relationships without using them to express model decisions.
That does not make every data structure a mistake. A read response or form may need only data. The problem appears when an Entity that should protect rules depends on each controller or process remembering to apply them separately.
Complete example: a ticket's lifecycle
The rules we will implement
For this instructional case, we agree on the following:
A ticket is created open, without an assignee or resolution.
Only an open ticket allows changing the subject or assigning an owner.
Resolving requires an assignee and a nonempty explanation.
Reopening is valid only for a resolved ticket. It retains the assignee, removes the current resolution, and maintains identity.
A resolved ticket must have an assignee and resolution; an open ticket has no current resolution.
The last condition is an Invariant: a property that must hold after every valid operation. Reopening rules are decisions of this example, not a universal support policy.
The lifecycle is expressed as follows:
Creation -> open -> resolve(...) -> resolved
^ |
+------- reopen() -------+
Changing the subject and assigning an owner are allowed only in open.
The example stores only current state. Removing the resolution when reopening does not represent a history-deletion policy: an application needing auditing would also retain earlier resolutions through additional design.
The program
This block is self-contained. Save it as entities.ts and run it with node entities.ts on Node.js 24.21.0. It uses only one included Node.js module; no framework, ORM, or database is needed.
Direct execution uses type stripping, which removes TypeScript annotations but does not perform static type checking. The program validates data relevant to its rules at runtime.
Creation establishes a valid initial state. Operations use business verbs: assignTo, resolve, reopen. They do not allow submitting an arbitrary collection of properties to change everything at once.
The program was run with Node.js 24.21.0 and completed its included assertions. This check covers the shown scenarios; no static analysis with the TypeScript compiler was performed.
Each method checks its conditions before replacing the state. For example, an empty resolution produces an error without leaving the ticket partially resolved. Preserving state after rejection is part of what the assertions check.
The #state field is private at runtime. JavaScript's # syntax restricts access from outside the class, as MDN documents. It does not depend solely on TypeScript's static checks.
The Readonly type expresses a restriction to the type checker; it does not itself freeze the object at runtime. That is why snapshot() returns a copy. Here, all fields are primitive values and a shallow copy suffices. With arrays or nested objects, you would also need to review those references.
The test modifying view demonstrates that distinction: it changes an external representation but not the ticket's identity or internal state. Encapsulation protects object operations; it does not constitute authorization or a security boundary for the entire system.
Creation and reconstruction are not the same operation
create() starts an open ticket. restore() reconstructs an existing representation and preserves both identifier and state. Both paths validate the conditions accepted by the model.
In the example, we pass explicit identifiers to keep tests readable. In a real application, whoever assigns them must guarantee uniqueness within the defined scope. Reconstruction should not generate another identifier or rerun effects belonging to new creation.
restore() receives a known structure; it is not a complete arbitrary JSON parser. Code receiving external data must check its shape before invoking it. If a legacy system contains states incompatible with current rules, decide how to interpret or migrate them rather than silently skipping validation.
The two example instances represent the same ticket but contain different subjects. The previous read does not update itself. Saving two concurrent representations requires detecting write conflicts through additional mechanisms. sameIdentityAs() does not resolve them.
Another scenario: an enrollment preserves its history
An academy has a student and course. The initial proposal uses both identifiers as enrollment identity: “an enrollment is the student–course pair.”
That choice can be correct if the business allows only one enrollment forever. But if it permits repeating the course in another offering, the same pair identifies two different participations. The second may have different dates, grades, and conditions.
In that case, Enrollment needs to distinguish each participation. Changing the student's email should not change enrollment identity, and suspending it should not replace it with a new enrollment if the business considers it the same process.
This example teaches reviewing identity against the entire lifecycle, not just the registration screen. Ask about retries, renewals, reopenings, and new participations before choosing a composite key.
Commerce: Entity and Value Object are not chosen by field count
An order has a delivery address. Shipping that order may require only its values: street, number, and locality. Two addresses with the same components can be equivalent for that purpose. That is the perspective of a Value Object, defined by its values, as Evans distinguishes.
By contrast, an entry in the customer's address book may need identity: it is labeled, edited, and selected as a favorite over time. Even when its values change, the customer recognizes the same saved entry.
There is no contradiction. These are different responsibilities. The address agreed for an order can remain a copy of values while the address-book entry evolves separately. Editing the address book should not automatically rewrite where an earlier order was shipped.
This case teaches that a concept is not inherently an Entity in every model. Decide whether you need to track its continuity or merely represent a value for a particular operation.
An Entity is not a persistence record either
A Persistence Model organizes the representation needed to store and retrieve information. It may include column names, technical keys, or metadata not belonging to business behavior.
The Entity represents identity and valid operations. It can be reconstructed from stored data, but does not need to inherit an ORM class or receive a database connection to resolve a ticket.
Sharing some fields does not make the two models equivalent. Nor does it require maintaining two identical classes in every project: the specific separation depends on needs and accepted coupling. For learning and checking rules here, keeping the Entity independent avoids introducing details that do not participate in its decisions.
Its methods should not respond to HTTP or send emails either. A Use Case can coordinate the operation and necessary effects outside the Entity while keeping decisions concerning its state and rules inside.
When a simpler solution is sufficient
A temporary ticket-filtering form needs neither its own identity nor a controlled lifecycle. It can be a structure with optional fields. A read projection can be limited to id, subject, and status for displaying a list without business operations.
Even a record with identity and few rules may need very little behavior. Do not add states, inheritance, or a generic base class merely to make it look like a more sophisticated Entity.
Implementation depth should answer the problem. In our ticket, the relationship between assignee, resolution, and status justifies protecting changes. In a structure used only to transport data, those same methods would belong elsewhere.
How to guide and review AI-generated Entities
Asking “create a Ticket entity” leaves identity, states, and transitions undefined. A tool may deliver a class with getters and setters without resolving any of those decisions.
Provide identity scope, initial state, operations, preconditions, and rejection examples. Also indicate what the Entity must not do. These prompts are starting points for tools such as Cursor, Claude, or Codex; the responsible person must validate rules before turning them into code.
Analyzing identity
Context: an academy allows a student to repeat a course in different offerings. Analyze whether student–course identifies an enrollment or whether participations must be distinguished. Return alternatives, counterexamples, and open questions; do not implement or invent policies. A coordinator will verify which process retains continuity and when another begins.
Implementing behavior and rejections
Implement SupportTicket in TypeScript without dependencies. Identity does not change when modifying the subject or reopening. Resolving requires an assignee and nonempty resolution; reopening retains the assignee and removes the current resolution. Do not use generic setters, HTTP, ORM, or external effects. Provide self-contained code and assertions for identity equality, rejection without partial changes, and invalid reconstruction. A person will run tests and validate reopening and auditing policy.
Reviewing an existing proposal
Review this Entity against the attached rules. Look for mutable identity, attribute-based equality, exposed internal state, transitions without preconditions, and validations performed after mutation. Do not change files. Return evidence and an observable scenario for each finding; distinguish questions from errors. A person will also review concurrency, authorization, and persistence, which are not guaranteed by class encapsulation.
AI can generate tests repeating its own assumptions. Compare them with agreed scenarios: a test treating resolution without an assignee as valid does not protect this example's rule, even if it passes alongside the implementation.
Three exercises with reasoned solutions
1. Two reads of the same shipment
Two instances have the same shipment identifier, but one retains the earlier tracking code. Are they the same Entity? Can you save either?
Reasoned solution: they represent the same Entity if that identifier is stable and unique within the agreed scope. That does not guarantee the same state or freshness. Before saving, handle the potentially stale read; comparing identity does not prevent overwriting recent changes.
2. Resolving and assigning afterward
A proposal first changes status to resolved, then checks whether an assignee exists. If not, it throws an error. Which behavior must a test protect?
Reasoned solution: verify that rejection leaves the ticket open and preserves other data. Validation must happen before mutation, or the operation must construct and validate a new state before replacing the previous one. Throwing an exception does not itself undo assignments already made.
3. Reopening with another identifier
The team proposes implementing reopen() by calling create() with a new identifier. When would that be correct?
Reasoned solution: only if the business defines the action as opening a different case, perhaps related to the previous one. If reopening means continuing the same ticket, identity must be retained and its transition controlled. The name and behavior must express which process was agreed.
How to recognize a well-designed Entity
Look for a reason to track its continuity, a clear identity scope, and operations explaining how it can change. Check valid states, what happens when an operation fails, and whether an external read lets rules be bypassed.
A useful Entity preserves who it is while controlling how it evolves. That combination of identity, behavior, and lifecycle lets you review the model with concrete criteria, whether you wrote it yourself or used AI to implement it.
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.