Ubiquitous Language
"Translation blunts communication and makes knowledge crunching anemic." — Eric Evans, Domain-Driven Design Reference (2015), pattern "Ubiquitous Language"
Summary: A ubiquitous language is one rigorous vocabulary, owned by experts and developers together, used in speech, diagrams, code, tests, APIs and the UI of one bounded context; when the words change, the model changes, and the code is renamed to match. Focus: Definition and scope (one context, not the whole company), why translation kills models, building the language (glossary, knowledge crunching, ambiguity listening, past-tense events, verbs vs nouns), the same word in three contexts, evolving and versioning the glossary, the language in code, tests, APIs, UI, database and tooling, multilingual teams (Persian business language, English code), smells, measuring, and renames of a real feature in Go and Laravel. Learning goal: Given a feature written in developer words, produce the glossary entries, rename packages, types, events, routes, tables and tests into the language of the business, write the Gherkin and Pest/Go tests that express it, and defend the result with a glossary-linting test.
This chapter belongs to group DD 01 (Strategic Design). It assumes you know what a domain and its subdomains are (Domains & Subdomains). It owns the words: where they come from, where they are valid, how they appear in code. The neighbours own the rest: where the language stops (Bounded Context), how two languages meet (Context Maps & Integration Patterns), the workshop that discovers events (Event Storming), the building blocks that carry the words (Entities & Value Objects, Domain Events vs Integration Events), and the service-level consequences (Service Boundaries, Data Ownership).
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why one shared language beats two dialects | Why a shared language exists |
| Evans, Fowler, Vernon, Brandolini, Khononov | Where it comes from |
| The definition and its five channels | What it is |
| "Customer" meaning five things | Why translation kills models |
| Glossary, knowledge crunching, listening for ambiguity | Building the language |
| Past-tense events, verbs vs nouns | Events and verbs |
| Order in Sales, Fulfilment and Billing | One word, three contexts |
| Words change; versioned glossaries | Evolving the language |
| Class, package, table, event names | Language in code |
| Gherkin, Pest, Go table tests | Language in tests |
| Routes, errors, enums, UI texts | Language in APIs and UI |
| Legacy schema, ACL pointer | Language in the database |
| Slack, tickets, diagrams, glossary page | Conversations and tooling |
| Persian business language, English code | Multilingual teams |
| Synonyms, jargon leaks, passive voice | Smells |
| New-hire test, glossary coverage | Measuring |
| Before/after renames in Go and Laravel | Go, Laravel |
| Monolith to distributed | In architecture |
| Hands-on | Lab |
| Wrong beliefs, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked in the concept catalogue.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Ubiquitous language | One vocabulary shared by experts and developers, used everywhere in one context | "A customer cancels an Order" is the sentence, the method and the test name | Experts say one thing, code says another, bugs live in the gap |
| Domain expert | The person who knows the business rules by doing the work | A warehouse supervisor, a support lead | Developers invent rules from guesses |
| Knowledge crunching | Experts and developers digest raw information into a model, by conversation | A two-hour session that ends with a cleaner glossary | Requirements arrive as documents, understanding does not |
| Glossary | The written list of terms, meanings and forbidden synonyms | Order: the customer's commitment to buy | Every new hire re-learns words from code archaeology |
| Model-driven design | Code literally follows the model, so names match | Order.cancel() exists because Sales says "cancel" | A deadly divide between analysis and design |
| Bounded context | The area where one word has one meaning | "Order" in Sales | One word, five meanings in one codebase |
| Domain event | Something that happened, named in the past tense | OrderPlaced | Events named OrderUpdated that nobody can interpret |
| Anticorruption layer | A translator at the edge between two languages | Billing turns OrderPlaced into ChargeRequest | One context's words leak into another |
Where the language lives (details in Language in code and following):
| Channel | What the language looks like there | Wrong version | Right version |
|---|---|---|---|
| Speech | Experts and developers use the same nouns and verbs | "the status flag" | "the order is cancelled" |
| Code | Types, packages, methods, events | OrderManager.ProcessOrder | sales.Place, Order.Cancel |
| Tests | Test names read as business rules | testUpdateStatus3 | "a dispatched order cannot be cancelled" |
| API | Resources and verbs from the glossary | POST /order/update-status | POST /orders/{id}/cancellation |
| UI and errors | Same words, same spelling | "Error 409" | "The order is already dispatched" |
| Database | Table and column names, or a mapping layer | tbl_ord.st = 2 | orders.state = 'cancelled' |
| Tooling | Tickets, chat, diagrams | "fix the thing in the order flow" | "customers cannot cancel after dispatch" |
The language is scoped (details in One word, three contexts):
| Word | Sales | Fulfilment | Billing |
|---|---|---|---|
| Order | The customer's commitment to buy | A work order: lines to pick and pack | The billable basis of an Invoice |
| Product | (Catalog: a listed offer with price and description) | (Warehouse: a SKU with a location and weight) | A tax category and a unit price |
| Customer | The person who places Orders | The recipient on the parcel label | The payer on the Invoice |
| Status | Placed, cancelled, dispatched | Released, picking, packed, dispatched | Draft, issued, settled |
Smell → fix (details in Smells):
| Smell | Symptom | Fix |
|---|---|---|
| Synonyms | Order, Purchase, Sale, Transaction in one context | Pick one in the glossary, rename the others |
| Jargon leak | OrderManager, OrderHelper, OrderData | Name the business role or the verb |
| System as actor | "The system updates the order" | Name the actor: "support cancels the order" |
| Developer corrects expert | "You mean an entity with a FK" | Learn the expert's word, adjust the model |
Why a shared language exists
Software is a translation of business knowledge into code. Every translation step loses detail. A single shared vocabulary removes the steps that can be removed, so the knowledge that survives is the knowledge that the people who know it can still read.
| Two dialects (translation) | One language (ubiquitous) |
|---|---|
| Experts speak business, developers speak design | Both speak the model |
| Meetings produce notes, notes produce tickets, tickets produce code | Meetings produce a refined model, which is the code's structure |
| Bugs come from mismatched meaning | Bugs come from wrong rules, found by reading aloud |
| New hires ask two people | New hires read one glossary and the code |
| Analysis and design drift apart | Analysis is design (Evans: "a deadly divide opens between analysis and design") |
The everyday analogy. A hospital where doctors, nurses and the billing office each call the same procedure by a different name. Every handover is a translation, and the wrong drug sometimes gets given. A ward that agrees on one name for each procedure, and writes it on the chart, still has disagreements, but they are visible disagreements.
Three common misunderstandings, up front
- "It is a company-wide dictionary." It is scoped to one bounded context. A company-wide vocabulary does not exist and forcing one creates the five-meaning Customer (scoped).
- "Developers should learn the business words, and that is it." The direction is both ways: experts also refine their words when the model shows ambiguity, and developers must refuse words the code cannot support.
- "It is a naming convention." A naming convention is a style rule. A language is a model: a change in the language is a change in the model, with behaviour, tests and data to change.
Where it comes from
| Year | Source | What it contributed |
|---|---|---|
| 2003 | Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of Software | Names the pattern, ties it to the model, Model-Driven Design, hands-on modelers, knowledge crunching |
| 2006 | Martin Fowler, bliki "Ubiquitous Language" (31 October 2006) | Short summary: the common, rigorous language between developers and users, which "software doesn't cope well with ambiguity" |
| 2013 | Vaughn Vernon, Implementing Domain-Driven Design (chapters 1–2) | Language within a bounded context; teams, context; secondary source here (not fetched) |
| 2013 | Alberto Brandolini starts EventStorming | Experts and developers share a wall of past-tense events; language emerges visibly (see Event Storming) |
| 2015 | Evans, DDD Reference (free PDF) | Concise pattern text: the quotes on this page |
| 2021 | Vlad Khononov, Learning Domain-Driven Design | A ubiquitous language per bounded context; the language as the context's boundary signal (secondary source here, not fetched) |
Primary quotes read for this page (saved text, see References). Evans, DDD Reference: "A language structured around the domain model and used by all team members within a bounded context to connect all the activities of the team with the software." Fowler: "Evans makes clear that using the ubiquitous language in conversations with domain experts is an important part of testing it, and hence the domain model." The Evans text also says: "Recognize that a change in the language is a change to the model."
What it is
The Reference gives the compact definition: a language structured around the domain model, used by all team members, within a bounded context, to connect all activities with the software. Unpacked:
| Part of the definition | Meaning | Consequence |
|---|---|---|
| Structured around the domain model | Words are the model's concepts, not UI labels or table names | The model gets tested every time someone speaks |
| Used by all team members | Experts, developers, testers, product, support | Nobody is allowed a private dialect |
| Within a bounded context | Valid inside one context only | Another context may use the same word differently |
| To connect all the activities with the software | Speech, writing, diagrams, code, tests | If code and speech differ, one of them is wrong |
The five channels the language must pass through: speech, documents and diagrams, code, tests, and the user interface. A sixth, data, is included when the team owns the schema.
The concept catalogue
Why translation kills models Must-know
In plain words: When business people say one thing and the code says another, someone has to translate in every conversation, and the translation always drops the subtle part. After a year, nobody remembers what the code names meant.
Common misunderstanding: "Developers can keep technical names; the team just remembers the mapping." The mapping lives in heads. It is lost when people leave, and meanwhile every sentence about the system costs a translation.
Definition: Translation between the experts' jargon and the developers' design language is a cost paid on every message and a lossy transform on every concept, so the model degrades (Evans: "Translation blunts communication and makes knowledge crunching anemic").
# Translation chain: one rule, four dialects, one bug
1 Expert says -> "Once the parcel is out the door the customer can't cancel, only return."
2 Analyst writes -> "Cancel allowed if status < 3"
3 Developer codes-> if ($order->st < 2) { $order->flag = true; }
4 Tester checks -> "status 2 + cancel => 409"
5 Support hears -> "customers can't cancel after shipping"
# st=2 was cancelled in the legacy table, not dispatched: the rule is inverted for 6 weeksReal scenario: "Customer" meaning five things. In a single online shop codebase:
| Who says "Customer" | They mean | Which table | Which rules |
|---|---|---|---|
| Marketing | Anyone who ever gave an email | contacts | No order needed, GDPR consent |
| Sales | The person who places an Order | customers | Credit limit, loyalty tier |
| Billing | The legal entity that pays the Invoice | accounts | VAT id, payment terms |
| Support | The person on the phone, may be a relative | callers | Verification questions |
| Fulfilment | The recipient on the parcel label | recipients | Delivery address, door code |
One Customer class with 60 columns and if ($type === ...) is the result of "we must have one Customer". The language approach: each context names its own concept (Customer, Payer, Recipient) and a translator maps identity between them (Context Maps).
What prevents it:
| Practice | Effect |
|---|---|
| One glossary per context | The five meanings stop sharing a name |
| Experts review code names and test names | Wrong words are caught while cheap |
| Model-driven design | No separate "analysis model" to translate from |
| Anticorruption layer at the border | Translation moves to one explicit place |
Fix / how to use it: see Go and Laravel.
Building the language Must-know
In plain words: You do not invent the language, you dig it out of conversations with experts, test it by speaking it, and write it down.
Common misunderstanding: "The architect defines the glossary and the team follows." A glossary written by developers alone is a developer dialect with business-looking words.
Definition: Building the language is the loop of knowledge crunching, glossary writing, speaking scenarios aloud and renaming code, until the sentences flow. Evans: "Play with the model as you talk about the system. Describe scenarios out loud using the elements and interactions of the model."
# One knowledge-crunching session (90 minutes), Sales context
1 Dev -> "When a user submits the cart we create an order record."
2 Expert-> "A shopper doesn't create an order. They place it. Before that it's a basket."
3 Dev -> "So Basket and Order are different things?"
4 Expert-> "Yes. A basket can be abandoned. An order is a commitment: we owe them goods."
5 Dev -> "What if they change their mind?"
6 Expert-> "Before dispatch they cancel. After, they return."
7 Dev -> "So cancel and return are different commands, with different events."
8 Output-> Glossary: Basket, Order, place, cancel, return; events OrderPlaced, OrderCancelledReal scenarios: workshop for a new product; support-ticket review (what words do customers and agents use?); code review where an expert reads the test names; Event Storming (Event Storming); a quarterly glossary review.
| Technique | What you do | What you get |
|---|---|---|
| Knowledge-crunching session | Talk through concrete scenarios with an expert | Terms, rules, edge cases |
| Listening for ambiguity | Note every word the expert uses in two ways, or two words for one thing | Candidates for a split or a synonym ban |
| Glossary | One page: term, meaning, example, avoid-list | A shared reference |
| Event Storming | Orange stickies in the past tense on a wall | The verbs and events of the process |
| Example mapping / Gherkin | Rules and examples on cards, then formulated in Given/When/Then | Language tested on real examples |
| Code reading with experts | Show them class names and test names | Instant feedback on misfits |
Fix / how to use it: the glossary data structure and the test that binds it to code are in Go; the Gherkin version is in Language in tests.
Events and verbs Must-know
In plain words: Name the things that happened in the past tense (OrderPlaced), and name the things people do as verbs (place, cancel). Nouns hold state, verbs carry business meaning.
Common misunderstanding: "OrderUpdated is a fine, generic event." It tells nobody what happened. A consumer must diff fields to guess the reason.
Definition: A domain event is a record of something that happened that the business cares about, named in the past tense with the glossary's words. A command is a verb in the imperative that expresses an intention (CancelOrder). Queries and state names are nouns and adjectives (cancelled, dispatched).
| Concept | Grammar | Sales example | Anti-pattern |
|---|---|---|---|
| Command | Imperative verb | PlaceOrder, CancelOrder | SaveOrder, UpdateOrder |
| Event | Past tense | OrderPlaced, OrderCancelled | OrderUpdated, OrderStatusChanged |
| State | Adjective or participle | placed, cancelled, dispatched | status = 3 |
| Rule | A sentence with "only if" | "An order can be cancelled only before dispatch" | if ($s < 2) without a name |
| Role | Noun for who acts | Customer, Support agent | "the user", "the system" |
# Verbs vs CRUD for the same business moment
1 CRUD : PUT /orders/42 {"status": "cancelled"} -> OrderUpdated {status: cancelled}
2 Language: POST /orders/42/cancellation {"reason": "changed my mind"} -> OrderCancelled {reason}
3 Difference: step 2 carries the rule (only before dispatch), the reason, and a name a human can sayReal scenario: Support asks "show me all orders cancelled this week with reason 'late delivery'". With OrderUpdated, the reason is archaeology; with OrderCancelled it is a column. See Domain Events vs Integration Events for event design and Message Design & Schema Evolution for versions.
One word, three contexts Must-know
In plain words: The same word may legitimately mean different things in different parts of the business. The fix is to draw a line around each meaning, not to force one meaning on everyone.
Common misunderstanding: "If two teams use the same word differently, one of them is wrong." Both can be right inside their own context. They are wrong only if they pretend to share a model.
Definition: Evans: "Statements about a model can only be understood in a context." A bounded context is the boundary within which a particular model and its language apply (Bounded Context). The ubiquitous language is ubiquitous within that boundary, not across it.
Running example, same word, three meanings (see the diagram):
| Word | Sales | Fulfilment | Billing |
|---|---|---|---|
| Order | Customer's commitment to buy; placed, cancelled, dispatched | Work order: PickLines to pick, pack, dispatch as a Parcel | Billable basis: amount, payer, tax treatment |
| Identity of an Order | OrderID assigned at placement | OrderID of the work order, linked to a Sales reference | Invoice number, with a reference to the Sales order |
| Cancel | Withdraw before dispatch | Stop picking, release stock | Void the Invoice or issue a credit note |
| Status | placed, cancelled, dispatched | released, picking, packed, dispatched | draft, issued, settled, voided |
| Customer | The person who places Orders | The recipient on the parcel label | The payer on the Invoice |
| Owner team | Sales squad | Warehouse squad | Finance squad |
A second pair, the "Product" word:
| Word | Catalog | Warehouse (Fulfilment) |
|---|---|---|
| Product | A listed offer: name, description, price, images | Not used; the term is SKU |
| SKU | The variant a shopper can choose | A stocked unit with location, weight, dimensions |
| Price | Public list price | Not known to the warehouse |
| Availability | "In stock" label for shoppers | Quantity per location, reserved vs free |
Rule of thumb: when a word needs an adjective to be understood ("billing order", "work order"), you are looking at two contexts. Do not fix it with a global name like GenericOrder. Let each context keep its short word, and give the integration its own published language (Context Maps & Integration Patterns).
| Option | When | Cost |
|---|---|---|
One shared Order class for all three | Never as a default | Contradictory fields, merge conflicts between teams |
Separate Order per context, same word | Contexts are really different | Needs a translator and a glossary per context |
Different words per context (Order, PickList, BillableOrder) | When the shared word keeps causing mistakes | Experts may resist; check with them |
Evolving the language Important
In plain words: The business changes its words, and so must the code. A language that is frozen is a language that is slowly becoming wrong.
Common misunderstanding: "Renaming is cosmetic and risky; leave it." Leaving a wrong name is the risky choice: it creates a permanent translation layer in everyone's head.
Definition: Evans: "Recognize that a change in the language is a change to the model. ... Then refactor the code, renaming classes, methods, and modules to conform to the new model." Evolving means: agree the new word, update the glossary version, rename code and data, keep wire compatibility with a period of overlap, retire the old word.
# Renaming "Client" to "Customer" across a running system
1 Week 1 Workshop agrees: Customer. Glossary v1.3 drafted, Client marked "avoid".
2 Week 1 PR 1: code rename (types, methods, tests); behaviour unchanged.
3 Week 2 PR 2: DB expand: add column customer_id, copy from client_id, dual-write.
4 Week 3 PR 3: API: accept both client_id and customer_id; emit customer_id; deprecation header.
5 Week 6 PR 4: events: OrderPlaced v2 carries customerId; v1 still published.
6 Week 10 PR 5: contract: drop client_id, stop v1; glossary marks Client "retired".| Change | What to do | Migration care |
|---|---|---|
| Pure rename of a word | Rename in code and glossary in one PR | None for internals; API and events need overlap |
| A word splits in two meanings | New term, new type, migrate data per meaning | Often a context split (Bounded Context) |
| Two words merge | Choose one, alias the other in the glossary as "avoid" | Update events with a new version |
| New concept appears | Add term, owner, example, first-used version | Announce in the team channel |
| Concept disappears | Mark retired with a date; remove after consumers move | Keep old events replayable |
Versioning the glossary. Put the glossary in the repo (docs/glossary/sales.md or a Go/PHP data file), give it a version number and a changelog, and change it in the same pull request as the code. The version of a published event or API names the language it was written in (sales.order.placed.v1). Database renames follow the zero-downtime expand/contract steps in Zero-Downtime Schema Migrations.
Language in code Must-know
In plain words: If a business person reads your class and package names, they should recognise their own business.
Common misunderstanding: "Good code uses generic technical names for flexibility (Manager, Handler, Data)." Generic names hide what the code is for and attract unrelated logic.
Definition: Model-driven design: "Design a portion of the software system to reflect the domain model in a very literal way, so that mapping is obvious." Class, package, table, endpoint and event names mirror the language, and the domain layer carries no technical jargon.
| Artefact | Mirror the language | Avoid | Notes |
|---|---|---|---|
| Go package | sales, fulfilment, billing | util, common, models, types | Code Review Comments: "Avoid meaningless package names like util, common, misc, api, types, and interfaces" |
| Go type | sales.Order, OrderPlaced | OrderData, OrderInfo, OrderDTO in the domain | Package name is part of the name: sales.Order, not sales.SalesOrder |
| Go constructor | sales.Place(...) | sales.NewOrder(...) when the business verb exists | Business verbs beat New when they carry rules |
| Go method | order.Cancel(reason) | order.SetStatus(3) | No Get prefix needed (Effective Go) |
| PHP namespace | App\Modules\Sales\Domain | App\Services, App\Helpers | PSR-4 autoload follows the namespace |
| PHP class | Order, OrderPlaced, OrderAlreadyDispatched | OrderManager, OrderHelper | PSR-12: class names in StudlyCaps (PascalCase) |
| Eloquent model | OrderRecord in a persistence namespace when the domain differs | One Order model doing domain, SQL and JSON | See Data Persistence in Design |
| Event | OrderPlaced, sales.order.placed.v1 | OrderEvent, OrderUpdated | Past tense, context-prefixed on the wire |
| Table | orders, order_lines | tbl_ord, t_data | If legacy, map in one layer (database) |
| Enum value | placed, cancelled, dispatched | 1, 2, 3 | Values appear in logs and UI; make them words |
| Exception / error | OrderAlreadyDispatched | InvalidStateException | The class name is the glossary entry |
Banned technical words in the domain layer (examples, team may extend): Manager, Helper, Util, Data, Info, Processor, Handler, Service without a business noun. These can live in the application and infrastructure layers where the language is technical (Domain, Application & Infrastructure Services). An application service named after a business use case (CancelOrder) is fine; OrderService is a smell.
The related object-modelling basics are in OOP Modeling; anemic models (setters only) lose the verbs in Anemic vs Rich Domain Models.
Language in tests Must-know
In plain words: A test name is a sentence about the business. If an expert can read the list of test names and nod, the tests are documentation.
Common misunderstanding: "BDD means installing Cucumber." BDD is the practice of discovering, formulating and automating examples; the tools are optional. The Cucumber docs say BDD closes the gap between business and technical people through collaboration, concrete examples, and "system documentation that is automatically checked against the system's behaviour".
Definition: Executable specifications in the domain language: Gherkin Feature/Rule/Example with Given/When/Then; Pest describe/it; Go table tests with sentence-like names. The Cucumber BDD guide: by writing the executable specification collaboratively "we establish a shared language for talking about the system. This helps us to use problem-domain terminology all the way down into the code."
Feature: Cancel an order
A customer may withdraw an Order until the warehouse dispatches the parcel.
Rule: An Order can be cancelled only before it is dispatched
Example: A placed Order is cancelled
Given Alice has placed an Order for 2 copies of "BK-1"
When Alice cancels the Order because "changed my mind"
Then the Order is cancelled
And OrderCancelled is recorded
Example: A dispatched Order cannot be cancelled
Given Alice has placed an Order for 1 copy of "BK-1"
And Fulfilment has dispatched the parcel
When Alice tries to cancel the Order
Then she is told "the order is already dispatched; request a return instead"| Test layer | Domain-language form | Example |
|---|---|---|
| Acceptance | Gherkin Feature, Rule, Example, steps Given/When/Then | the feature above |
| Unit (PHP) | Pest describe('Order') with it('cannot be cancelled once it is dispatched') | Laravel |
| Unit (Go) | Test function names as sentences; table-test name fields as business statements | TestCustomerCanCancelAnOrderBeforeItIsDispatched |
| Architecture | Rules in language terms: "the domain layer has no jargon names" | Pest arch(), Go go/parser test |
| Contract | The field names of the published language | Service Boundaries |
Gherkin facts from the reference: the primary keywords are Feature, Rule, Example (or Scenario), Given/When/Then/And/But, Background, Scenario Outline and Examples; free-text descriptions under Feature are "available for reporting"; "Given steps are used to describe the initial context of the system", and you should "avoid talking about user interaction in Given's". Each .feature file can hold a single Feature.
A step that mentions "click the blue button" or "POST /order/update" is leaking the UI or API into the language; push it down into step definitions.
Language in APIs and UI Important
In plain words: The words in the URL, the JSON field, the error message and the button should be the same words the support agent says on the phone.
Common misunderstanding: "API names are technical, the UI is where wording matters." Integrators and the support team read API names too, and error texts end up in customer emails.
Definition: Resource names are glossary nouns, state-changing operations are glossary verbs (as sub-resources or action endpoints), enum values are words, and error messages are sentences from the language. See API Realization for REST and GraphQL mechanics.
| Surface | Developer-word version | Language version |
|---|---|---|
| Resource | POST /order/process | POST /orders (place) |
| Operation | PUT /orders/42 {"status":3} | POST /orders/42/cancellation |
| JSON field | st, flag, cust | state, customerId |
| Enum | 1,2,3 | "placed", "cancelled", "dispatched" |
| Error code | ERR_409_STATE | order_already_dispatched |
| Error text | "Invalid state transition" | "The order is already dispatched; request a return instead." |
| Button | "Submit" | "Place order" |
| Event name | order.updated | sales.order.cancelled.v1 |
| GraphQL | mutation updateOrder | mutation cancelOrder(orderId, reason) |
Language in the database Important
In plain words: Ideally the tables use the same words. When they do not (a legacy schema), draw a line: the mismatch lives in one mapping layer and never leaks into the domain.
Common misunderstanding: "The schema is the model." The schema is one persistence of the model. The language drives the model; the schema serves it (Data Persistence in Design, Repositories).
Definition: For a greenfield schema, table and column names are glossary terms. For a legacy schema, wrap it with a view, a persistence model or an anticorruption layer so the domain code sees clean words.
-- Legacy tables: tbl_ord(ord_id, cust_no, st, dt_c) and tbl_ord_it(ord_id, sku_cd, q)
-- A translation view per context keeps the mismatch in one place (PostgreSQL syntax).
CREATE SCHEMA IF NOT EXISTS sales;
CREATE VIEW sales.orders AS
SELECT o.ord_id AS order_id,
o.cust_no AS customer_id,
CASE o.st WHEN 0 THEN 'placed' WHEN 1 THEN 'dispatched' WHEN 2 THEN 'cancelled' END AS state,
o.dt_c AS placed_at
FROM tbl_ord o;
CREATE VIEW sales.order_lines AS
SELECT i.ord_id AS order_id, i.sku_cd AS sku, i.q AS quantity FROM tbl_ord_it i;
-- Greenfield alternative: say it in the table
CREATE TABLE sales.orders_v2 (
order_id uuid PRIMARY KEY,
customer_id uuid NOT NULL,
state text NOT NULL CHECK (state IN ('placed', 'cancelled', 'dispatched')),
placed_at timestamptz NOT NULL
);| Situation | Approach | Where the mismatch lives |
|---|---|---|
| Greenfield | Name tables and columns from the glossary | Nowhere |
| Legacy, writable | Persistence model (Eloquent OrderRecord, Go repository) | One class or package per aggregate |
| Legacy, shared with another system | Anticorruption layer; views for reads | The ACL (Context Maps) |
| Data warehouse | Dimension names follow the reporting context's language | ETL |
| Microservices | Database per service, names are the service's own (Data Ownership) | Nowhere across services |
Also see Schema Design for column naming mechanics.
Conversations and tooling Important
In plain words: The language should be visible where work happens: tickets, chat, diagrams, pull requests and a glossary page in the repo.
Common misunderstanding: "The glossary is a wiki page for onboarding." A glossary nobody updates is just a poster. Treat it like code: version it, review it, test it.
| Place | Practice |
|---|---|
| Tickets | Titles are in domain sentences ("Customers cannot cancel after dispatch"), not "Fix status bug" |
| Slack / chat | A pinned glossary link; correct the word, not the person; use the thread to propose a new term |
| Diagrams | Boxes use glossary words only; label arrows with verbs or events |
| Pull requests | Template question: "Did a word change? Did you update the glossary?" |
| Docs in repo | docs/glossary/<context>.md next to the code, or a Go/PHP data file used by a test |
| Event catalogue | Each event lists its context, glossary term and version |
| Onboarding | The new hire's first task is to read the glossary and rewrite one confusing name |
| Meetings | The expert reads test names aloud; mismatches become tasks |
# Glossary change flow
1 Developer or expert proposes a term in the pull request or a thread
2 Expert reviews the meaning and the avoid-list
3 Glossary file changes in the same pull request as the code rename
4 The glossary test (names in code vs terms in file) passes
5 Merge; announce in the team channel with the version numberMultilingual teams: Persian business language, English code Important
In plain words: In a Persian-speaking business with an English codebase, you have two languages for each concept. The ubiquitous language still needs one meaning per concept, so you keep one glossary with both words and never mix them in code.
Common misunderstanding: "We can mix: Persian transliteration in variable names is faster." Mixing creates synonyms (sefaresh, order, request) and inconsistent spellings (sefaresh, sefareš, sefarsh), and it breaks searching.
Definition: A bilingual glossary maps each business term in Persian to exactly one English identifier. Conversations use the Persian term; code, tests, APIs and events use the English identifier. The mapping is the contract.
| Persian term | English identifier | Meaning (Sales) | Avoid |
|---|---|---|---|
| سفارش | Order | The customer's commitment to buy | Request, Purchase, Sefaresh |
| مشتری | Customer | A person who can place Orders | User, Client, Moshtari |
| ثبت سفارش | place / OrderPlaced | The moment of commitment | create, submit |
| لغو سفارش | cancel / OrderCancelled | Withdraw before dispatch | delete, remove |
| ارسال | dispatch / ParcelDispatched | The parcel leaves the warehouse | send, ship (if Fulfilment prefers dispatch) |
| فاکتور | Invoice | Legal document asking for payment | Bill, Receipt |
| Strategy | When | Pros | Cons |
|---|---|---|---|
| Translate to English identifiers, keep a bilingual glossary | Default for most teams | Searchable, readable by any developer, one spelling | Needs care for terms with no clean English equivalent |
Transliterate (sefaresh) | A term truly has no English counterpart and is an official legal word | Faithful to the law or regulation | Spelling variance; keep as a single constant, define it in the glossary |
| Persian identifiers | Rare, not recommended | Closest to the business | Tooling, review and package ecosystems assume ASCII |
| Mixed (Persian in some places, English in others) | Never | None | Synonyms, search failure, confusion |
Rules: (1) the glossary holds persian, english, meaning, avoid; (2) UI strings, error messages and reports for end users use the Persian term from the glossary, so Persian text lives in translation files, not in identifiers; (3) code comments are English only; (4) when an English word has two plausible Persian terms, the Persian side gets the second glossary row, so experts are consistent; (5) dates, numbers and the calendar (Jalali vs Gregorian) are part of the language: name which calendar a field uses (placed_at in UTC, rendered in Jalali by the UI).
Smells Important
In plain words: Smells are signals that the language is leaking or fragmented.
Common misunderstanding: "Smells are style issues." They predict real defects: wrong rule implemented, wrong report, wrong event consumed.
| Smell | How you notice | Cost | Fix |
|---|---|---|---|
| Synonyms | Order, Purchase, Sale, Transaction appear in the same context | Reviewers assume different concepts | Pick one in the glossary; rename; add avoid-list |
| Technical names in the domain | OrderManager, OrderHelper, OrderData, OrderDTO | Responsibilities leak in, nobody knows where rules live | Name the business role or the verb; move jargon to infrastructure |
| "The system does X" | Requirements say "the system updates the status" | Hides the actor and the rule | Name the actor: "support cancels the order" |
| Developers correct experts with jargon | "You mean a one-to-many with a foreign key" | The expert stops talking | Learn the expert's word; model it |
| One word, two meanings in one context | Order means commitment and invoice basis | Bugs at the seams | Split the context or the word (scoped) |
| Status ints and booleans | status = 3, flag = true | Lost rules, magic numbers | Named states, methods, events |
| CRUD verbs | updateOrder, saveOrder | No business intention captured | Business verbs and events |
| The glossary says X, code says Y | Glossary test fails | Drift | Rename code or fix glossary in the same PR |
| Names only developers understand | Expert cannot read test names | Tests do not document | Rewrite names as sentences |
| Translating in meetings | "In the code we call it..." | The knowledge crunch is anemic | Rename the code |
Measuring Good to know
In plain words: You cannot measure language with one number, but you can ask three honest questions.
Common misunderstanding: "If the glossary exists we are done." Existence is not use.
| Measure | How | Healthy sign |
|---|---|---|
| New-hire comprehension | Give a new hire the glossary and one module; ask them to explain a rule aloud to an expert | They use the same words without hints |
| Glossary coverage | A test lists exported domain types and checks each is in the glossary | 100 percent of domain types, zero banned suffixes |
| Expert readability | An expert reads test names and event names | Few corrections per session |
| Synonym count | Search the codebase for avoid-list words | Zero in the domain layer |
| Renames per quarter | Count merged renames driven by business words | Non-zero means the language is alive |
| Ticket titles in domain words | Sample 20 ticket titles | Most mention a glossary term |
| Translation incidents | Bugs traced to wrong word | Trending down |
Mechanics
The glossary as data Must-know
A glossary entry has a fixed shape so tools can check it.
| Field | Purpose | Example |
|---|---|---|
| context | Which bounded context this meaning is valid in | sales |
| term | The identifier-level word | Order |
| persian | The business term for bilingual teams | سفارش |
| meaning | One sentence, no jargon | The customer's commitment to buy |
| avoid | Banned synonyms | Purchase, Transaction |
| example | A sentence using it | "Alice placed an Order for two books." |
| since | Glossary version that introduced it | 1.0 |
| owner | Who answers questions about it | Sales product owner |
Linting the language Important
| Check | Go implementation | PHP implementation |
|---|---|---|
| No banned suffixes in the domain package | go/parser walks identifiers (the test in Go) | Pest arch()->not->toHaveSuffix('Manager') |
| Every exported domain type is in the glossary | A test compares AST type names with the glossary data | A Pest test reflecting classes in the Domain namespace |
| No import from another context's domain | go/parser imports test (Service Boundaries) | Pest arch() not->toUse |
| Events end in past tense | Regex or a list of allowed suffixes (ed, Placed) | Same, via a Pest dataset |
No Util/Common packages | Directory listing test | Namespace test |
Error and event names on the wire Good to know
| Item | Format | Example |
|---|---|---|
| Event type | context.aggregate.fact_in_past_tense.vN | sales.order.cancelled.v1 |
| Error code | snake_case glossary phrase | order_already_dispatched |
| Queue name | context.consumer.event | billing.invoice.order_placed |
| Metric label | Glossary noun | orders_placed_total |
| Log key | Glossary field | order_id, customer_id |
Go
The module is docs/snippets/ddd/ubiquitous-language/go; gofmt -l . is clean, go vet ./... and go test ./... pass. The running example is the Sales, Fulfilment and Billing split of an online shop.
Before: developer words
The first file works, and nobody in the business can read it. Manager, Data, Info, a numeric Status and a boolean Flag carry the whole rule:
// Package before shows a feature written in developer words, not in the
// language of the business. It compiles, it even works, and nobody in the
// sales team can read it.
package before
// OrderData is a bag of fields; "Data" says nothing about the domain.
type OrderData struct {
ID string
Status int // 0 = new, 1 = ok, 2 = done, 3 = x. Nobody remembers which.
Items []ItemInfo
Flag bool // true after the customer "cancelled"? or the shop?
}
// ItemInfo is another "Info" type: a line of an order, but the code never says so.
type ItemInfo struct {
SKU string
Qty int
}
// OrderManager does everything to everything.
type OrderManager struct{}
// ProcessOrder is the "the system does X" voice: no actor, no business verb.
func (m *OrderManager) ProcessOrder(d *OrderData) error {
d.Status = 1
return nil
}
// UpdateStatus is a setter in disguise; the business never "updates a status".
func (m *OrderManager) UpdateStatus(d *OrderData, s int) {
d.Status = s
}
// HandleCancel hides two different business rules behind one flag.
func (m *OrderManager) HandleCancel(d *OrderData) {
d.Flag = true
d.Status = 3
}After: the Sales language
The package is named after the context. The type is Order, the constructor is the business verb Place, the methods are Cancel and MarkDispatched, the events are past tense, and the errors are sentences the support agent can read:
// Package sales is the Sales bounded context. Here an Order is the customer's
// commitment to buy. Every exported name below is a word from the Sales glossary.
package sales
import (
"errors"
"fmt"
"time"
)
type (
// OrderID identifies an Order inside Sales.
OrderID string
// CustomerID identifies the Customer who placed the Order.
CustomerID string
// SKU is the stock keeping unit the shopper picked.
SKU string
)
// Line is one SKU and a quantity on an Order.
type Line struct {
SKU SKU
Quantity int
}
type state int
const (
placed state = iota
cancelled
dispatched
)
// Errors are phrased in the language of the business so a support agent can
// read them aloud to the customer.
var (
ErrEmptyOrder = errors.New("an order needs at least one line")
ErrAlreadyDispatched = errors.New("the order is already dispatched; request a return instead")
ErrAlreadyCancelled = errors.New("the order is already cancelled")
)
// Event is something that happened in Sales, named in the past tense.
type Event interface{ EventName() string }
// OrderPlaced: the customer committed to buy.
type OrderPlaced struct {
OrderID OrderID
CustomerID CustomerID
Lines []Line
At time.Time
}
// EventName implements Event: the class name, not the wire type.
func (OrderPlaced) EventName() string { return "OrderPlaced" }
// OrderCancelled: the customer (or support on their behalf) withdrew the commitment.
type OrderCancelled struct {
OrderID OrderID
Reason string
At time.Time
}
// EventName implements Event: the class name, not the wire type.
func (OrderCancelled) EventName() string { return "OrderCancelled" }
// Order is the Sales aggregate: the customer's commitment to buy.
type Order struct {
id OrderID
lines []Line
state state
events []Event
}
// Place records the commitment. The constructor is a business verb, not New.
func Place(id OrderID, customer CustomerID, lines []Line, now time.Time) (*Order, error) {
if len(lines) == 0 {
return nil, ErrEmptyOrder
}
for _, l := range lines {
if l.Quantity <= 0 {
return nil, fmt.Errorf("line %s: quantity must be positive", l.SKU)
}
}
o := &Order{id: id, lines: append([]Line(nil), lines...), state: placed}
o.events = append(o.events, OrderPlaced{OrderID: id, CustomerID: customer, Lines: o.lines, At: now})
return o, nil
}
// Cancel withdraws the commitment. It is allowed until the Order is dispatched.
func (o *Order) Cancel(reason string, now time.Time) error {
switch o.state {
case cancelled:
return ErrAlreadyCancelled
case dispatched:
return ErrAlreadyDispatched
}
o.state = cancelled
o.events = append(o.events, OrderCancelled{OrderID: o.id, Reason: reason, At: now})
return nil
}
// MarkDispatched is called when Fulfilment reports ParcelDispatched.
func (o *Order) MarkDispatched() { o.state = dispatched }
// IsCancelled answers a question the business asks.
func (o *Order) IsCancelled() bool { return o.state == cancelled }
// PullEvents returns and clears the events recorded by the last commands.
func (o *Order) PullEvents() []Event {
ev := o.events
o.events = nil
return ev
}The tests read as business rules, in a table test whose name fields are sentences:
package sales_test
import (
"errors"
"testing"
"time"
"academy/ubiquitous-language/sales"
)
var now = time.Date(2026, 11, 25, 10, 0, 0, 0, time.UTC)
// The test names are sentences a sales manager can confirm.
func TestCustomerCanCancelAnOrderBeforeItIsDispatched(t *testing.T) {
tests := []struct {
name string
dispatch bool
cancelTw bool
want error
}{
{name: "a placed order can be cancelled"},
{name: "a dispatched order cannot be cancelled", dispatch: true, want: sales.ErrAlreadyDispatched},
{name: "a cancelled order cannot be cancelled again", cancelTw: true, want: sales.ErrAlreadyCancelled},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
o, err := sales.Place("o-1", "c-1", []sales.Line{{SKU: "BK-1", Quantity: 1}}, now)
if err != nil {
t.Fatal(err)
}
if tc.dispatch {
o.MarkDispatched()
}
if tc.cancelTw {
_ = o.Cancel("changed my mind", now)
}
err = o.Cancel("changed my mind", now)
if !errors.Is(err, tc.want) {
t.Fatalf("got %v, want %v", err, tc.want)
}
})
}
}
func TestPlacingAnOrderRecordsOrderPlaced(t *testing.T) {
o, _ := sales.Place("o-2", "c-1", []sales.Line{{SKU: "BK-1", Quantity: 2}}, now)
ev := o.PullEvents()
if len(ev) != 1 || ev[0].EventName() != "OrderPlaced" {
t.Fatalf("unexpected events: %#v", ev)
}
}
func TestAnOrderWithoutLinesCannotBePlaced(t *testing.T) {
if _, err := sales.Place("o-3", "c-1", nil, now); !errors.Is(err, sales.ErrEmptyOrder) {
t.Fatalf("got %v", err)
}
}Same word, other contexts
In Fulfilment the word Order means a work order (PickLine, Release, Pick, DispatchParcel). It does not import the Sales package; a translator (see Service Boundaries) turns OrderPlaced into Release:
// Package fulfilment is the Fulfilment bounded context. Here an Order is a
// work order: lines to pick from shelves and pack into parcels. It is NOT the
// customer's commitment; that word belongs to Sales.
package fulfilment
import "errors"
// OrderID is the Fulfilment work order number (a different value from the Sales one).
type OrderID string
// PickLine is one location, SKU and quantity to pick.
type PickLine struct {
SKU string
Quantity int
Picked int
}
// Order is a work order for the warehouse.
type Order struct {
id OrderID
salesRef string // reference only; Fulfilment never imports the Sales package
lines []PickLine
dispatched bool
}
// ErrNotFullyPicked is raised when packing is attempted too early.
var ErrNotFullyPicked = errors.New("every line must be picked before the parcel is dispatched")
// Release creates the work order when Sales reports OrderPlaced (via a translator).
func Release(id OrderID, salesRef string, lines []PickLine) *Order {
return &Order{id: id, salesRef: salesRef, lines: lines}
}
// Pick records picked units for a SKU.
func (o *Order) Pick(sku string, qty int) {
for i := range o.lines {
if o.lines[i].SKU == sku {
o.lines[i].Picked += qty
}
}
}
// DispatchParcel hands the packed parcel to the carrier.
func (o *Order) DispatchParcel() error {
for _, l := range o.lines {
if l.Picked < l.Quantity {
return ErrNotFullyPicked
}
}
o.dispatched = true
return nil
}
// IsDispatched answers the question the warehouse asks.
func (o *Order) IsDispatched() bool { return o.dispatched }In Billing, Order is only the basis of an Invoice:
// Package billing is the Billing bounded context. Here an Order is only the
// reason an Invoice exists: an amount, a payer and a tax treatment.
package billing
import "fmt"
// Money is an amount in minor units with a currency.
type Money struct {
Minor int64
Currency string
}
// Order is the billable basis of an Invoice. Billing keeps no lines, no stock, no addresses.
type Order struct {
Reference string
Payer string
Total Money
}
// Invoice is what Billing owes the customer's accountant.
type Invoice struct {
Number string
Basis Order
}
// Issue creates an Invoice for a billable Order.
func Issue(seq int, o Order) Invoice {
return Invoice{Number: fmt.Sprintf("INV-2026-%06d", seq), Basis: o}
}The glossary as code, and a linting test
The glossary is data with Context, Term, Meaning, Avoid and Since. The two "Order" rows differ by context, which is the point:
// Package glossary is the glossary as data: one entry per word and context.
// A test fails when an exported domain type has no entry, so the glossary
// cannot silently drift away from the code.
package glossary
// Entry is one word in one bounded context.
type Entry struct {
Context string
Term string
Meaning string
Avoid []string // synonyms the team agreed not to use
Since string // glossary version that introduced the term
}
// Terms is the Sales and Fulfilment glossary (version 1.3).
var Terms = []Entry{
{"sales", "Order", "The customer's commitment to buy specific SKUs at agreed prices.", []string{"Purchase", "Transaction"}, "1.0"},
{"sales", "Line", "One SKU and a quantity on an Order.", []string{"Item", "Row"}, "1.0"},
{"sales", "Customer", "A person or company that can place an Order.", []string{"User", "Client"}, "1.0"},
{"sales", "OrderPlaced", "Event: the customer committed to buy.", []string{"OrderCreated"}, "1.0"},
{"sales", "OrderCancelled", "Event: the commitment was withdrawn before dispatch.", []string{"OrderDeleted"}, "1.1"},
{"fulfilment", "Order", "A work order: lines to pick and pack into parcels.", []string{"Job", "Task"}, "1.0"},
{"fulfilment", "PickLine", "One location, SKU and quantity to pick.", []string{"Item"}, "1.0"},
{"billing", "Order", "The billable basis of an Invoice: amount, payer, tax treatment.", []string{"Sale"}, "1.2"},
{"billing", "Invoice", "The legal document asking the payer for money.", []string{"Bill", "Receipt"}, "1.0"},
}
// Has reports whether a context defines a term.
func Has(context, term string) bool {
for _, e := range Terms {
if e.Context == context && e.Term == term {
return true
}
}
return false
}A test walks the AST of each context package and fails when an exported domain type is missing from the glossary or when a name ends in a banned technical word:
package ubiquitouslanguage_test
import (
"go/ast"
"go/parser"
"go/token"
"strings"
"testing"
"academy/ubiquitous-language/glossary"
)
var contexts = []string{"sales", "fulfilment", "billing"}
// bannedSuffixes are technical words that do not belong in a domain package.
var bannedSuffixes = []string{"Manager", "Helper", "Util", "Data", "Info", "Processor", "Handler"}
func TestEveryExportedTypeIsInTheGlossary(t *testing.T) {
for _, c := range contexts {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, c, nil, 0)
if err != nil {
t.Fatal(err)
}
for _, pkg := range pkgs {
for fname, f := range pkg.Files {
if strings.HasSuffix(fname, "_test.go") {
continue
}
for _, d := range f.Decls {
gd, ok := d.(*ast.GenDecl)
if !ok || gd.Tok != token.TYPE {
continue
}
for _, s := range gd.Specs {
name := s.(*ast.TypeSpec).Name.Name
if !ast.IsExported(name) {
continue
}
if name == "Event" || name == "Money" || name == "OrderID" || name == "CustomerID" || name == "SKU" {
continue // infrastructure of the model, not glossary words
}
if !glossary.Has(c, name) {
t.Errorf("%s.%s is not in the glossary", c, name)
}
}
}
}
}
}
}
func TestNoTechnicalJargonInDomainNames(t *testing.T) {
for _, c := range contexts {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, c, nil, 0)
if err != nil {
t.Fatal(err)
}
for _, pkg := range pkgs {
for _, f := range pkg.Files {
ast.Inspect(f, func(n ast.Node) bool {
id, ok := n.(*ast.Ident)
if !ok {
return true
}
for _, s := range bannedSuffixes {
if strings.HasSuffix(id.Name, s) {
t.Errorf("%s: %q ends with banned word %q", fset.Position(id.Pos()), id.Name, s)
}
}
return true
})
}
}
}
}The Go angle
| Go feature | Language face it serves | Notes |
|---|---|---|
| Package names | The context name | One lowercase word (Effective Go): sales, not salesService |
package.Type | Short names | sales.Order, not sales.SalesOrder (Code Review Comments on package names) |
| Constructors | Business verbs | sales.Place where a rule exists; New otherwise |
| Unexported state, methods | The rule's name | Cancel, not SetStatus; invalid states are impossible |
errors.Is with sentinel errors | Error vocabulary | Messages are sentences of the language |
Table tests with name fields | Examples | t.Run(tc.name, ...) prints business sentences |
go/parser + go/ast | Language lint | Banned suffixes, glossary coverage |
internal/ | Context privacy | A context's words stay inside |
Initialisms (ID, URL) | Style | Code Review Comments: appID, not appId; this is style, not vocabulary |
Laravel
The same feature in a Laravel 13 application (PHP 8.4) structured as modules under App\Modules. PHP is not installed on the authoring machine; the code was reviewed, not run.
Before: developer words
<?php
namespace App\Services;
use App\Models\Order;
use Illuminate\Http\Request;
// Before: developer words everywhere. "process", "update status", magic numbers.
class OrderManager
{
public function processOrder(Request $request): Order
{
$order = new Order();
$order->status = 1;
$order->data = json_encode($request->input('items'));
$order->save();
return $order;
}
public function updateStatus(Order $order, int $status): void
{
$order->status = $status; // 3 means cancelled, unless flag is set
$order->save();
}
}After: Sales language in the domain
The domain events are final readonly value objects in the past tense:
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
/** Past tense: the customer committed to buy. The outbox translator publishes it as sales.order.placed.v1. */
final readonly class OrderPlaced
{
/** @param list<array{sku: string, quantity: int}> $lines */
public function __construct(
public string $orderId,
public string $customerId,
public array $lines,
public DateTimeImmutable $placedAt,
) {}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
/** Past tense: the commitment was withdrawn before dispatch. */
final readonly class OrderCancelled
{
public function __construct(
public string $orderId,
public string $reason,
public DateTimeImmutable $cancelledAt,
) {}
}The aggregate speaks the language: place, cancel, markDispatched, with a named exception for the dispatched case:
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DateTimeImmutable;
use DomainException;
/** In Sales, an Order is the customer's commitment to buy. */
final class Order
{
private const PLACED = 'placed';
private const CANCELLED = 'cancelled';
private const DISPATCHED = 'dispatched';
/** @var list<object> */
private array $events = [];
private function __construct(
public readonly string $id,
private array $lines,
private string $state,
) {}
/** @param list<array{sku: string, quantity: int}> $lines */
public static function place(string $id, string $customerId, array $lines, DateTimeImmutable $now): self
{
if ($lines === []) {
throw new DomainException('An order needs at least one line.');
}
$order = new self($id, $lines, self::PLACED);
$order->events[] = new OrderPlaced($id, $customerId, $lines, $now);
return $order;
}
public function cancel(string $reason, DateTimeImmutable $now): void
{
if ($this->state === self::DISPATCHED) {
throw OrderAlreadyDispatched::for($this->id);
}
if ($this->state === self::CANCELLED) {
throw new DomainException("Order {$this->id} is already cancelled.");
}
$this->state = self::CANCELLED;
$this->events[] = new OrderCancelled($this->id, $reason, $now);
}
public function markDispatched(): void
{
$this->state = self::DISPATCHED;
}
public function isCancelled(): bool
{
return $this->state === self::CANCELLED;
}
/** @return list<object> */
public function pullEvents(): array
{
$events = $this->events;
$this->events = [];
return $events;
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
use DomainException;
/** The message is readable by a support agent and by the customer. */
final class OrderAlreadyDispatched extends DomainException
{
public static function for(string $orderId): self
{
return new self("Order {$orderId} is already dispatched; request a return instead.");
}
}<?php
declare(strict_types=1);
namespace App\Modules\Sales\Domain;
interface OrderRepository
{
public function get(string $orderId): Order;
public function save(Order $order): void;
}Application service, routes and controller
The use case is named as the business says it, and the routes use glossary nouns and verbs:
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Http;
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderRepository;
use DateTimeImmutable;
use Illuminate\Contracts\Events\Dispatcher;
/** Use case named as the business says it: "cancel order". */
final class CancelOrder
{
public function __construct(private OrderRepository $orders, private Dispatcher $events) {}
public function __invoke(string $orderId, string $reason): void
{
/** @var Order $order */
$order = $this->orders->get($orderId);
$order->cancel($reason, new DateTimeImmutable());
$this->orders->save($order);
foreach ($order->pullEvents() as $event) {
$this->events->dispatch($event);
}
}
}<?php
declare(strict_types=1);
use App\Modules\Sales\Http\CancelOrderController;
use App\Modules\Sales\Http\PlaceOrderController;
use Illuminate\Support\Facades\Route;
// Before: POST /order/process, POST /order/update-status
// After: URLs are nouns from the glossary, actions are business verbs.
Route::post('/orders', PlaceOrderController::class)->name('orders.place');
Route::post('/orders/{order}/cancellation', CancelOrderController::class)->name('orders.cancel');<?php
declare(strict_types=1);
namespace App\Modules\Sales\Http;
use App\Modules\Sales\Domain\OrderAlreadyDispatched;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class CancelOrderController
{
public function __invoke(Request $request, string $order, CancelOrder $cancelOrder): JsonResponse
{
try {
$cancelOrder($order, (string) $request->input('reason', ''));
} catch (OrderAlreadyDispatched $e) {
// Error code and message are glossary words, not "ERR_409_STATE".
return response()->json(['error' => 'order_already_dispatched', 'message' => $e->getMessage()], 409);
}
return response()->json(['order' => $order, 'state' => 'cancelled']);
}
}Legacy table: the mismatch in one class
The Eloquent model sits in the persistence namespace and translates the legacy tbl_ord.st integer into words; the domain never sees it:
<?php
declare(strict_types=1);
namespace App\Modules\Sales\Persistence;
use Illuminate\Database\Eloquent\Model;
/**
* Persistence model over a LEGACY table. The mismatch lives here and only here:
* the table says tbl_ord / st, the domain says Order / state. The domain layer
* never sees a column name.
*/
class OrderRecord extends Model
{
protected $table = 'tbl_ord';
protected $primaryKey = 'ord_id';
public $incrementing = false;
protected $keyType = 'string';
private const LEGACY_STATE = [0 => 'placed', 1 => 'dispatched', 2 => 'cancelled'];
public function state(): string
{
return self::LEGACY_STATE[(int) $this->st] ?? throw new \UnexpectedValueException("Unknown legacy st={$this->st}");
}
}The same word in Fulfilment
<?php
declare(strict_types=1);
namespace App\Modules\Fulfilment\Domain;
use DomainException;
/** In Fulfilment, an Order is a work order: lines to pick and pack. Not the Sales Order. */
final class Order
{
/** @param array<string, array{quantity: int, picked: int}> $lines keyed by SKU */
private function __construct(public readonly string $id, private array $lines, private bool $dispatched = false) {}
/** @param array<string, int> $quantities SKU => quantity, translated from Sales by an ACL */
public static function release(string $id, array $quantities): self
{
$lines = [];
foreach ($quantities as $sku => $quantity) {
$lines[$sku] = ['quantity' => $quantity, 'picked' => 0];
}
return new self($id, $lines);
}
public function pick(string $sku, int $quantity): void
{
$this->lines[$sku]['picked'] += $quantity;
}
public function dispatchParcel(): void
{
foreach ($this->lines as $line) {
if ($line['picked'] < $line['quantity']) {
throw new DomainException('Every line must be picked before the parcel is dispatched.');
}
}
$this->dispatched = true;
}
}Gherkin and Pest tests
The feature file (shown above in Language in tests) lives at:
Feature: Cancel an order
A customer may withdraw an Order until the warehouse dispatches the parcel.
Rule: An Order can be cancelled only before it is dispatched
Example: A placed Order is cancelled
Given Alice has placed an Order for 2 copies of "BK-1"
When Alice cancels the Order because "changed my mind"
Then the Order is cancelled
And OrderCancelled is recorded
Example: A dispatched Order cannot be cancelled
Given Alice has placed an Order for 1 copy of "BK-1"
And Fulfilment has dispatched the parcel
When Alice tries to cancel the Order
Then she is told "the order is already dispatched; request a return instead"Pest unit tests with describe and it; the Pest docs say it() "prefixes the test description with the word 'it', making your tests more readable" and describe() groups related tests:
<?php
declare(strict_types=1);
use App\Modules\Sales\Domain\Order;
use App\Modules\Sales\Domain\OrderAlreadyDispatched;
use App\Modules\Sales\Domain\OrderCancelled;
use App\Modules\Sales\Domain\OrderPlaced;
$now = new DateTimeImmutable('2026-11-25 10:00:00');
// Test names are sentences the sales manager can confirm.
describe('Order', function () use ($now) {
it('records OrderPlaced when a customer places it', function () use ($now) {
$order = Order::place('o-1', 'c-1', [['sku' => 'BK-1', 'quantity' => 1]], $now);
expect($order->pullEvents())->toHaveCount(1)->and($order->pullEvents())->toBeEmpty();
});
it('cannot be placed without lines', function () use ($now) {
Order::place('o-2', 'c-1', [], $now);
})->throws(DomainException::class, 'at least one line');
it('can be cancelled before it is dispatched', function () use ($now) {
$order = Order::place('o-3', 'c-1', [['sku' => 'BK-1', 'quantity' => 1]], $now);
$order->pullEvents();
$order->cancel('changed my mind', $now);
expect($order->isCancelled())->toBeTrue()
->and($order->pullEvents()[0])->toBeInstanceOf(OrderCancelled::class);
});
it('cannot be cancelled once it is dispatched', function () use ($now) {
$order = Order::place('o-4', 'c-1', [['sku' => 'BK-1', 'quantity' => 1]], $now);
$order->markDispatched();
$order->cancel('too late', $now);
})->throws(OrderAlreadyDispatched::class);
});Pest architecture tests keep jargon out of the domain:
<?php
declare(strict_types=1);
// Pest architecture tests keep jargon out of the domain layer.
arch('the domain layer has no technical-jargon class names')
->expect('App\Modules\Sales\Domain')
->not->toHaveSuffix('Manager')
->not->toHaveSuffix('Helper')
->not->toHaveSuffix('Util')
->not->toHaveSuffix('Data');
arch('the domain layer does not depend on Eloquent or HTTP')
->expect('App\Modules\Sales\Domain')
->not->toUse(['Illuminate\Database', 'Illuminate\Http']);
arch('domain events are final readonly value objects named in the past tense')
->expect('App\Modules\Sales\Domain\OrderPlaced')
->toBeFinal()->toBeReadonly();The Laravel angle
| Laravel feature | Language face it serves | Notes |
|---|---|---|
| PSR-4 namespaces per module | Context names | App\Modules\Sales\... mirrors the glossary |
| PSR-12 class naming | StudlyCaps classes | Style only; vocabulary is yours |
| Route names and URIs | API language | orders.cancel, /orders/{order}/cancellation |
$table, $primaryKey on Eloquent | Mapping a legacy schema | Keep in a persistence model, not in the domain |
| Accessors and casts | Translating columns to words | Enum casts give state words instead of ints |
Exceptions rendered in bootstrap/app.php | Error vocabulary | Map OrderAlreadyDispatched to a 409 with the glossary code |
Events (Dispatcher) | Domain events | Names in the past tense; wire names carry the context and version |
Lang files (lang/fa/*.php) | Persian UI wording | Persian text in translation files, English identifiers in code |
Pest describe/it/arch() | Test language | Sentence-like names, jargon bans |
| Form Requests | Input vocabulary | Field names match the API language |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost |
|---|---|---|---|---|
| Five meanings of Customer | One term per context, translators | Rename per context; ACL | Each model is small | Needs identity mapping |
| Code and speech disagree | Rename code to the spoken word | Refactor with glossary version bump | One language | Short-term churn |
| Legacy schema in cryptic names | Persistence model or view | OrderRecord, sales.orders view | Domain stays clean | One more layer |
| Experts cannot read tests | Sentence test names, Gherkin | Rewrite names; add Rules/Examples | Living documentation | Discipline |
| Terms drift unnoticed | Glossary test in CI | AST/Pest checks | Drift fails the build | Maintenance of the test |
| Persian vs English | Bilingual glossary | One identifier per Persian term | No synonyms | Review effort |
| Event names useless | Past-tense domain events | OrderCancelled with reason | Consumers act without diffing | Event versioning |
| Jargon leaks | Naming bans | arch() and AST checks | Cleaner domain layer | Occasional false positives |
Renaming a feature into the language, step by step
# Rename "ProcessOrder / UpdateStatus(3)" into "Place / Cancel"
1 Write the sentences with the expert: "A customer places an order. Before dispatch they can cancel it."
2 Add glossary rows (Order, place, cancel, OrderPlaced, OrderCancelled)
3 Move the code to a package named after the context (sales)
4 Replace Status int with named states; replace the flag with a method (Cancel)
5 Replace the setter with business verbs; emit events from the verbs
6 Rename tests into sentences; add the Gherkin feature
7 Rename routes and error codes; keep the old routes for one release with a deprecation header
8 Run the glossary lint; merge; announce the glossary version| Before | After | Where |
|---|---|---|
OrderManager.ProcessOrder | sales.Place / Order::place | Go, PHP |
OrderData | sales.Order | Go |
Status int | state with placed, cancelled, dispatched | Go, PHP, SQL |
HandleCancel | Order.Cancel(reason, now) | Go |
POST /order/update-status | POST /orders/{id}/cancellation | HTTP |
ERR_409_STATE | order_already_dispatched | API |
tbl_ord.st | sales.orders.state view or OrderRecord::state() | SQL, Eloquent |
order.updated | sales.order.cancelled.v1 | Events |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New project, experts available | Build the glossary in the first sessions | Event Storming, Gherkin examples | The words become the structure |
| Legacy system with cryptic names | Do not rename the schema first; wrap it | Views, OrderRecord, ACL | Cheap, reversible |
| Two teams argue over "Order" | Split into contexts | Context map | Meanings are different, not wrong |
| Persian business, English code | Bilingual glossary, English identifiers | UI strings in lang files | One identifier per concept |
| Experts have no time | Short weekly session on one flow | Read test names aloud | Small steady corrections |
| Regulated vocabulary (law, tax) | Use the official term, even if awkward | Single constant, glossary note | Compliance beats elegance |
| Microservices | One language per service boundary | Published language for events | Services own words |
| Pure CRUD admin tool | A light glossary is enough | None | The model is thin |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One codebase, one deployable. The easy failure is a single global vocabulary: one Order class, one customers table, serving Sales, Fulfilment and Billing. Even here, draw the language lines: separate packages or namespaces per context (sales, fulfilment, billing), each with its own Order, and a glossary per context. A feature touching "cancel" reads the same across code, tests and UI.
Modular monolith and multiple databases
Modules are the bounded contexts inside one deployable (Modular Monolith). Each module has its own namespace, glossary file and, ideally, its own schema or table prefix. Modules talk through published events and small interfaces, and a translator converts one module's words into another's. Architecture tests enforce that Fulfilment does not import sales.Order.
Microservices: the boundary becomes a network
Services own contexts. The ubiquitous language becomes the service's own; what crosses the network is the published language (a versioned event or API schema). A flow:
# Cancel an order across three services
1 Customer -> Sales API: POST /orders/42/cancellation
2 Sales: Order.Cancel -> record OrderCancelled in the outbox (same transaction)
3 Outbox relay -> broker: sales.order.cancelled.v1
4 Fulfilment (ACL): OrderCancelled -> StopPicking(workOrder) ; emits PickingStopped
5 Billing (ACL): OrderCancelled -> VoidInvoice or CreditNote ; emits InvoiceVoided
6 Each service speaks its own words; only step 3 uses the published languageSee Outbox and Saga for reliability, Service Communication for transport, and Message Transformation for the translator.
Distributed data: replicas, caches and multi-region
Read models, caches and search indexes need names too. A read model for "orders awaiting dispatch" is named in the reporting context's words, not orders_cache. Language risks at distance: stale words in old events (keep upcasters), multi-region teams with different vocabularies (a glossary per region only if the business differs), and analytics copying tables with developer names (rename in the warehouse layer). A schema registry versions the published language so consumers adapt.
Scaling path: 1×, 10×, 100×
| Scale | Language practice |
|---|---|
| 1× (one team, one product) | One glossary file, review it in retrospectives |
| 10× (several teams, one monolith) | A glossary per module, owners per term, a glossary lint in CI |
| 100× (many teams, many services) | Published languages per service, a catalogue of events and terms, translators at every border, regular cross-team vocabulary reviews |
Language scales by splitting, not by standardising: more contexts, each with a small shared vocabulary.
Lab: put a feature into the language
Prerequisite: Go 1.24+.
cd docs/snippets/ddd/ubiquitous-language/go
gofmt -l . # expected: no output
go vet ./... # expected: no output
go test ./... # expected: ok for the root and sales packagesExperiments:
- Open
before/order.go. List every word that a sales manager would not say. Write the glossary rows you would add. - In
sales/order.go, renameCanceltoDelete. Rungo test ./.... The tests fail on a name, which is the point: the test names are the business rules. - Add a type
OrderManagerto thesalespackage. Run the tests. Expected:glossary_test.gofails withends with banned word "Manager"and "is not in the glossary". - Add
{"sales", "Basket", "A cart that can be abandoned.", nil, "1.4"}to the glossary, then addtype Basket struct{}tosales. The coverage test passes. - Add a second context file
billing/refund.gowith a type namedRefund. Observe how the glossary test only checks the three known contexts; add the context to the list and the glossary. - Write one more Gherkin example for "an already cancelled order cannot be cancelled again", then add the corresponding
it()in Pest and the table-test row in Go.
Common misconceptions
| Belief | Reality |
|---|---|
| One ubiquitous language for the whole company | It is ubiquitous within one bounded context; other contexts have their own |
| It is a glossary document | The glossary records it; the language lives in speech, code and tests |
| Developers define it | Experts and developers define it together; experts object to awkward terms, developers watch for ambiguity |
| Translating is fine if the mapping is documented | Evans: translation blunts communication; the mapping is lost and slow |
| Renaming is cosmetic | A change in the language is a change in the model |
OrderUpdated is a fine event name | Events are specific past-tense facts: OrderCancelled |
| Technical names are neutral | Manager, Helper, Data hide responsibilities |
| Persian business and English code means mixing is fine | Use one English identifier per Persian term, never mix |
| The database must match the language exactly | The domain must; a mapping layer can hide a legacy schema |
| BDD means Cucumber | BDD is discovery, formulation, automation; tools are optional |
Cheat sheet
| Topic | What to remember |
|---|---|
| Definition | One shared language of experts and developers, within one bounded context, in speech, code, tests, UI |
| Scope | Never company-wide; one word can differ across contexts |
| Source of truth | The model; a language change is a model change |
| Building | Knowledge crunching, glossary, listening for ambiguity, Event Storming |
| Events | Past tense, glossary words, versioned: sales.order.cancelled.v1 |
| Commands | Imperative business verbs: PlaceOrder, CancelOrder |
| Code | Packages and types named from the glossary; no Manager, Helper, Data in the domain |
| Tests | Sentences; Gherkin Rule/Example; Pest it; Go table-test names |
| API and UI | Same nouns, verbs and error sentences |
| Database | Greenfield: same words. Legacy: view or persistence model, never leak |
| Persian and English | Bilingual glossary, English identifiers, Persian in UI strings |
| Evolving | Rename with expand/contract; bump the glossary version |
| Smells | Synonyms, jargon leaks, "the system does X", developers correcting experts |
| Measuring | New-hire test, glossary coverage test, expert readability |
| Enforcement | Glossary lint in CI: banned suffixes, coverage |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What does "ubiquitous" mean in "ubiquitous language", and where does the ubiquity end? Must-know
Answer
Answer: It means everywhere inside one bounded context: speech, diagrams, code, tests, UI. It ends at the context boundary, where another context may use the same word differently.
2 — Why does translation between experts' words and code names hurt the model? Must-know
Answer
Answer: Each translation drops detail and costs time, and the mapping lives in heads. Evans: "Translation blunts communication and makes knowledge crunching anemic."
3 — Give three meanings of "Customer" in an online shop and name the contexts. Important
Answer
Answer: Sales: the person who places Orders. Billing: the payer on the Invoice. Fulfilment: the recipient on the parcel label. Support and Marketing add more.
4 — Why is OrderUpdated a weak event name, and what is better? Must-know
Answer
Answer: It states no business fact. Prefer a specific past-tense event such as OrderCancelled with a reason.
5 — What is wrong with a class named OrderManager in the domain layer? Must-know
Answer
Answer: It is technical jargon; it hides what the business does and attracts unrelated logic. Name the role or the verb: Order, CancelOrder.
6 — How do you handle a legacy table tbl_ord(st int) without leaking it into the domain? Important
Answer
Answer: Wrap it in a persistence model (Eloquent OrderRecord, a Go repository) or a SQL view that exposes state as words, so only one layer knows the legacy names.
7 — How should a Persian-speaking business team with an English codebase manage terms? Important
Answer
Answer: Keep a bilingual glossary mapping each Persian term to one English identifier; speak Persian, code in English, keep Persian text in UI translation files, and never mix.
8 — How do you evolve the language when the business renames "Client" to "Customer"? Important
Answer
Answer: Agree the term, bump the glossary version, rename code, use expand/contract for the schema, support both names on the API for a period, publish a new event version, retire the old term.
9 — How does a glossary lint test work and what does it catch? Good to know
Answer
Answer: It parses the domain packages (AST or reflection), checks that exported domain types appear in the glossary and that no name ends in banned words like Manager. It catches drift and jargon leaks.
10 — How do you test whether the language works for a newcomer? Good to know
Answer
Answer: Give a new hire the glossary and one module, and ask them to explain a rule to an expert using the same words. Corrections show gaps.
Glossary
| Term | Meaning |
|---|---|
| Ubiquitous language | A language structured around the domain model and used by all team members within a bounded context |
| Bounded context | The boundary within which a model and its language apply |
| Domain model | A system of abstractions describing selected aspects of a domain |
| Domain expert | A person with deep business knowledge who works with developers on the model |
| Knowledge crunching | Collaborative digestion of domain information into a model through conversation |
| Model-driven design | Making the code reflect the model literally so names and structure match |
| Hands-on modeler | A modeler who also touches the code, so models are implementable |
| Glossary | A versioned list of terms, meanings and avoided synonyms |
| Domain event | A past-tense record of something that happened in the domain |
| Command | An imperative business request such as CancelOrder |
| Published language | A documented, versioned shared format between contexts, such as an event schema |
| Anticorruption layer | A translator that protects one context's model from another's |
| Translator | Code that converts one context's terms into another's |
| Synonym smell | Two words for one concept inside one context |
| Jargon leak | Technical names such as Manager or Data appearing in the domain layer |
| Gherkin | The Given/When/Then language for executable specifications |
| BDD | Behaviour-driven development: discovery, formulation, automation of examples |
| Living documentation | Documentation checked automatically against the system's behaviour |
| Persistence model | A class that maps the domain to storage, absorbing legacy names |
| Expand/contract | A zero-downtime rename: add the new, dual-write, migrate, drop the old |
| Event Storming | A workshop that discovers events and language on a wall of stickies |
| Eloquent | Laravel's ORM |
| Pest | A PHP testing framework with it, describe and arch() |
| Table test | A Go test running one function over rows of named cases |
References
- Eric Evans, Domain-Driven Design Reference, 2015: Ubiquitous Language, Bounded Context, Model-Driven Design, Hands-on Modelers. Saved text:
scratchpad/sources/ubiquitous-language/ddd_reference.txt - Martin Fowler, Ubiquitous Language, 31 October 2006. Saved:
martinfowler-ubiquitous.html - Martin Fowler, Bounded Context. Saved:
martinfowler-bc.html - Cucumber, Behaviour-Driven Development and Gherkin reference. Saved:
bdd.html,gherkin.html - Go, Effective Go (package names, MixedCaps), Code Review Comments (package names, initialisms), Package names. Saved:
effective_go.html,codereview.html,gopkgnames.html - PHP-FIG, PSR-12; Pest, Writing tests and Architecture testing; Laravel 13, Eloquent
- Alberto Brandolini, EventStorming (book landing page read; no language claims quoted from it)
- Vaughn Vernon, Implementing Domain-Driven Design (2013), chapters 1–2, and Vlad Khononov, Learning Domain-Driven Design (2021): cited as background, not fetched, no quotes taken