Skip to content

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 forGo to
The whole page in four tablesEverything in one minute
Why one shared language beats two dialectsWhy a shared language exists
Evans, Fowler, Vernon, Brandolini, KhononovWhere it comes from
The definition and its five channelsWhat it is
"Customer" meaning five thingsWhy translation kills models
Glossary, knowledge crunching, listening for ambiguityBuilding the language
Past-tense events, verbs vs nounsEvents and verbs
Order in Sales, Fulfilment and BillingOne word, three contexts
Words change; versioned glossariesEvolving the language
Class, package, table, event namesLanguage in code
Gherkin, Pest, Go table testsLanguage in tests
Routes, errors, enums, UI textsLanguage in APIs and UI
Legacy schema, ACL pointerLanguage in the database
Slack, tickets, diagrams, glossary pageConversations and tooling
Persian business language, English codeMultilingual teams
Synonyms, jargon leaks, passive voiceSmells
New-hire test, glossary coverageMeasuring
Before/after renames in Go and LaravelGo, Laravel
Monolith to distributedIn architecture
Hands-onLab
Wrong beliefs, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked in the concept catalogue.

TermIn plain wordsTiny exampleWhat goes wrong without it
Ubiquitous languageOne vocabulary shared by experts and developers, used everywhere in one context"A customer cancels an Order" is the sentence, the method and the test nameExperts say one thing, code says another, bugs live in the gap
Domain expertThe person who knows the business rules by doing the workA warehouse supervisor, a support leadDevelopers invent rules from guesses
Knowledge crunchingExperts and developers digest raw information into a model, by conversationA two-hour session that ends with a cleaner glossaryRequirements arrive as documents, understanding does not
GlossaryThe written list of terms, meanings and forbidden synonymsOrder: the customer's commitment to buyEvery new hire re-learns words from code archaeology
Model-driven designCode literally follows the model, so names matchOrder.cancel() exists because Sales says "cancel"A deadly divide between analysis and design
Bounded contextThe area where one word has one meaning"Order" in SalesOne word, five meanings in one codebase
Domain eventSomething that happened, named in the past tenseOrderPlacedEvents named OrderUpdated that nobody can interpret
Anticorruption layerA translator at the edge between two languagesBilling turns OrderPlaced into ChargeRequestOne context's words leak into another

Where the language lives (details in Language in code and following):

ChannelWhat the language looks like thereWrong versionRight version
SpeechExperts and developers use the same nouns and verbs"the status flag""the order is cancelled"
CodeTypes, packages, methods, eventsOrderManager.ProcessOrdersales.Place, Order.Cancel
TestsTest names read as business rulestestUpdateStatus3"a dispatched order cannot be cancelled"
APIResources and verbs from the glossaryPOST /order/update-statusPOST /orders/{id}/cancellation
UI and errorsSame words, same spelling"Error 409""The order is already dispatched"
DatabaseTable and column names, or a mapping layertbl_ord.st = 2orders.state = 'cancelled'
ToolingTickets, chat, diagrams"fix the thing in the order flow""customers cannot cancel after dispatch"

The language is scoped (details in One word, three contexts):

WordSalesFulfilmentBilling
OrderThe customer's commitment to buyA work order: lines to pick and packThe 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
CustomerThe person who places OrdersThe recipient on the parcel labelThe payer on the Invoice
StatusPlaced, cancelled, dispatchedReleased, picking, packed, dispatchedDraft, issued, settled

Smell → fix (details in Smells):

SmellSymptomFix
SynonymsOrder, Purchase, Sale, Transaction in one contextPick one in the glossary, rename the others
Jargon leakOrderManager, OrderHelper, OrderDataName 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 designBoth speak the model
Meetings produce notes, notes produce tickets, tickets produce codeMeetings produce a refined model, which is the code's structure
Bugs come from mismatched meaningBugs come from wrong rules, found by reading aloud
New hires ask two peopleNew hires read one glossary and the code
Analysis and design drift apartAnalysis 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 ​

  1. "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).
  2. "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.
  3. "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 ​

YearSourceWhat it contributed
2003Eric Evans, Domain-Driven Design: Tackling Complexity in the Heart of SoftwareNames the pattern, ties it to the model, Model-Driven Design, hands-on modelers, knowledge crunching
2006Martin 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"
2013Vaughn Vernon, Implementing Domain-Driven Design (chapters 1–2)Language within a bounded context; teams, context; secondary source here (not fetched)
2013Alberto Brandolini starts EventStormingExperts and developers share a wall of past-tense events; language emerges visibly (see Event Storming)
2015Evans, DDD Reference (free PDF)Concise pattern text: the quotes on this page
2021Vlad Khononov, Learning Domain-Driven DesignA 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 ​

Sales bounded contextUbiquitous LanguageOrder, Line, place, cancelDomain experts (speech)Developers (code)Tests and GherkinUI, API, error textsGlossary in the repoEvents and tablesSame words in speech, diagrams, code, tests, UI. A translation layer between dialects is the failure mode.

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 definitionMeaningConsequence
Structured around the domain modelWords are the model's concepts, not UI labels or table namesThe model gets tested every time someone speaks
Used by all team membersExperts, developers, testers, product, supportNobody is allowed a private dialect
Within a bounded contextValid inside one context onlyAnother context may use the same word differently
To connect all the activities with the softwareSpeech, writing, diagrams, code, testsIf 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 weeks

Real scenario: "Customer" meaning five things. In a single online shop codebase:

Who says "Customer"They meanWhich tableWhich rules
MarketingAnyone who ever gave an emailcontactsNo order needed, GDPR consent
SalesThe person who places an OrdercustomersCredit limit, loyalty tier
BillingThe legal entity that pays the InvoiceaccountsVAT id, payment terms
SupportThe person on the phone, may be a relativecallersVerification questions
FulfilmentThe recipient on the parcel labelrecipientsDelivery 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:

PracticeEffect
One glossary per contextThe five meanings stop sharing a name
Experts review code names and test namesWrong words are caught while cheap
Model-driven designNo separate "analysis model" to translate from
Anticorruption layer at the borderTranslation 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, OrderCancelled

Real 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.

TechniqueWhat you doWhat you get
Knowledge-crunching sessionTalk through concrete scenarios with an expertTerms, rules, edge cases
Listening for ambiguityNote every word the expert uses in two ways, or two words for one thingCandidates for a split or a synonym ban
GlossaryOne page: term, meaning, example, avoid-listA shared reference
Event StormingOrange stickies in the past tense on a wallThe verbs and events of the process
Example mapping / GherkinRules and examples on cards, then formulated in Given/When/ThenLanguage tested on real examples
Code reading with expertsShow them class names and test namesInstant 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).

ConceptGrammarSales exampleAnti-pattern
CommandImperative verbPlaceOrder, CancelOrderSaveOrder, UpdateOrder
EventPast tenseOrderPlaced, OrderCancelledOrderUpdated, OrderStatusChanged
StateAdjective or participleplaced, cancelled, dispatchedstatus = 3
RuleA sentence with "only if""An order can be cancelled only before dispatch"if ($s < 2) without a name
RoleNoun for who actsCustomer, 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 say

Real 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):

SalesOrder = the customer'scommitment to buyLine, Customer, place, cancelEvents: OrderPlaced,OrderCancelledFulfilmentOrder = a work order:lines to pick and packPickLine, Parcel, pick, dispatchEvents: ParcelDispatchedBillingOrder = the billable basisof an InvoiceInvoice, Payer, issue, settleEvents: InvoiceIssuedOrderPlaced via translatorvia translator
WordSalesFulfilmentBilling
OrderCustomer's commitment to buy; placed, cancelled, dispatchedWork order: PickLines to pick, pack, dispatch as a ParcelBillable basis: amount, payer, tax treatment
Identity of an OrderOrderID assigned at placementOrderID of the work order, linked to a Sales referenceInvoice number, with a reference to the Sales order
CancelWithdraw before dispatchStop picking, release stockVoid the Invoice or issue a credit note
Statusplaced, cancelled, dispatchedreleased, picking, packed, dispatcheddraft, issued, settled, voided
CustomerThe person who places OrdersThe recipient on the parcel labelThe payer on the Invoice
Owner teamSales squadWarehouse squadFinance squad

A second pair, the "Product" word:

WordCatalogWarehouse (Fulfilment)
ProductA listed offer: name, description, price, imagesNot used; the term is SKU
SKUThe variant a shopper can chooseA stocked unit with location, weight, dimensions
PricePublic list priceNot known to the warehouse
Availability"In stock" label for shoppersQuantity 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).

OptionWhenCost
One shared Order class for all threeNever as a defaultContradictory fields, merge conflicts between teams
Separate Order per context, same wordContexts are really differentNeeds a translator and a glossary per context
Different words per context (Order, PickList, BillableOrder)When the shared word keeps causing mistakesExperts 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".
v1.0v1.1v1.2v1.3Order, Line,Customer definedFirst workshopOrderCancelledadded aftersupport sessionBilling says Ordermeans billable basis;Sales entry untouchedClient renamed toCustomer in code,tables and UIEach version: glossary change, code rename, migration and a note in the changelog, in one pull request.
ChangeWhat to doMigration care
Pure rename of a wordRename in code and glossary in one PRNone for internals; API and events need overlap
A word splits in two meaningsNew term, new type, migrate data per meaningOften a context split (Bounded Context)
Two words mergeChoose one, alias the other in the glossary as "avoid"Update events with a new version
New concept appearsAdd term, owner, example, first-used versionAnnounce in the team channel
Concept disappearsMark retired with a date; remove after consumers moveKeep 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.

ArtefactMirror the languageAvoidNotes
Go packagesales, fulfilment, billingutil, common, models, typesCode Review Comments: "Avoid meaningless package names like util, common, misc, api, types, and interfaces"
Go typesales.Order, OrderPlacedOrderData, OrderInfo, OrderDTO in the domainPackage name is part of the name: sales.Order, not sales.SalesOrder
Go constructorsales.Place(...)sales.NewOrder(...) when the business verb existsBusiness verbs beat New when they carry rules
Go methodorder.Cancel(reason)order.SetStatus(3)No Get prefix needed (Effective Go)
PHP namespaceApp\Modules\Sales\DomainApp\Services, App\HelpersPSR-4 autoload follows the namespace
PHP classOrder, OrderPlaced, OrderAlreadyDispatchedOrderManager, OrderHelperPSR-12: class names in StudlyCaps (PascalCase)
Eloquent modelOrderRecord in a persistence namespace when the domain differsOne Order model doing domain, SQL and JSONSee Data Persistence in Design
EventOrderPlaced, sales.order.placed.v1OrderEvent, OrderUpdatedPast tense, context-prefixed on the wire
Tableorders, order_linestbl_ord, t_dataIf legacy, map in one layer (database)
Enum valueplaced, cancelled, dispatched1, 2, 3Values appear in logs and UI; make them words
Exception / errorOrderAlreadyDispatchedInvalidStateExceptionThe 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."

gherkin
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 layerDomain-language formExample
AcceptanceGherkin Feature, Rule, Example, steps Given/When/Thenthe 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 statementsTestCustomerCanCancelAnOrderBeforeItIsDispatched
ArchitectureRules in language terms: "the domain layer has no jargon names"Pest arch(), Go go/parser test
ContractThe field names of the published languageService 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.

SurfaceDeveloper-word versionLanguage version
ResourcePOST /order/processPOST /orders (place)
OperationPUT /orders/42 {"status":3}POST /orders/42/cancellation
JSON fieldst, flag, custstate, customerId
Enum1,2,3"placed", "cancelled", "dispatched"
Error codeERR_409_STATEorder_already_dispatched
Error text"Invalid state transition""The order is already dispatched; request a return instead."
Button"Submit""Place order"
Event nameorder.updatedsales.order.cancelled.v1
GraphQLmutation updateOrdermutation 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.

sql
-- 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
);
SituationApproachWhere the mismatch lives
GreenfieldName tables and columns from the glossaryNowhere
Legacy, writablePersistence model (Eloquent OrderRecord, Go repository)One class or package per aggregate
Legacy, shared with another systemAnticorruption layer; views for readsThe ACL (Context Maps)
Data warehouseDimension names follow the reporting context's languageETL
MicroservicesDatabase 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.

PlacePractice
TicketsTitles are in domain sentences ("Customers cannot cancel after dispatch"), not "Fix status bug"
Slack / chatA pinned glossary link; correct the word, not the person; use the thread to propose a new term
DiagramsBoxes use glossary words only; label arrows with verbs or events
Pull requestsTemplate question: "Did a word change? Did you update the glossary?"
Docs in repodocs/glossary/<context>.md next to the code, or a Go/PHP data file used by a test
Event catalogueEach event lists its context, glossary term and version
OnboardingThe new hire's first task is to read the glossary and rewrite one confusing name
MeetingsThe 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 number

Multilingual 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 termEnglish identifierMeaning (Sales)Avoid
سفارشOrderThe customer's commitment to buyRequest, Purchase, Sefaresh
مشتریCustomerA person who can place OrdersUser, Client, Moshtari
ثبت سفارشplace / OrderPlacedThe moment of commitmentcreate, submit
لغو سفارشcancel / OrderCancelledWithdraw before dispatchdelete, remove
ارسالdispatch / ParcelDispatchedThe parcel leaves the warehousesend, ship (if Fulfilment prefers dispatch)
فاکتورInvoiceLegal document asking for paymentBill, Receipt
StrategyWhenProsCons
Translate to English identifiers, keep a bilingual glossaryDefault for most teamsSearchable, readable by any developer, one spellingNeeds care for terms with no clean English equivalent
Transliterate (sefaresh)A term truly has no English counterpart and is an official legal wordFaithful to the law or regulationSpelling variance; keep as a single constant, define it in the glossary
Persian identifiersRare, not recommendedClosest to the businessTooling, review and package ecosystems assume ASCII
Mixed (Persian in some places, English in others)NeverNoneSynonyms, 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.

SmellHow you noticeCostFix
SynonymsOrder, Purchase, Sale, Transaction appear in the same contextReviewers assume different conceptsPick one in the glossary; rename; add avoid-list
Technical names in the domainOrderManager, OrderHelper, OrderData, OrderDTOResponsibilities leak in, nobody knows where rules liveName 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 ruleName the actor: "support cancels the order"
Developers correct experts with jargon"You mean a one-to-many with a foreign key"The expert stops talkingLearn the expert's word; model it
One word, two meanings in one contextOrder means commitment and invoice basisBugs at the seamsSplit the context or the word (scoped)
Status ints and booleansstatus = 3, flag = trueLost rules, magic numbersNamed states, methods, events
CRUD verbsupdateOrder, saveOrderNo business intention capturedBusiness verbs and events
The glossary says X, code says YGlossary test failsDriftRename code or fix glossary in the same PR
Names only developers understandExpert cannot read test namesTests do not documentRewrite names as sentences
Translating in meetings"In the code we call it..."The knowledge crunch is anemicRename 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.

MeasureHowHealthy sign
New-hire comprehensionGive a new hire the glossary and one module; ask them to explain a rule aloud to an expertThey use the same words without hints
Glossary coverageA test lists exported domain types and checks each is in the glossary100 percent of domain types, zero banned suffixes
Expert readabilityAn expert reads test names and event namesFew corrections per session
Synonym countSearch the codebase for avoid-list wordsZero in the domain layer
Renames per quarterCount merged renames driven by business wordsNon-zero means the language is alive
Ticket titles in domain wordsSample 20 ticket titlesMost mention a glossary term
Translation incidentsBugs traced to wrong wordTrending down

Mechanics ​

The glossary as data Must-know ​

A glossary entry has a fixed shape so tools can check it.

FieldPurposeExample
contextWhich bounded context this meaning is valid insales
termThe identifier-level wordOrder
persianThe business term for bilingual teamsسفارش
meaningOne sentence, no jargonThe customer's commitment to buy
avoidBanned synonymsPurchase, Transaction
exampleA sentence using it"Alice placed an Order for two books."
sinceGlossary version that introduced it1.0
ownerWho answers questions about itSales product owner

Linting the language Important ​

CheckGo implementationPHP implementation
No banned suffixes in the domain packagego/parser walks identifiers (the test in Go)Pest arch()->not->toHaveSuffix('Manager')
Every exported domain type is in the glossaryA test compares AST type names with the glossary dataA Pest test reflecting classes in the Domain namespace
No import from another context's domaingo/parser imports test (Service Boundaries)Pest arch() not->toUse
Events end in past tenseRegex or a list of allowed suffixes (ed, Placed)Same, via a Pest dataset
No Util/Common packagesDirectory listing testNamespace test

Error and event names on the wire Good to know ​

ItemFormatExample
Event typecontext.aggregate.fact_in_past_tense.vNsales.order.cancelled.v1
Error codesnake_case glossary phraseorder_already_dispatched
Queue namecontext.consumer.eventbilling.invoice.order_placed
Metric labelGlossary nounorders_placed_total
Log keyGlossary fieldorder_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:

go
// 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:

go
// 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:

go
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:

go
// 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:

go
// 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:

go
// 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:

go
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 featureLanguage face it servesNotes
Package namesThe context nameOne lowercase word (Effective Go): sales, not salesService
package.TypeShort namessales.Order, not sales.SalesOrder (Code Review Comments on package names)
ConstructorsBusiness verbssales.Place where a rule exists; New otherwise
Unexported state, methodsThe rule's nameCancel, not SetStatus; invalid states are impossible
errors.Is with sentinel errorsError vocabularyMessages are sentences of the language
Table tests with name fieldsExamplest.Run(tc.name, ...) prints business sentences
go/parser + go/astLanguage lintBanned suffixes, glossary coverage
internal/Context privacyA context's words stay inside
Initialisms (ID, URL)StyleCode 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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
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
<?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
<?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 featureLanguage face it servesNotes
PSR-4 namespaces per moduleContext namesApp\Modules\Sales\... mirrors the glossary
PSR-12 class namingStudlyCaps classesStyle only; vocabulary is yours
Route names and URIsAPI languageorders.cancel, /orders/{order}/cancellation
$table, $primaryKey on EloquentMapping a legacy schemaKeep in a persistence model, not in the domain
Accessors and castsTranslating columns to wordsEnum casts give state words instead of ints
Exceptions rendered in bootstrap/app.phpError vocabularyMap OrderAlreadyDispatched to a 409 with the glossary code
Events (Dispatcher)Domain eventsNames in the past tense; wire names carry the context and version
Lang files (lang/fa/*.php)Persian UI wordingPersian text in translation files, English identifiers in code
Pest describe/it/arch()Test languageSentence-like names, jargon bans
Form RequestsInput vocabularyField names match the API language

Solving the classic problems ​

ProblemSolutionHowAdvantageCost
Five meanings of CustomerOne term per context, translatorsRename per context; ACLEach model is smallNeeds identity mapping
Code and speech disagreeRename code to the spoken wordRefactor with glossary version bumpOne languageShort-term churn
Legacy schema in cryptic namesPersistence model or viewOrderRecord, sales.orders viewDomain stays cleanOne more layer
Experts cannot read testsSentence test names, GherkinRewrite names; add Rules/ExamplesLiving documentationDiscipline
Terms drift unnoticedGlossary test in CIAST/Pest checksDrift fails the buildMaintenance of the test
Persian vs EnglishBilingual glossaryOne identifier per Persian termNo synonymsReview effort
Event names uselessPast-tense domain eventsOrderCancelled with reasonConsumers act without diffingEvent versioning
Jargon leaksNaming bansarch() and AST checksCleaner domain layerOccasional 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
BeforeAfterWhere
OrderManager.ProcessOrdersales.Place / Order::placeGo, PHP
OrderDatasales.OrderGo
Status intstate with placed, cancelled, dispatchedGo, PHP, SQL
HandleCancelOrder.Cancel(reason, now)Go
POST /order/update-statusPOST /orders/{id}/cancellationHTTP
ERR_409_STATEorder_already_dispatchedAPI
tbl_ord.stsales.orders.state view or OrderRecord::state()SQL, Eloquent
order.updatedsales.order.cancelled.v1Events

Choosing ​

SituationRecommendationExtra techniqueReason
New project, experts availableBuild the glossary in the first sessionsEvent Storming, Gherkin examplesThe words become the structure
Legacy system with cryptic namesDo not rename the schema first; wrap itViews, OrderRecord, ACLCheap, reversible
Two teams argue over "Order"Split into contextsContext mapMeanings are different, not wrong
Persian business, English codeBilingual glossary, English identifiersUI strings in lang filesOne identifier per concept
Experts have no timeShort weekly session on one flowRead test names aloudSmall steady corrections
Regulated vocabulary (law, tax)Use the official term, even if awkwardSingle constant, glossary noteCompliance beats elegance
MicroservicesOne language per service boundaryPublished language for eventsServices own words
Pure CRUD admin toolA light glossary is enoughNoneThe 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 language

See 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× ​

ScaleLanguage 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+.

bash
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 packages

Experiments:

  1. Open before/order.go. List every word that a sales manager would not say. Write the glossary rows you would add.
  2. In sales/order.go, rename Cancel to Delete. Run go test ./.... The tests fail on a name, which is the point: the test names are the business rules.
  3. Add a type OrderManager to the sales package. Run the tests. Expected: glossary_test.go fails with ends with banned word "Manager" and "is not in the glossary".
  4. Add {"sales", "Basket", "A cart that can be abandoned.", nil, "1.4"} to the glossary, then add type Basket struct{} to sales. The coverage test passes.
  5. Add a second context file billing/refund.go with a type named Refund. Observe how the glossary test only checks the three known contexts; add the context to the list and the glossary.
  6. 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 ​

BeliefReality
One ubiquitous language for the whole companyIt is ubiquitous within one bounded context; other contexts have their own
It is a glossary documentThe glossary records it; the language lives in speech, code and tests
Developers define itExperts and developers define it together; experts object to awkward terms, developers watch for ambiguity
Translating is fine if the mapping is documentedEvans: translation blunts communication; the mapping is lost and slow
Renaming is cosmeticA change in the language is a change in the model
OrderUpdated is a fine event nameEvents are specific past-tense facts: OrderCancelled
Technical names are neutralManager, Helper, Data hide responsibilities
Persian business and English code means mixing is fineUse one English identifier per Persian term, never mix
The database must match the language exactlyThe domain must; a mapping layer can hide a legacy schema
BDD means CucumberBDD is discovery, formulation, automation; tools are optional

Cheat sheet ​

TopicWhat to remember
DefinitionOne shared language of experts and developers, within one bounded context, in speech, code, tests, UI
ScopeNever company-wide; one word can differ across contexts
Source of truthThe model; a language change is a model change
BuildingKnowledge crunching, glossary, listening for ambiguity, Event Storming
EventsPast tense, glossary words, versioned: sales.order.cancelled.v1
CommandsImperative business verbs: PlaceOrder, CancelOrder
CodePackages and types named from the glossary; no Manager, Helper, Data in the domain
TestsSentences; Gherkin Rule/Example; Pest it; Go table-test names
API and UISame nouns, verbs and error sentences
DatabaseGreenfield: same words. Legacy: view or persistence model, never leak
Persian and EnglishBilingual glossary, English identifiers, Persian in UI strings
EvolvingRename with expand/contract; bump the glossary version
SmellsSynonyms, jargon leaks, "the system does X", developers correcting experts
MeasuringNew-hire test, glossary coverage test, expert readability
EnforcementGlossary lint in CI: banned suffixes, coverage

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Ubiquitous languageA language structured around the domain model and used by all team members within a bounded context
Bounded contextThe boundary within which a model and its language apply
Domain modelA system of abstractions describing selected aspects of a domain
Domain expertA person with deep business knowledge who works with developers on the model
Knowledge crunchingCollaborative digestion of domain information into a model through conversation
Model-driven designMaking the code reflect the model literally so names and structure match
Hands-on modelerA modeler who also touches the code, so models are implementable
GlossaryA versioned list of terms, meanings and avoided synonyms
Domain eventA past-tense record of something that happened in the domain
CommandAn imperative business request such as CancelOrder
Published languageA documented, versioned shared format between contexts, such as an event schema
Anticorruption layerA translator that protects one context's model from another's
TranslatorCode that converts one context's terms into another's
Synonym smellTwo words for one concept inside one context
Jargon leakTechnical names such as Manager or Data appearing in the domain layer
GherkinThe Given/When/Then language for executable specifications
BDDBehaviour-driven development: discovery, formulation, automation of examples
Living documentationDocumentation checked automatically against the system's behaviour
Persistence modelA class that maps the domain to storage, absorbing legacy names
Expand/contractA zero-downtime rename: add the new, dual-write, migrate, drop the old
Event StormingA workshop that discovers events and language on a wall of stickies
EloquentLaravel's ORM
PestA PHP testing framework with it, describe and arch()
Table testA Go test running one function over rows of named cases

References ​

Built by Morteza Negahi