data-oriented-architecture
Apply when encountering switch/if-else dispatch on entity type, designing entity systems, or refactoring toward extensibility. Provides registry-based dispatch, capability composition, and infrastructure-first patterns. Complements solid-architecture.
What this skill does
# Data-Oriented Architecture Patterns
## When To Use This Skill
Activate this skill when:
- Encountering switch statements or if/else chains dispatching on entity/object type
- Designing systems with multiple variants of similar entities
- Refactoring code where adding new types requires changes in multiple locations
- Building plugin systems, handler registries, or factory patterns
- Noticing the "expression problem" (hard to add new types AND new operations)
## Core Principle
**Separate data from behavior, dispatch via registry.**
```
Entity = Pure Data (what it IS) + type discriminator
Definition = Bundled Behavior (what it DOES)
Registry = Type → Definition mapping (HOW to dispatch)
```
## Pattern 1: Registry-Based Polymorphism
### Problem
Switch statements scattered throughout codebase:
```
// Scattered in rendering.ts
switch (entity.type) {
case 'typeA': renderA(entity); break;
case 'typeB': renderB(entity); break;
}
// Scattered in update.ts
switch (entity.type) {
case 'typeA': updateA(entity); break;
case 'typeB': updateB(entity); break;
}
// Adding new type = edit N files
```
### Solution
Single registry bundling all type-specific behavior:
```
// definitions.ts - ONE location for all type-specific code
const DEFS: Record<EntityType, Definition> = {
typeA: { render: renderA, update: updateA, ... },
typeB: { render: renderB, update: updateB, ... },
};
// Consumers dispatch generically
DEFS[entity.type].render(entity, ctx);
DEFS[entity.type].update(entity, dt);
// Adding new type = ONE registry entry, ZERO consumer changes
```
### Implementation Checklist
1. Define base `Definition` interface with all operations
2. Create `DEFS: Record<Type, Definition>` registry
3. Export `getDef(type): Definition` helper
4. Replace all switches with `getDef(entity.type).operation()`
5. Use language features for exhaustiveness (TypeScript `Record`, Rust `match`)
## Pattern 2: Capability Composition
### Problem
Not all entities need all behaviors. Deep inheritance or marker interfaces create coupling.
### Solution
Optional capability configs with type guards:
```
interface Definition<T> {
// Required for all
create(): T;
render(): void;
// Optional capabilities - entities opt-in
collision?: CollisionConfig;
physics?: PhysicsConfig;
persistence?: PersistenceConfig;
}
// Type guard for safe access
function hasCollision(def): def is Definition & { collision: CollisionConfig } {
return def.collision !== undefined;
}
// Consumer checks capability
if (hasCollision(def)) {
collisionSystem.register(entity, def.collision);
}
```
### Benefits
- Entities opt-in to behaviors they need
- No inheritance hierarchies
- Capability presence is runtime-checkable
- Systems ignore entities without relevant capabilities
## Pattern 3: Layered Definition Interfaces
```
BaseDefinition (create, render, layer)
↓ extends
DomainDefinition (domain-specific: AI, weapons)
↓ implemented by
ConcreteDefinitions (typeA, typeB, typeC)
```
### Implementation
```
// Base - works for any domain
interface EntityDefinition<TState, TType> {
type: TType;
create(pos): TState;
update?(entity, ctx): void;
render(entity, ctx): void;
collision?: CollisionConfig;
physics?: PhysicsConfig;
}
// Domain-specific extension
interface EnemyDefinition extends EntityDefinition<EnemyState, EnemyType> {
aiStrategy: AIStrategy;
weapons: WeaponConfig[];
}
// Another domain
interface PickupDefinition extends EntityDefinition<PickupState, PickupType> {
onCollect(collector): void;
floatAnimation: AnimationConfig;
}
```
## Pattern 4: Context Objects
### Problem
Functions with many parameters, hard to extend.
### Solution
Bundle related parameters into context objects:
```
// Bad - hard to extend
function update(entity, dt, playerPos, playerVel, gravity, time) { ... }
// Good - extensible
interface UpdateContext {
dt: number;
playerPos: Vec2;
playerVel: Vec2;
// Easy to add fields without breaking signatures
}
function update(entity, ctx: UpdateContext) { ... }
```
### Context Inheritance
```
interface BaseContext { dt: number; }
interface AIContext extends BaseContext { playerPos: Vec2; threats: Entity[]; }
interface RenderContext { graphics: Graphics; screenPos: Vec2; scale: number; }
```
## Pattern 5: Infrastructure-First Development
### Order of Implementation
1. **Generic infrastructure first** (dispatcher, event bus, registry helpers)
2. **Base interfaces** (EntityDefinition, capability configs)
3. **First domain implementation** (proves the pattern)
4. **Second domain validates pattern** (confirms generality)
5. **Retrofit existing systems** (migrate incrementally)
### Rule
> If writing a switch statement on entity type, infrastructure is missing.
## Anti-Patterns To Avoid
### 1. Scattered Switches
Adding new type requires editing N files.
**Fix**: Consolidate into registry.
### 2. Deep Inheritance
`SpecialEnemy extends FlyingEnemy extends Enemy extends Entity`
**Fix**: Capability composition.
### 3. Optional Fields Instead of Capabilities
```
interface Entity {
weapon?: Weapon; // null checks everywhere
}
```
**Fix**: Separate capability with type guard.
### 4. Premature Abstraction
Creating registry for 1 type.
**Fix**: Wait for second type to validate pattern.
### 5. God Objects
Definition with 50 fields for every possible behavior.
**Fix**: Required base + optional capabilities.
## Exhaustiveness Enforcement
Use language features to ensure all types are handled:
```typescript
// TypeScript - Record requires all keys
const DEFS: Record<EntityType, Definition> = {
// Compiler error if type missing
};
// Helper for switch exhaustiveness
function assertNever(x: never): never {
throw new Error(`Unexpected: ${x}`);
}
```
## Summary Checklist
When designing entity systems:
- [ ] Entities are pure data with type discriminator field
- [ ] Definitions bundle ALL type-specific behavior
- [ ] Single registry maps type → definition
- [ ] Consumers dispatch via registry lookup (no switches)
- [ ] Capabilities are optional configs with type guards
- [ ] Context objects bundle related parameters
- [ ] Language features enforce exhaustiveness
- [ ] Adding new type = one registry entry, zero system changes
Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.