Logo de Architecture Domain Driven Design

Architecture Domain Driven Design

Comunidade
j4flmao
architecture-domain-driven-design

Use this skill when the user says 'DDD', 'domain-driven design', 'bounded context', 'aggregate', 'aggregate root', 'ubiquitous language', 'context map', 'anti-corruption layer', 'event storming', 'value object'. Applies strategic DDD (subdomains, bounded contexts, context maps) and tactical DDD (aggregates, entities, value objects, domain events, repositories) to model complex business logic. Do NOT use for: simple CRUD apps where DDD adds ceremony, service decomposition mechanics (architecture/system-design/microservices-patterns), or layering/folder structure only (backend/universal/clean-architecture).

Visão geral

Publicado porj4flmao
Repositórioagent-skills
Nome da habilidadearchitecture-domain-driven-design
Estrelas
41
Forks
6
Arquivos incluídos
Somente instruções
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Sem arquivos extras

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por j4flmao no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Architecture Domain Driven Design no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/system-design/domain-driven-design
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/architecture/system-design/domain-driven-design .claude/skills/architecture-domain-driven-design
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Architecture Domain Driven Design em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Architecture Domain Driven Design automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Architecture Domain Driven Design não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Domain-Driven Design

Purpose

DDD aligns software structure with the business: a shared language inside explicit boundaries, models that enforce business invariants, and deliberate translation where contexts meet. Use it where domain complexity is the main risk (pricing, underwriting, logistics, billing). For simple CRUD, plain layered code is cheaper.

Agent Protocol

Trigger

"DDD", "bounded context", "aggregate", "aggregate root", "entity vs value object", "domain event", "context map", "anti-corruption layer", "ubiquitous language", "event storming".

Input Context

  • Business capabilities and processes; domain experts' vocabulary.
  • Current pain: tangled models, inconsistent rules, overloaded terms.
  • Team structure (contexts usually map to team ownership).
  • Persistence and integration constraints.

Output Artifact

Strategic map (subdomains, contexts, relationships) and/or tactical model (aggregates with invariants, value objects, events, repository interfaces).

Response Format

Subdomains: {core|supporting|generic}: {name}
Contexts: {name} owns {terms}; team {x}
Context map: {upstream} -> {downstream} [{pattern}]
Aggregate: {Root} invariants: {list}; references others by id
Events: {PastTenseName}(fields)

Completion Criteria

  • Each term defined per context (no global "User"/"Product" model).
  • Every aggregate lists the invariants it protects.
  • One aggregate modified per transaction; others updated via events.
  • Context relationships named with a context-map pattern.

Strategic Design

Subdomains: core (competitive advantage: invest, custom build), supporting (needed, specific: build simply), generic (commodity: buy/SaaS, e.g. auth, payments).

Bounded context: a boundary within which a model and its language are consistent. "Product" in Catalog (description, images), Inventory (SKU, quantity, location), and Pricing (price lists, discounts) are different models that share an identifier.

Context map patterns

PatternRelationship
PartnershipTwo teams coordinate releases jointly
Shared KernelSmall shared model owned by both (keep tiny)
Customer/SupplierDownstream needs influence upstream's roadmap
ConformistDownstream adopts upstream model as-is
Anti-Corruption Layer (ACL)Downstream translates upstream model into its own terms
Open Host Service + Published LanguageUpstream offers a stable, documented API/schema for many consumers
Separate WaysNo integration; duplicate where cheaper

Event Storming (Brandolini): domain experts and engineers place domain events (orange) on a timeline, then commands, actors, policies, and aggregates; clusters suggest context boundaries.

Tactical Design

Building blockIdentityMutabilityExample
EntityHas id; equality by idMutable via methodsOrder
Value objectNo id; equality by valueImmutableMoney, Address, DateRange
AggregateCluster with one root; consistency boundaryChanged only through rootOrder + OrderLine
Domain eventImmutable factImmutableOrderPlaced
RepositoryLoads/saves whole aggregatesn/aOrderRepository
Domain serviceLogic not belonging to one entityStatelessPricingService

Aggregate rules (Vernon)

  1. Protect true invariants inside the boundary.
  2. Design small aggregates.
  3. Reference other aggregates by identity only.
  4. Use eventual consistency (domain events) outside the boundary; modify one aggregate per transaction.

Example (TypeScript)

typescript
export class Money {
  private constructor(readonly cents: number, readonly currency: string) {}
  static of(cents: number, currency: string): Money {
    if (!Number.isInteger(cents) || cents < 0) throw new RangeError(`invalid amount: ${cents}`);
    return new Money(cents, currency);
  }
  add(other: Money): Money {
    if (other.currency !== this.currency) {
      throw new Error(`currency mismatch: ${this.currency} vs ${other.currency}`);
    }
    return new Money(this.cents + other.cents, this.currency);
  }
}

type OrderStatus = "draft" | "placed" | "cancelled";
export type OrderEvent =
  | { type: "OrderPlaced"; orderId: string; customerId: string; totalCents: number; at: Date };

interface OrderLine { readonly sku: string; readonly qty: number; readonly unitPrice: Money }

export class Order {
  private lines: OrderLine[] = [];
  private status: OrderStatus = "draft";
  private pending: OrderEvent[] = [];

  constructor(readonly id: string, readonly customerId: string, private readonly currency: string) {}

  addLine(sku: string, qty: number, unitPrice: Money): void {
    if (this.status !== "draft") throw new Error(`order ${this.id} is ${this.status}; cannot add lines`);
    if (qty <= 0) throw new RangeError(`qty must be positive, got ${qty}`);
    if (unitPrice.currency !== this.currency) throw new Error("line currency differs from order");
    if (this.lines.length >= 100) throw new Error("max 100 lines per order");   // invariant
    this.lines.push({ sku, qty, unitPrice });
  }

  total(): Money {
    return this.lines.reduce((sum, l) => sum.add(Money.of(l.unitPrice.cents * l.qty, this.currency)),
                             Money.of(0, this.currency));
  }

  place(now: Date): void {
    if (this.status !== "draft") throw new Error(`order ${this.id} already ${this.status}`);
    if (this.lines.length === 0) throw new Error("cannot place an empty order");
    this.status = "placed";
    this.pending.push({ type: "OrderPlaced", orderId: this.id, customerId: this.customerId,
                        totalCents: this.total().cents, at: now });
  }

  pullEvents(): OrderEvent[] {
    const events = this.pending;
    this.pending = [];
    return events;
  }
}

export interface OrderRepository {
  get(id: string): Promise<Order>;
  save(order: Order): Promise<void>;   // persists state + pulled events (outbox) in one transaction
}

Application service: load aggregate → call one method → save (state + events via outbox) in one transaction. Other contexts (Inventory, Billing) react to OrderPlaced asynchronously, translating through their own ACL.

Anti-Corruption Layer

typescript
// Shipping context translating a legacy ERP customer into its own model
export function toRecipient(erp: { CUST_NM: string; ADDR1: string; CNTRY_CD: string }): Recipient {
  if (!erp.ADDR1) throw new Error(`ERP customer ${erp.CUST_NM} has no address`);
  return { name: erp.CUST_NM.trim(), street: erp.ADDR1.trim(), country: mapCountry(erp.CNTRY_CD) };
}

The ACL keeps upstream naming, quirks, and changes from leaking into the downstream model.

Anti-Patterns

  • Anemic domain model: entities as property bags, rules spread through services.
  • Giant aggregates (Customer containing all orders): lock contention and slow loads.
  • One enterprise-wide model for core concepts.
  • Repositories per table instead of per aggregate.
  • DDD ceremony on CRUD subdomains.
  • Bounded contexts that ignore team boundaries (Conway's law will win).

Checklist

  • Subdomains classified; investment matches type.
  • Bounded contexts with glossary and owning team.
  • Context map with explicit patterns; ACL where upstream model is foreign.
  • Aggregates small, invariants listed and enforced in methods.
  • Value objects immutable with validation.
  • Domain events published via outbox; consumers idempotent.
  • Unit tests on aggregates without infrastructure.

References

  • Evans, "Domain-Driven Design" (2003); Vernon, "Implementing Domain-Driven Design" (2013) and "Effective Aggregate Design" essays.
  • Brandolini, "Introducing EventStorming"; Khononov, "Learning Domain-Driven Design" (2021).

Perguntas frequentes

O que a habilidade de IA Architecture Domain Driven Design faz?

Use this skill when the user says 'DDD', 'domain-driven design', 'bounded context', 'aggregate', 'aggregate root', 'ubiquitous language', 'context map', 'anti-corruption layer', 'event storming', 'value object'. Applies strategic DDD (subdomains, bounded contexts, context maps) and tactical DDD (aggregates, entities, value objects, domain events, repositories) to model complex business logic. Do NOT use for: simple CRUD apps where DDD adds ceremony, service decomposition mechanics (architecture/system-design/microservices-patterns), or layering/folder structure only (backend/universal/clean...

Por que usar Architecture Domain Driven Design no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Architecture Domain Driven Design é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Architecture Domain Driven Design no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/j4flmao/agent-skills/tree/main/skills/architecture/system-design/domain-driven-design. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Architecture Domain Driven Design?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Architecture Domain Driven Design?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Architecture Domain Driven Design com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Architecture Domain Driven Design é gratuita?

Sim. A habilidade é publicada no GitHub por j4flmao sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇