# Domain Driven Design (DDD)

Domain Driven Design (DDD) is an approach to software development that centers the design on the core domain and domain logic. It relies on a close collaboration between technical experts (developers) and domain experts (business owners).

## 1. Strategic Design

Strategic design deals with high-level architecture and team organization.

### Ubiquitous Language
A common, rigorous language shared by developers and domain experts. This language is used in all communication and in the code itself (class names, method names).
*   **Goal:** Eliminate translation cost between "Business Speak" and "Tech Speak".

### Bounded Contexts
A specific boundary within which a domain model is defined and applicable. A "User" in the *Sales Context* might be different from a "User" in the *Support Context*.
*   **Goal:** Prevent a single, monolithic model that tries to do everything and becomes unmanageable.

## 2. Tactical Design (Building Blocks)

Tactical design provides a set of patterns to create the domain model code.

### Entities
Objects that are defined by their **identity**, not just their attributes. Even if their attributes change, they remain the same object.
*   **Example:** A `User` (defined by `userId`). If a user changes their name, they are still the same user.

### Value Objects
Objects that are defined by their **attributes**. They have no identity and are typically immutable.
*   **Example:** An `Address` or `Money`. If you change the street name, it is effectively a new address.

### Aggregates
A cluster of domain objects that can be treated as a single unit. An aggregate has a **Root Entity** (Aggregate Root). External objects can only hold references to the root.
*   **Example:** An `Order` (Root) containing `LineItems`. You shouldn't access a `LineItem` directly without going through the `Order`.

### Repositories
Mechanisms for encapsulating storage, retrieval, and search behavior which emulates a collection of objects.
*   **Rule:** Repositories should only return **Aggregates**.

### Domain Events
Something that happened in the domain that domain experts care about.
*   **Example:** `OrderPlaced`, `PaymentFailed`.

## 3. Anemic vs. Rich Domain Model

*   **Anemic Domain Model:** Entities are just data holders (getters/setters) with no logic. Logic lives in "Service" classes. (Often considered an anti-pattern in DDD).
*   **Rich Domain Model:** Entities contain both data and the business logic that operates on that data.

[[programming/clean-architecture]]
[[programming/hexagonal-architecture]]
[[programming/microservices-architecture]]