Domain driven design

From bfollington/terma · View interactive version

Domain driven design is an AI agent skill from the GitHub repository bfollington/terma. This skill should be used whenever domain modeling is taking place. It provides specialized guidance for type-driven and data-driven design based on Rich Hickey and Scott Wlaschin's principles. The skill helps contextualize current modeling within the existing domain model, identifies inconsistencie

How to use this skill

Skill file

Domain-Driven Design

Overview

This skill provides guidance for domain modeling based on Rich Hickey's data-oriented design principles and Scott Wlaschin's type-driven design approach. Focus on building systems that make illegal states unrepresentable, prioritize data and transformations over objects and methods, and establish a ubiquitous language that bridges technical implementation and business domain.

Core Principles

Rich Hickey's Data-Oriented Design

Simplicity over Ease

Data is King

Value of Values

Decomplecting

Scott Wlaschin's Type-Driven Design

Make Illegal States Unrepresentable

Domain Modeling Made Functional

Railway-Oriented Programming

Types as Documentation

DDD Building Blocks

Entities vs Value Objects

Entities are defined by identity, not attributes:

Value Objects are defined entirely by attributes:

Decision Guide:

Aggregates and Aggregate Roots

Aggregate: A cluster of entities and value objects treated as a single unit for data changes.

Aggregate Root: The single entity through which all external access to the aggregate must pass.

Purpose:

Rules:

When NOT to create an aggregate:

Bounded Contexts

Definition: An explicit boundary within which a domain model applies.

Purpose:

Key Insight: Ubiquitous language is only ubiquitous within a context. "Customer" in Sales context may be different from "Customer" in Shipping context.

When modeling:

Domain Events

Definition: Something important that happened in the domain.

Characteristics:

Uses:

Repositories

Purpose: Provide illusion of an in-memory collection of aggregates, abstracting persistence.

Characteristics:

Pattern: Application layer uses repository to get/save aggregates; domain layer remains pure.

Domain Modeling Workflow

1. Discover the Ubiquitous Language

Start by identifying the domain concepts, using terminology from domain experts:

Action Items:

Output Format:

Create a glossary section documenting each term:

**Term** (Type: Entity/ValueObject/Event/Command)
- Definition: [Clear, domain-expert-approved definition]
- Examples: [Concrete examples]
- Invariants: [Rules that must always hold]

2. Analyze the Existing Domain Model

Before making changes, understand the current state:

Exploration Steps:

Questions to Answer:

3. Identify Inconsistencies and Smells

Common problems to surface:

Naming Inconsistencies

Structural Problems

Complected Concerns

Missing Concepts

4. Design the Domain Model

Apply type-driven and data-driven principles:

Data Modeling:

Type Design:

```

type PaymentStatus =

| Pending

| Approved { approvedAt: Timestamp, approvedBy: UserId }

| Rejected { rejectedAt: Timestamp, reason: string }

```

```

type EmailAddress = EmailAddress of string // with validation

type Money = { amount: Decimal, currency: Currency }

```

Workflow Modeling:

```

ValidateInput → ExecuteBusinessLogic → HandleResult → Persist → Notify

```

5. Build and Maintain Ubiquitous Language

Consistency Rules:

Code Conventions:

Documentation:

6. Visualize the Domain Model

Use diagrams to communicate domain structure and relationships:

Mermaid for Relationships:

classDiagram
    Order --> Customer
    Order --> OrderLine
    OrderLine --> Product
    Order --> PaymentStatus

    class Order {
        +OrderId id
        +CustomerId customerId
        +List~OrderLine~ lines
        +PaymentStatus status
    }

    class PaymentStatus {
        <<enumeration>>
        Pending
        Approved
        Rejected
    }

Mermaid for Workflows:

graph LR
    A[Receive Order] --> B{Valid?}
    B -->|Yes| C[Calculate Total]
    B -->|No| D[Return Validation Error]
    C --> E[Process Payment]
    E --> F{Payment Success?}
    F -->|Yes| G[Fulfill Order]
    F -->|No| H[Cancel Order]

Mermaid for State Transitions:

stateDiagram-v2
    [*] --> Draft
    Draft --> Submitted: submit()
    Submitted --> Approved: approve()
    Submitted --> Rejected: reject()
    Approved --> Fulfilled: fulfill()
    Fulfilled --> [*]
    Rejected --> [*]

Graphviz/DOT for Complex Relationships:

digraph domain {
    rankdir=LR;
    node [shape=box];

    Customer -> Order [label="places"];
    Order -> OrderLine [label="contains"];
    OrderLine -> Product [label="references"];
    Order -> Payment [label="requires"];
    Payment -> PaymentMethod [label="uses"];
}

ASCII for Quick Sketches:

Customer
  └─> Order (1:N)
       ├─> OrderLine (1:N)
       │    └─> Product
       └─> Payment (1:1)
            └─> PaymentMethod

When to Use Each:

Domain Modeling Anti-Patterns

Anemic Domain Model

Entity Services Anti-Pattern

Primitive Obsession

Accidental Complexity

Hidden Temporal Coupling

Boolean Blindness

Contextualizing Within Existing Models

When adding to or changing an existing domain model:

  1. Map Current State: Document existing types, relationships, and patterns
  2. Identify Affected Concepts: Which existing concepts does this change touch?
  3. Check Consistency: Does new design follow existing patterns? If not, why?
  4. Assess Impact: What breaks if we make this change?
  5. Migration Path: How do we evolve from current to desired state?
  6. Update Ubiquitous Language: Ensure all usage points are updated
  7. Visualize Before/After: Create diagrams showing current and proposed models

Key Questions:

Checklist for Domain Modeling

Before completing domain modeling work:

Language & Communication:

Type Design:

Domain Logic:

Aggregates & Boundaries:

Consistency & Integration:

Documentation:

Resources

references/

This skill includes reference documentation for deeper exploration:

Load these references when deeper context is needed on specific principles or patterns.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.