コンテンツにスキップ

What is DDD? How a domain, a domain object, and a domain model differ

Domain-driven design (DDD) is an approach to design that builds a program around the domain that expresses the application’s business rules.

When you start learning DDD, the similar words “domain,” “domain object,” and “domain model” appear first, and it is easy to be unsure where to begin.

I initially thought of a domain as something at the level of an entity, such as a “user domain” or a “product domain.” To untangle that mix-up, this article explains the real-world work and rules separately from the objects that represent them in a program.

As an introduction to DDD, this article sorts out the following four ideas in plain terms, with concrete examples from an online store and a social network.

A domain is a term for “what this application is for.”

It is not about variable names or class names inside a program. It refers to the real-world work and events that the application is trying to reproduce.

When you build an online store application, the domain is “selling and buying products online.”

Imagine the flow a customer actually follows when using the application.

flowchart LR
    A[Choose a product] --> B[Add to cart]
    B --> C[Place an order]
    C --> D[Pay]
    D --> E[Arrives at home]

This whole sequence is the domain of the online store. It refers to what actually happens as a store, not to program operations such as “display a screen” or “press a button.”

A domain contains various “elements” and “rules”

Section titled “A domain contains various “elements” and “rules””

A domain includes various elements, such as users, products, orders, payments, and delivery. Each one has data and rules.

Examples of dataExamples of rules
Product name, price, stock quantity, descriptionThe price cannot be 0 yen or less
A product with a stock quantity of 0 cannot be purchased
Examples of dataExamples of rules
Order date and time, products purchased, quantity, total amountAn order cannot be placed when there is not enough stock
An order that has already been shipped cannot be canceled
Examples of dataExamples of rules
Name, phone number, email address, addressAt least one of a phone number or an email address is required
The email address must be in a format that includes @
Examples of dataExamples of rules
Payment method, payment amount, payment date and timeOnly an amount equal to the order amount can be paid
An order that has already been paid cannot be paid again

These sets of “data” and “rules” are what a domain is made of. A domain includes not only “what the product name is,” but also the real store’s rules, such as “it cannot be sold when it is out of stock.”

For a social networking application, the domain is “connecting with people on a social network.”

ElementExamples of dataExamples of rules
PostBody, image, posted at, authorA post cannot be created when both the body and the image are empty
FollowThe person who follows, the person who is followedYou cannot follow yourself
UserDisplay name, profile imageThe display name cannot be empty

An online store and a social network have different domains, so the data and rules they need also change. A delivery application centers on elements such as “courier,” “delivery destination,” and “delivery time.” A reservation application centers on elements such as “reservation slot” and “cancellation deadline.”

Up to this point, the domain has been discussed apart from the program. From the next section, we put it into a program.

A domain object is an object that expresses an element of the domain in a program.

Meaning
DomainThe real world (store rules, the flow of an order, and so on)
Domain objectAn element of the domain expressed as a component of a program (User, Order, and so on)

A domain object is what you get by writing each element in the domain, such as “user,” “product,” or “order,” into a program one by one.

Representative domain objects are entities, which determine identity by an ID, and value objects, which keep a value and its rules together. The entry point for saving and retrieving domain objects is explained in repositories.

The following is a picture of putting the domain elements covered so far into a program.

flowchart LR
    subgraph domain["Domain (the real store's world)"]
        D1["Product … name, price, stock, conditions under which it cannot be sold"]
        D2["Order … when, what, and how many were bought"]
        D3["User … contact details, registration rules"]
    end
    subgraph objects["Domain objects"]
        O1[Product]
        O2[Order]
        O3[User]
    end
    D1 --> O1
    D2 --> O2
    D3 --> O3

For each domain element (a product, an order, a user, and so on), you write the data and the rules together in the program. That grouping is a domain object.

Domain objectThe real-world thing it representsExamples of rules it holds
UserA customerAt least one of the contact methods is required
ProductA productThe price cannot be 0 yen or less
OrderAn orderAn order cannot be placed when there is not enough stock
PaymentA paymentOnly an amount equal to the order amount can be paid

A domain object holds the following two things together.

  1. Data: information the element holds, such as a name, a price, or a stock quantity
  2. Behavior: operations and checks that uphold the rules (such as “place an order” or “cancel”)

The point is that it is a program component that holds the rules as well, not a box that only stores data (something like a database row).

A domain object for a user looks roughly like this. In the sample, the address, which is not directly related to the contact-details rule, is omitted, and the checks are performed when the object is created.

classDiagram
    class User {
        Name
        Phone number
        Email address
    }
    note for User "Check the contact details and the email format at creation time"

Written as a program, the idea looks like the following (the language does not matter).

class User(
val name: String,
val phoneNumber: String?,
val email: String?,
) {
init {
// Rule: at least one of the contact methods is required
require(!phoneNumber.isNullOrBlank() || !email.isNullOrBlank()) {
"At least one of a phone number or an email address is required"
}
// Rule: check the email address format
// A simplified introductory example that only looks at whether @ is present
if (!email.isNullOrBlank()) {
require(email.contains("@")) {
"The email address format is not correct"
}
}
}
}

Here, data (a name, a phone number, and so on) and rules (the conditions under which it can be saved) are gathered into one User. The email format check is a simplified introductory example that only checks that @ is included.

An order follows the same idea.

classDiagram
    class Order {
        Order date and time
        Products purchased
        Quantity
        Total amount
        Whether it has been shipped
        Place an order()
        Cancel()
    }

Operations such as “place an order” and “cancel” are also written inside the domain object. The rule “an order can be placed only under conditions like these” then stays entirely inside Order.

Database table design is easy to mix up with this, but the roles differ a little.

Role
Database tableThe shape used to store data, and the constraints upheld when storing it (columns, types, uniqueness, CHECK constraints, and so on)
Domain objectA representation in the program that includes rules and operations in addition to the data

For example, the rule on a users table that “at least one of a phone number or an email address is required” can also be expressed with a database CHECK constraint. In PostgreSQL, you can define a CHECK constraint that references multiple columns.

Giving the domain object this rule as well prevents an invalid state before the data is saved to the database, and lets you express the business meaning “at least one of a phone number or an email address is required” in code, as the creation of User and as its operations. You can use the two together: database constraints protect consistency at save time, and the domain object protects the validity of state and operations inside the program.

Processing in an API or on a screen becomes the side that uses domain objects.

flowchart LR
    subgraph api["Screens and API"]
        A1[User registration API]
        A2[Email change API]
        A3[Order API]
    end
    subgraph dom["Domain objects"]
        U["User (with rules)"]
        O["Order (with rules)"]
    end
    A1 -->|uses| U
    A2 -->|uses| U
    A3 -->|uses| O

There is no need to write the same check for every API. The rules are upheld simply by leaving them to the domain object.

Once the individual components are clear, the next section looks at the big picture: an abstraction of the domain knowledge.

A domain model is an abstraction of domain knowledge. It organizes concepts, rules, and the relationships among them. An overall design that combines domain objects is also one way of expressing it.

Meaning
Domain objectAn individual program component that represents an element of the domain
Domain modelThe whole picture that abstracts domain knowledge (what exists, and how those things relate). A design that combines domain objects is also one way of expressing it

In a Lego analogy, each domain object is one brick, and the blueprint of the finished product assembled from those bricks is one form that represents the domain model.

Concrete example: the domain model of an online store

Section titled “Concrete example: the domain model of an online store”

Expressed as the relationships among domain objects, the domain model of an online store is roughly the whole picture below.

classDiagram
    class User {
        Customer information and registration rules
    }
    class Product {
        Product information and sales rules
    }
    class Order {
        Order information and rules for ordering and cancellation
    }
    class Payment {
        Payment information and payment rules
    }
    User "1" --> "*" Order : Place an order
    Order "*" --> "*" Product : includes
    Order "1" --> "1" Payment : is paid

The many-to-many relationship between an order and products is a simplified diagram that omits order lines. The one-to-one relationship between an order and a payment is drawn as a simplification that does not consider installment payments and similar cases.

What a domain model shows is not only the list of elements, but also the relationships between elements. Connections such as “an order is always tied to a user” and “a payment is made for an order” are part of the domain model too.

When you organize a domain model, make the following two points explicit.

  1. What exists: the elements that appear in the domain, such as users, products, and orders (that is, domain objects)
  2. How they relate: an order has a user, a payment is made for an order, and so on

The three terms that have appeared so far can be summed up together.

flowchart LR
  D["Domain<br/>The work of an online store"]
  DM["Domain model<br/>Whole picture that abstracts the knowledge"]
  DO["Domain objects<br/>User, Product, Order …"]
  D -->|Abstract real-world knowledge| DM
  DO -->|A combination of components is also one expression| DM
  • Domain: real-world work and rules
  • Domain object: an individual program component that represents an element of the domain
  • Domain model: an abstraction of domain knowledge. A design that combines domain objects is also one way of expressing it

If you build the domain objects properly and also organize their relationships as an expression of the domain model, the program as a whole becomes easier to follow. Domain-driven design, explained in the next section, is exactly this approach: “build the program around domain objects.”

Domain-driven design (DDD) is a way of designing that treats the application’s rules as important and builds the whole program into a shape where those rules are easy to uphold.

It may sound difficult, but what it does is simple.

Write the rules in one place, and only use them from other places.

This is the basic idea of domain-driven design.

Suppose user information has the following rule.

“At least one of a phone number or an email address is always registered.”

If the rules about a user are written separately for each API, it looks like this.

flowchart TB
    subgraph scattered["Write the rules in many places"]
        API1[User registration API] --> C1[Contact check]
        API2[Email change API] --> C2[Contact check]
        API3[Phone number change API] --> C3[Contact check]
    end

The same check is needed many times, and it becomes easy to forget to write it. That causes bugs such as “the check was left out only in the change-email API.”

Prepare the data and rules about a user as a User domain object. When a value is put into it, it raises an error if the value violates a rule.

flowchart TB
    subgraph centralized["Keep the rules in one place"]
        API1[User registration API] --> User
        API2[Email change API] --> User
        API3[Phone number change API] --> User
        User["User domain object<br/>Contact rules kept in one place"]
    end

For example, trying to save a state in which both the phone number and the email address are empty raises an error such as “At least one of a phone number or an email address is required.”

Whether the user is being registered or changed, the same rule is always used. You can avoid forgetting to write the check.

In this way of working, you build around domain objects (program components that express the application’s rules).

Before the appearance of the screen or the shape of the API, you make the rules of “what is correct in this application” explicit as domain objects, and you make those objects the foundation of the program. That is why it is called design built around the domain: domain-driven design.

DDD is an approach to design that places the application’s business rules (the domain) at the center of the program and gathers the same rule in one place, in a domain object, rather than writing it in many places. See What is domain-driven design? for details.

What is the difference between a domain and a domain object?

Section titled “What is the difference between a domain and a domain object?”

A domain is about the real world (a store’s order rules, the rules of inventory, and so on). A domain object expresses that as a program component such as User or Order. See What is a domain? and What is a domain object? for details.

What is the difference between a domain model and a domain object?

Section titled “What is the difference between a domain model and a domain object?”

A domain object is an individual component. A domain model is an abstraction of domain knowledge. It is the whole picture, including concepts, rules, and relationships, and a blueprint that combines domain objects is also one way of expressing it. In Lego terms, the bricks are domain objects, and the design of the assembled finished product corresponds to that expression.

How does a domain object differ from database table design?

Section titled “How does a domain object differ from database table design?”

Table design decides the storage format of the data and the constraints applied when it is saved. A rule such as “at least one of a phone number or an email address is required” can also be expressed with a database CHECK constraint. A domain object is a representation in the program that also holds rules and operations in addition to the data. The same rule can also be applied before saving to the database, so the business meaning can be expressed in code. See How this differs from database design for details.

Yes. The only point worth remembering as a first step is “do not write the same rule in many places. Keep it in one place and reuse it.” You do not need to introduce every technique of large-scale DDD at once.

  • Domain: the real-world work and events the application is trying to reproduce. A collection of elements such as products, orders, and users, together with their data and rules
  • Domain object: an individual component that represents an element of the domain (User, Order, and so on). It holds data and behavior (rules) as a set
  • Domain model: an abstraction of domain knowledge. A design that combines domain objects is also one way of expressing it
  • Domain-driven design: a way of designing that builds the whole program, around domain objects, into a shape where those rules are easy to uphold

The point worth remembering as a first step is “do not write the same rule in many places. Keep it in one place and reuse it.” That alone makes the program easier to read, and makes bugs easier to reduce.