MCP HubMCP Hub
SKILL·1D11F3

domain-driven-design

wondelai
Обновлено 20 days ago
5 просмотров
2,065
213
2,065
Посмотреть на GitHub
Дизайнaidesign

О программе

Этот навык помогает разработчикам моделировать программное обеспечение вокруг бизнес-доменов, используя концепции DDD, такие как ограниченные контексты, агрегаты и единый язык. Он активируется при обсуждении предметного моделирования, разделения монолитов, определения границ сервисов или согласования кода с бизнес-процессами. Фреймворк охватывает стратегические паттерны проектирования, включая сущности и объекты-значения, доменные события и стратегии контекстного маппинга.

Быстрая установка

Claude Code

Рекомендуется
Основной
npx skills add wondelai/skills -a claude-code
Команда плагинаАльтернативный
/plugin add https://github.com/wondelai/skills
Git клонированиеАльтернативный
git clone https://github.com/wondelai/skills.git ~/.claude/skills/domain-driven-design

Скопируйте и вставьте эту команду в Claude Code для установки этого навыка

Документация

Domain-Driven Design Framework

Framework for tackling software complexity by modeling code around the business domain. The greatest risk in software is not technical failure -- it is building a model that does not reflect how the business actually works.

Core Principle

The model is the code; the code is the model. Software should embody a deep, shared understanding of the business domain. When domain experts and developers speak the same language and that language is directly expressed in the codebase, complexity becomes manageable and the system evolves gracefully as the business changes.

Scoring

Goal: 10/10. Score a domain model by awarding 1 point per satisfied row of the Quick Diagnostic (7 rows) plus up to 3 points for depth: +1 if the Core Domain has a genuinely rich model (not just CRUD), +1 if invariants live inside aggregates rather than in services, +1 if the ubiquitous language is consistent across conversation, code, and tests. Bands: 9-10 = expert-readable names, explicit context boundaries with ACLs, small aggregates, behavior-rich entities, events for cross-aggregate flow, an identified Core Domain; 5-6 = some domain language but leaky boundaries or anemic objects; <=3 = technical naming, one model for everything, logic scattered in services. Report the score and the specific diagnostic rows failing.

Framework

1. Ubiquitous Language

Core concept: A shared, rigorous language between developers and domain experts, used consistently in conversation, documentation, and code. When the language changes, the code changes -- and awkward naming in code feeds back into refining the language.

Why it works: Ambiguity is the root cause of most modeling failures. When a developer says "order" and an expert means "purchase request," bugs are inevitable; a ubiquitous language forces every name in code to map to a concept the business recognizes and validates.

Key insights:

  • The language emerges from deep collaboration, not a glossary bolted on after the fact
  • If a concept is hard to name, the model is likely wrong -- naming difficulty is a design signal
  • Technical jargon (DataProcessor vs. ClaimAdjudicator) hides domain logic from the experts who could correct it
  • Different bounded contexts may use the same word with different meanings -- and that is fine

Code applications:

ContextPatternExample
Class/method namingName after domain concepts and verbsLoanApplication, policy.underwrite() -- not RequestHandler, process()
Module structureOrganize by domain conceptshipping/, billing/ -- not controllers/, services/
Code reviewReject technical-only namesFlag Manager, Helper, Processor, Utils as naming smells

See: references/ubiquitous-language.md when running modeling sessions or maintaining a glossary -- covers how the language evolves and feeds back into code.

2. Bounded Contexts and Context Mapping

Core concept: A bounded context is an explicit boundary within which a particular domain model applies. The same word ("Customer") can mean different things in different contexts; context maps define the relationships and translation strategies between them.

Why it works: Large systems that try to maintain a single unified model inevitably collapse into inconsistency. Bounded contexts accept that different parts of the business need different models; context maps manage the integration between them.

Key insights:

  • A bounded context is not a microservice -- it is a linguistic and model boundary that may contain multiple services
  • Context boundaries often align with team boundaries (Conway's Law)
  • The nine context mapping patterns describe political and technical relationships between teams
  • Anti-Corruption Layer is the most important defensive pattern -- never let a foreign model leak into your core domain
  • Shared Kernel couples two teams; keep it small and explicitly governed
  • Start by mapping what exists (Big Ball of Mud), then define target boundaries

Code applications:

ContextPatternExample
Service integrationAnti-Corruption LayerTranslate external API responses into your domain objects at the boundary
Legacy migrationConformist / ACLWrap the legacy system behind an adapter that speaks your domain language
API designOpen Host Service + Published LanguageExpose a well-documented REST API with a canonical schema

See: references/bounded-contexts.md for the nine mapping patterns and integration strategies.

3. Entities, Value Objects, and Aggregates

Core concept: Entities have identity that persists across state changes. Value Objects are defined entirely by their attributes and are immutable. Aggregates are clusters of entities and value objects with a single root that enforces consistency boundaries.

Why it works: Without these distinctions, everything becomes a mutable, identity-bearing object -- tangled state, inconsistent updates, fragile concurrency. Aggregates draw the line: everything inside is guaranteed consistent; everything outside is eventually consistent.

Key insights:

  • Entity test: "Am I the same thing even if all my attributes change?" (a person changes name and address -- still the same person)
  • Value Object test: "Am I defined only by my attributes?" (any $10 bill is interchangeable with another)
  • Most things should be Value Objects, not Entities -- prefer immutability
  • Keep aggregates small (one root plus a minimal cluster); reference other aggregates by ID, not object reference
  • Immediate consistency only within an aggregate; design for eventual consistency between aggregates

Code applications:

ContextPatternExample
Identity trackingEntity with IDOrder identified by orderId, survives state changes
Immutable attributesValue ObjectAddress(street, city, zip) -- replace, never mutate
Consistency boundaryAggregate RootOrder is root; OrderLine items exist only through it
Concurrency controlOptimistic locking on rootVersion field on Order; conflict if two edits race

See: references/building-blocks.md for aggregate design rules and consistency boundaries.

4. Domain Events

Core concept: A domain event captures something that happened in the domain that experts care about, named in past tense (OrderPlaced, PaymentReceived) -- a fact that has already occurred.

Why it works: Domain events decouple cause from effect. When OrderPlaced is published, shipping, billing, and notifications each react independently without the ordering context knowing about them -- less coupling, eventual consistency, a natural audit trail.

Key insights:

  • Events are immutable facts -- once published, they cannot be changed or retracted
  • Domain events are internal to a bounded context; integration events cross boundaries
  • Events enable temporal decoupling: the producer does not wait for the consumer
  • Event sourcing stores the full event history as the source of truth, deriving current state by replay
  • Not every state change deserves an event -- only publish what the domain cares about

Code applications:

ContextPatternExample
State transitionsRaise event on domain actionorder.place() raises OrderPlaced
Cross-context integrationPublish integration eventOrderPlaced triggers ShippingLabelRequested in shipping context
Eventual consistencyAsync event handlersInventory handler updates stock asynchronously after OrderPlaced

See: references/domain-events.md for event naming, event sourcing, and integration events.

5. Repositories and Factories

Core concept: Repositories provide the illusion of an in-memory collection of domain objects, hiding persistence. Factories encapsulate complex creation logic so aggregates are always born in a valid state.

Why it works: When persistence and assembly details leak into domain code, every storage change ripples through business rules and aggregates can be constructed in half-valid states. Repositories confine SQL/ORM concerns to infrastructure so the domain stays testable in memory; factories make the only path to an aggregate one that enforces its invariants, so an invalid instance is unrepresentable.

Key insights:

  • The Repository interface belongs in the domain layer; its implementation belongs in infrastructure
  • Repository methods speak the ubiquitous language: findPendingOrders(), not getByStatusCode(3)
  • Collection-oriented repositories mimic add/remove; persistence-oriented ones use save
  • Factories are warranted for complex rules or multi-part assembly; a two-field Value Object just needs a constructor
  • The Specification pattern encapsulates query criteria as domain objects: OverdueInvoiceSpecification

Code applications:

ContextPatternExample
Data access abstractionRepository interfaceOrderRepository.findByCustomer(customerId) in domain; PostgresOrderRepository in infrastructure
Complex creationFactory methodOrder.createFromQuote(quote) validates and assembles from a Quote aggregate
Query encapsulationSpecificationspec = OverdueBy(days=30); repo.findMatching(spec)

See: references/repositories-factories.md for Repository, Factory, and Specification patterns.

6. Strategic Design and Distillation

Core concept: Not all parts of a system are equally important. Strategic design identifies the Core Domain -- where competitive advantage lives -- and distinguishes it from Supporting Subdomains (necessary, not differentiating) and Generic Subdomains (commodity).

Why it works: Applying the same rigor everywhere spreads your best talent thin and over-engineers commodity functionality. Identifying the Core Domain concentrates the best developers and deepest modeling where they matter most.

Key insights:

  • Core Domain: invest your best people and deepest modeling; Supporting: build, but don't over-engineer; Generic (auth, email, payments): buy or use open-source
  • Distillation extracts and highlights the Core Domain from surrounding complexity
  • A Domain Vision Statement is a one-page description of the Core Domain's value proposition
  • Revisit what is "core" as the business evolves -- today's differentiator may become tomorrow's commodity

Code applications:

ContextPatternExample
Build vs. buyClassify subdomain typeBuild custom pricing engine (core); use Stripe for payments (generic)
Team allocationBest developers on Core DomainSeniors model underwriting rules; juniors integrate the email service
Code organizationSeparate core from genericdomain/pricing/ (deep model) vs. infrastructure/email/ (thin adapter)

See: references/strategic-design.md when deciding where to invest engineering effort -- subdomain classification and distillation techniques.

Common Mistakes

MistakeWhy It FailsFix
Technical names instead of domain languageLogic hidden behind DataManager; experts can't validate the modelRename to domain terms (ClaimAdjudicator); if no domain term exists, the concept may be wrong
One model to rule them allA single Customer class for billing, shipping, and marketing becomes bloated and contradictoryBounded contexts: each gets its own Customer with only the attributes it needs
Giant aggregatesConcurrency conflicts, slow loads, transactional bottlenecksKeep aggregates small; reference by ID; eventual consistency between them
Anemic domain modelObjects are data bags; rules scatter across services and duplicateMove behavior into entities and value objects; services orchestrate only
No Anti-Corruption LayerForeign models leak in; code couples to external schemasWrap every external system behind a translation layer
Bounded context = microservicePremature extraction; distributed complexity without benefitA context is a model boundary, not a deployment unit; start with modules in a monolith
Skipping domain expertsDevelopers invent a model that doesn't match reality; expensive reworkRegular modeling sessions until experts say "yes, that is how it works"

Quick Diagnostic

QuestionIf NoAction
Can a domain expert read your class names and understand them?Technical jargon hides the modelRename classes, methods, events to ubiquitous language
Are bounded context boundaries explicitly defined?Models bleed; same term means different thingsDraw a context map; define boundaries and translations
Are aggregates small (one root + minimal cluster)?Slow loads, concurrency issuesSplit aggregates; reference by ID; accept eventual consistency
Do domain objects contain behavior, not just data?Anemic model; logic scattered in servicesMove business rules into entities and value objects
Are domain events used for cross-aggregate communication?Tight coupling, synchronous chainsIntroduce events; let aggregates react asynchronously
Is there an Anti-Corruption Layer at every external integration?Foreign models pollute your domainAdd a translation layer at each boundary
Have you identified which subdomain is core?Best talent spread thinClassify subdomains; focus deep modeling on the Core Domain

Further Reading

For the complete methodology, patterns, and deeper insights:

About the Author

Eric Evans is a software design consultant and the originator of Domain-Driven Design, developed through work on large-scale systems in finance, insurance, and logistics. His 2003 book Domain-Driven Design: Tackling Complexity in the Heart of Software is one of the most influential software architecture books ever written, and he continues to evolve DDD through his consultancy, Domain Language.

GitHub репозиторий

wondelai/skills
Путь: plugins/code-craftsmanship/skills/domain-driven-design
0
agent-skillsai-skillsbusinessclaude-codeclaude-code-marketplaceclaude-code-plugin
FAQ

Часто задаваемые вопросы

Что такое Skill domain-driven-design?

domain-driven-design — это Claude Skill от wondelai. Skills объединяют инструкции и ресурсы, которые Claude загружает по мере необходимости, чтобы выполнять задачи, связанные с domain-driven-design, без дополнительных запросов.

Как установить domain-driven-design?

Используйте команды установки на этой странице: добавьте domain-driven-design в Claude Code как плагин или клонируйте репозиторий в каталог skills, затем перезапустите Claude, чтобы загрузить Skill.

К какой категории относится domain-driven-design?

domain-driven-design относится к категории Дизайн.

Можно ли использовать domain-driven-design бесплатно?

Да. domain-driven-design размещён на AIMCP и доступен для бесплатной установки.

Похожие навыки

executing-plans
Дизайн

Используйте навык executing-plans, когда у вас есть полный план реализации для выполнения контролируемыми партиями с контрольными точками проверки. Он загружает и критически анализирует план, затем выполняет задачи небольшими партиями (по умолчанию 3 задачи), сообщая о прогрессе между каждой партией для проверки архитектором. Это обеспечивает систематическую реализацию со встроенными контрольными точками проверки качества.

Просмотреть навык
requesting-code-review
Дизайн

Этот навык запускает суб-агента для ревью кода, который анализирует изменения в коде на соответствие требованиям перед дальнейшими действиями. Его следует использовать после завершения задач, реализации крупных функций или перед слиянием с основной веткой. Ревью помогает выявить проблемы на ранней стадии, сравнивая текущую реализацию с исходным планом.

Просмотреть навык
connect-mcp-server
Дизайн

Этот навык предоставляет разработчикам подробное руководство по подключению серверов MCP к Claude Code с использованием транспортов HTTP, stdio или SSE. Он охватывает установку, конфигурацию, аутентификацию и безопасность для интеграции внешних сервисов, таких как GitHub, Notion и пользовательские API. Используйте его при настройке интеграций MCP, конфигурации внешних инструментов или работе с Model Context Protocol от Claude.

Просмотреть навык
web-cli-teleport
Дизайн

Этот навык помогает разработчикам выбирать между веб-интерфейсом Claude Code и CLI на основе анализа задачи, а также обеспечивает бесшовное перемещение сессий между этими средами. Он оптимизирует рабочий процесс, управляя состоянием и контекстом сессии при переключении между веб-интерфейсом, CLI или мобильным приложением. Используйте его для сложных проектов, требующих различных инструментов на разных этапах работы.

Просмотреть навык