The Ontology
A canon of software architecture you can query: every principle with its relations and its repair, every term with its definition, every algorithm with its contract, the reasoning that derives them, the layers they live in and the resolution of every tension between them. Every reference one record makes to another is a link, so any record is a starting point.
Principles
AI / Model Architecture
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_artificial_intelligence_architecture["Artificial Intelligence Architecture"]
n_machine_learning_architecture["Machine Learning Architecture"]
n_model_governance["Model Governance"]
n_model_evaluation["Model Evaluation"]
n_model_inference["Model Inference"]
n_retrieval_augmented_generation["Retrieval-Augmented Generation (RAG)"]
n_vector_search["Vector Search"]
n_knowledge_graphs["Knowledge Graphs"]
n_explainability["Explainability"]
n_ai_safety["AI Safety"]
n_prompt_engineering["Prompt Engineering"]
n_model_drift_monitoring["Model Drift Monitoring"]
n_agentic_architecture["Agentic Architecture"]
n_artificial_intelligence_architecture --> n_model_governance
n_artificial_intelligence_architecture --> n_model_evaluation
n_artificial_intelligence_architecture --> n_ai_safety
n_artificial_intelligence_architecture -.-> n_explainability
n_machine_learning_architecture --> n_model_governance
n_model_governance --> n_ai_safety
n_model_evaluation --> n_ai_safety
n_model_inference --> n_artificial_intelligence_architecture
n_retrieval_augmented_generation --> n_explainability
n_vector_search --> n_retrieval_augmented_generation
n_knowledge_graphs --> n_explainability
n_ai_safety --> n_model_governance
n_prompt_engineering --> n_model_inference
n_prompt_engineering --> n_model_evaluation
n_model_drift_monitoring --> n_model_evaluation
n_model_drift_monitoring --> n_model_governance
n_agentic_architecture --> n_model_inference
n_agentic_architecture --> n_explainability
n_agentic_architecture --> n_ai_safetyArtificial Intelligence Architecture
- Kind: model
- Severity: contextual/mandatory for AI systems
- Scope: AI system, application, platform
- Layer: Correctness Core
Details
Beforeasync function answerFoo(prompt: string) { return model.generate(prompt); }
Afterasync function answerFoo(request: FooRequest) { const input = FooRequestSchema.parse(request); const context = await fooRetriever.retrieve(input.query); const output = await fooModel.generate(buildFooPrompt(input, context)); return FooResponseSchema.parse(output); }
Machine Learning Architecture
- Kind: model
- Severity: contextual
- Scope: ML pipeline, model serving, data
- Layer: Correctness Core
Details
Beforeconst model = trainFoo(loadAllData()); serve(model);
Afterconst dataset = datasetRegistry.load("foo", "v3"); const features = fooFeaturePipeline.transform(dataset); const model = trainFoo(features, versionedTrainingConfig); modelRegistry.register(model, evaluateFooModel(model, validationSet));
Model Governance
- Kind: activity
- Severity: mandatory for production AI
- Scope: model lifecycle, AI system
- Layer: Correctness Core
Details
BeforedeployModel(newestModelFile());
Afterconst candidate = modelRegistry.get("foo-model", "1.4.0"); requireApproval(candidate, ["model-owner", "risk-owner"]); requirePolicyCompliance(candidate, fooModelPolicies); deployModel(candidate);
Model Evaluation
- Kind: activity
- Severity: mandatory
- Scope: model, AI feature, pipeline
- Layer: Correctness Core
Details
Beforeif (model.accuracy > 0.8) deploy(model);
Afterconst evaluation = evaluateModel(model, { datasets: [fooValidationSet, fooStressSet], metrics: [precision, recall, calibration, latencyP95], slices: ["foo-kind", "foo-region"], }); requireThresholds(evaluation, fooModelThresholds);
Model Inference
- Kind: capability
- Severity: contextual
- Scope: service, model serving
- Layer: Correctness Core
Details
Beforeconst output = model.predict(input as any);
Afterconst input = FooInferenceSchema.parse(rawInput); const output = await inferenceRuntime.predict(fooModelVersion, input, { timeoutMs: 500, traceId, }); return FooPredictionSchema.parse(output);
Retrieval-Augmented Generation (RAG)
- Kind: pattern
- Severity: contextual
- Scope: LLM system, knowledge retrieval
- Aliases: RAG
- Layer: Correctness Core
Details
Beforeconst answer = await model.generate(`Answer: ${question}`);
Afterconst query = normalizeFooQuery(question); const documents = await fooRetriever.search(query, { topK: 8 }); const groundedPrompt = buildGroundedFooPrompt(question, documents); const answer = await model.generate(groundedPrompt); return attachCitations(answer, documents);
Vector Search
- Kind: mechanism
- Severity: contextual
- Scope: retrieval, search, RAG
- Layer: Correctness Core
Details
Beforeconst results = foos.filter(foo => foo.text.includes(query));
Afterconst queryVector = await embedder.embed(query); const results = await fooVectorIndex.search(queryVector, { topK: 10, filter: { tenantId }, });
Knowledge Graphs
- Kind: pattern
- Severity: contextual
- Scope: knowledge modeling, retrieval, reasoning
- Layer: Correctness Core
Details
Beforeconst fooLinks = new Map<string, string[]>(); fooLinks.set(foo.id, [bar.id, baz.id]);
Afterconst graph = new KnowledgeGraph(); graph.addNode(foo.id, "Foo", foo); graph.addNode(bar.id, "Bar", bar); graph.addEdge(foo.id, "DEPENDS_ON", bar.id); graph.addEdge(bar.id, "PRODUCES", baz.id);
Explainability
- Kind: quality-attribute
- Severity: contextual/mandatory in regulated AI
- Scope: model, AI system, decision flow
- Layer: Correctness Core
Details
Beforereturn model.predict(foo.features);
Afterconst prediction = await model.predict(foo.features); const explanation = await explainer.explain({ modelVersion: model.version, input: foo.features, prediction, }); return { prediction, explanation };
AI Safety
- Kind: quality-attribute
- Severity: mandatory for AI systems
- Scope: AI system, model, application
- Layer: Correctness Core
Details
Beforereturn model.generate(userPrompt);
Afterconst input = await safety.validateInput(userPrompt); const draft = await model.generate(input); const checked = await safety.validateOutput(draft, { policy: "foo-assistant-v2" }); if (!checked.allowed) return safeRefusal(checked.reasons); return checked.output;
Prompt Engineering
- Kind: technique
- Severity: contextual/mandatory for AI systems
- Scope: AI system, LLM system, application
- Layer: Correctness Core
Details
Beforeconst answer = await model.generate("summarize: " + text);
Afterconst prompt = fooPromptTemplate.render({ task: "summarize", input: text, format: "bullet-points", maxWords: 100 }); const answer = await model.generate(prompt, { temperature: 0, stop: ["\n\n"] });
Model Drift Monitoring
- Kind: activity
- Severity: mandatory for production AI
- Scope: AI system, model lifecycle, operations
- Layer: Correctness Core
Details
BeforeserveModel(fooModel);
Aftermonitor.track(fooModel, { metrics: [inputDistribution, predictionConfidence, groundTruthLag], alertOn: { populationStabilityIndex: 0.2 }, });
Agentic Architecture
- Kind: pattern
- Severity: contextual/mandatory in regulated AI
- Scope: AI system, reasoning, decision flow
- Layer: Correctness Core
Details
Beforeconst answer = await model.generate(question);
Afterconst agent = createFooAgent({ tools: [searchFoos, calculator, fooStore], maxSteps: 8 }); const answer = await agent.run(question);
anti-patterns
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_big_ball_of_mud["Big Ball of Mud"]
n_god_object["God Object"]
n_concrete_coupling["Concrete Coupling"]
n_schema_drift["Schema Drift"]
n_implicit_contract["Implicit Contract"]
n_hardcoded_configuration["Hardcoded Configuration"]
n_shared_mutable_state["Shared Mutable State"]
n_boundary_leakage["Boundary Leakage"]
n_manual_only_governance["Manual-Only Governance"]
n_opaque_runtime_behavior["Opaque Runtime Behavior"]
n_unowned_risk["Unowned Risk"]
n_unobservable_failure["Unobservable Failure"]
n_unversioned_breaking_change["Unversioned Breaking Change"]
n_distributed_monolith["Distributed Monolith"]
n_shotgun_surgery["Shotgun Surgery"]
n_divergent_change["Divergent Change"]
n_feature_envy["Feature Envy"]
n_inappropriate_intimacy["Inappropriate Intimacy"]
n_message_chain["Message Chain"]
n_middle_man["Middle Man"]
n_data_clumps["Data Clumps"]
n_primitive_obsession["Primitive Obsession"]
n_stringly_typed_programming["Stringly Typed Programming"]
n_boolean_trap["Boolean Trap"]
n_long_parameter_list["Long Parameter List"]
n_magic_value["Magic Value"]
n_speculative_generality["Speculative Generality"]
n_premature_abstraction["Premature Abstraction"]
n_over_abstraction["Over-Abstraction"]
n_golden_hammer["Golden Hammer"]
n_pattern_cargo_cult["Pattern Cargo Cult"]
n_lava_flow["Lava Flow"]
n_zombie_code["Zombie Code"]
n_temporal_coupling["Temporal Coupling"]
n_hidden_side_effect["Hidden Side Effect"]
n_action_at_a_distance["Action at a Distance"]
n_ambient_context["Ambient Context"]
n_inconsistent_error_model["Inconsistent Error Model"]
n_exception_control_flow["Exception Control Flow"]
n_null_semantics_drift["Null Semantics Drift"]
n_anemic_domain_model["Anemic Domain Model"]
n_transaction_script_sprawl["Transaction Script Sprawl"]
n_fat_controller["Fat Controller"]
n_repository_dump["Repository Dump"]
n_utility_dump["Utility Dump"]
n_framework_leakage["Framework Leakage"]
n_vendor_lock_in_leakage["Vendor Lock-In Leakage"]
n_circular_dependency["Circular Dependency"]
n_cyclic_deployment_dependency["Cyclic Deployment Dependency"]
n_synchronous_chain_trap["Synchronous Chain Trap"]
n_chatty_interface["Chatty Interface"]
n_n_plus_one_query["N Plus One Query"]
n_cache_poisoning_by_design["Cache Poisoning by Design"]
n_retry_storm["Retry Storm"]
n_timeout_omission["Timeout Omission"]
n_missing_backpressure["Missing Backpressure"]
n_silent_data_corruption["Silent Data Corruption"]
n_lost_update["Lost Update"]
n_dual_write["Dual Write"]
n_read_your_writes_violation["Read-Your-Writes Violation"]
n_security_theater["Security Theater"]
n_authorization_scattering["Authorization Scattering"]
n_secret_sprawl["Secret Sprawl"]
n_pii_oversharing["PII Oversharing"]
n_observability_noise["Observability Noise"]
n_log_as_control_flow["Log-as-Control-Flow"]
n_manual_runbook_dependency["Manual Runbook Dependency"]
n_big_bang_release["Big-Bang Release"]
n_irreversible_migration["Irreversible Migration"]
n_big_upfront_frozen_architecture["Big-Upfront Frozen Architecture"]
n_architecture_astronaut["Architecture Astronaut"]
n_feature_only_design["Feature-Only Design"]
n_test_pyramid_inversion["Test Pyramid Inversion"]
n_mock_mirage["Mock Mirage"]
n_flaky_test_normalization["Flaky Test Normalization"]
n_ai_prompt_sprawl["AI Prompt Sprawl"]
n_ungrounded_ai_output["Ungrounded AI Output"]
n_model_version_ambiguity["Model Version Ambiguity"]Big Ball of Mud
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, state_transaction
- Layer: Enforcement Core
Details
Beforefunction handle(req) { const foo = db.query(req.body.sql); render(foo); email(foo); audit(foo); cache(foo); }
Afterclass CreateFoo { constructor(private readonly foos: FooRepository, private readonly events: EventPublisher) {} execute(input: CreateFooInput) { const foo = Foo.create(input); this.foos.save(foo); this.events.publish(fooCreated(foo)); } }
God Object
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, semantic_consistency, domain_boundary, control_coordination
- Layer: Enforcement Core
Details
Beforeclass FooManager { createFoo() {} priceFoo() {} renderFoo() {} emailFoo() {} auditFoo() {} shipFoo() {} }
Afterclass FooFactory { create(input: CreateFooInput): Foo {} } class FooPricer { price(foo: Foo): Money {} } class FooShipper { ship(foo: Foo): void {} }
Concrete Coupling
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity
- Layer: Enforcement Core
Details
Beforeclass FooService { private readonly store = new SqlFooStore(); }
Afterclass FooService { constructor(private readonly store: FooStore) {} }
Schema Drift
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, security_governance, ai_governance
- Layer: Enforcement Core
Details
Beforetype FooApi = { id: string; label: string }; type FooDb = { id: string; name: string; extra: string };
Afterconst FooSchema = schema({ id: fooIdSchema, name: nonEmptyString }); type Foo = Infer<typeof FooSchema>; fooApi.use(FooSchema); fooDb.use(FooSchema);
Implicit Contract
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, causality_ordering
- Layer: Enforcement Core
Details
Beforefunction saveFoo(foo) { return db.insert(foo); }
Afterinterface Foo { id: FooId; name: NonEmptyString; } function saveFoo(foo: Foo): Promise<void> { return fooStore.save(foo); }
Hardcoded Configuration
- Kind: anti-pattern
- Severity: discouraged
- Scope: semantic_consistency, state_transaction
- Layer: Enforcement Core
Details
Beforeconst client = new FooClient("https://foo.prod.example", "sk_live_abc123");
Afterconst config = FooConfigSchema.parse({ url: process.env.FOO_URL, key: process.env.FOO_KEY }); const client = new FooClient(config);
Shared Mutable State
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, state_transaction
- Layer: Enforcement Core
Details
Beforelet currentFoo = null; function setFoo(f) { currentFoo = f; } function useFoo() { return currentFoo.name; }
Afterclass FooContext { constructor(private readonly foo: Foo) {} name() { return this.foo.name; } }
Boundary Leakage
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, ai_governance
- Layer: Enforcement Core
Details
Beforeapp.get("/foo/:id", async (req, res) => res.json(await ormFoo.findByPk(req.params.id)));
Afterapp.get("/foo/:id", async (req, res) => res.json(toFooDto(await getFoo.execute(req.params.id))));
Manual-Only Governance
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification, security_governance
- Layer: Enforcement Core
Details
Beforeconst CONVENTION = "remember to prefix every foo id with foo_";
Afterexport const rule = { id: "valid-foo-id", check: (id: string) => id.startsWith("foo_") };
Opaque Runtime Behavior
- Kind: anti-pattern
- Severity: discouraged
- Scope: runtime_extensibility, metaprogramming_modeling
- Layer: Enforcement Core
Details
Beforefunction processFoo(foo) { doWork(foo); }
Afterfunction processFoo(foo: Foo) { logger.info("foo.process.start", { fooId: foo.id }); const result = doWork(foo); logger.info("foo.process.done", { fooId: foo.id, outcome: result.status }); }
Unowned Risk
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforeawait payment.charge(foo);
Afterconst outcome = await payment.charge(foo); if (!outcome.ok) { logger.error("foo.charge.failed", outcome); throw new ChargeFailedError(foo.id); }
Unobservable Failure
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility
- Layer: Enforcement Core
Details
Beforetry { await ship(foo); } catch { }
Aftertry { await ship(foo); } catch (error) { logger.error("foo.ship.failed", error); metrics.increment("foo.ship.failure"); throw new ShipFailedError(foo.id); }
Unversioned Breaking Change
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, event_messaging, architecture_evolution
- Layer: Enforcement Core
Details
Beforeapp.get("/foo", () => ({ label: foo.name }));
Afterapp.get("/v2/foo", () => ({ name: foo.name })); app.get("/v1/foo", () => ({ label: foo.name }));
Distributed Monolith
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility, state_transaction
- Layer: Enforcement Core
Details
Beforeasync function createFoo(foo) { await http.post("bar-service/validate", foo); await http.post("baz-service/price", foo); await http.post("qux-service/save", foo); }
Afterasync function createFoo(input: CreateFooInput) { const foo = Foo.create(input); await fooStore.save(foo); await outbox.append(fooCreated(foo)); }
Shotgun Surgery
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity
- Layer: Enforcement Core
Details
Beforeconst taxA = value * 0.2; const taxB = other * 0.2; const taxC = more * 0.2;
Afterconst FOO_TAX_RATE = 0.2; function taxFoo(value: number) { return value * FOO_TAX_RATE; }
Divergent Change
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity
- Layer: Enforcement Core
Details
Beforeclass Foo { renderHtml() {} saveToSql() {} sendEmail() {} parseCsv() {} }
Afterclass Foo {} class FooView { render(foo: Foo): string {} } class FooStore { save(foo: Foo): Promise<void> {} }
Feature Envy
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility
- Layer: Enforcement Core
Details
Beforefunction totalFoo(bar: Bar) { return bar.items.reduce((s, i) => s + i.price * i.qty, 0); }
Afterclass Bar { total(): Money { return this.items.reduce((s, i) => s + i.subtotal(), 0); } }
Inappropriate Intimacy
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility
- Layer: Enforcement Core
Details
Beforebar.foo._internalState.status = "ready";
Afterbar.foo.markReady();
Message Chain
- Kind: anti-pattern
- Severity: discouraged
- Scope: event_messaging
- Layer: Enforcement Core
Details
Beforeconst city = foo.getOwner().getAddress().getCity().getName();
Afterconst city = foo.ownerCityName();
Middle Man
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, correctness_verification, control_coordination
- Layer: Enforcement Core
Details
Beforeclass FooService { save(foo: Foo) { return this.store.save(foo); } find(id: FooId) { return this.store.find(id); } }
Afterconst fooStore: FooStore = new SqlFooStore();
Data Clumps
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility
- Layer: Enforcement Core
Details
Beforefunction shipFoo(street: string, city: string, zip: string, country: string) {}
Afterinterface Address { street: string; city: string; zip: string; country: string; } function shipFoo(address: Address) {}
Primitive Obsession
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification, domain_boundary
- Layer: Enforcement Core
Details
Beforefunction transfer(fooId: string, amount: number, currency: string) {}
Afterclass Money { constructor(readonly amount: number, readonly currency: Currency) {} } function transfer(fooId: FooId, money: Money) {}
Stringly Typed Programming
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforeif (foo.status === "reddy") ship(foo);
Afterenum FooStatus { Ready, Shipped } if (foo.status === FooStatus.Ready) ship(foo);
Boolean Trap
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
BeforecreateFoo(true, false, true);
AftercreateFoo({ active: true, archived: false, notify: true });
Long Parameter List
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility, correctness_verification, object_creation
- Layer: Enforcement Core
Details
Beforefunction makeFoo(a, b, c, d, e, f, g) {}
Afterinterface MakeFooInput { a: A; b: B; c: C; d: D; e: E; f: F; g: G; } function makeFoo(input: MakeFooInput) {}
Magic Value
- Kind: anti-pattern
- Severity: discouraged
- Scope: domain_boundary
- Layer: Enforcement Core
Details
Beforeif (foo.retries > 3) fail(foo);
Afterconst MAX_FOO_RETRIES = 3; if (foo.retries > MAX_FOO_RETRIES) fail(foo);
Speculative Generality
- Kind: anti-pattern
- Severity: discouraged
- Scope: runtime_extensibility
- Layer: Enforcement Core
Details
Beforeabstract class AbstractFooProviderFactoryBase<T> { abstract create(): T; }
Afterfunction createFoo(input: CreateFooInput): Foo { return Foo.create(input); }
Premature Abstraction
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity
- Layer: Enforcement Core
Details
Beforeinterface FooStrategy { run(): void; } class OnlyFooStrategy implements FooStrategy { run() {} }
Afterfunction runFoo() {}
Over-Abstraction
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility
- Layer: Enforcement Core
Details
Beforeconst foo = fooFactoryProvider.getFactory().createBuilder().build();
Afterconst foo = Foo.create(input);
Golden Hammer
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforeconst config = parseFooConfig(runRegexOverEverything(rawYaml));
Afterconst config = FooConfigSchema.parse(yaml.load(rawYaml));
Pattern Cargo Cult
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, correctness_verification
- Layer: Enforcement Core
Details
Beforeclass FooSingletonFactoryObserverProxy {}
Afterclass FooService { constructor(private readonly store: FooStore) {} }
Lava Flow
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforefunction saveFoo(foo) { legacySaveV1(foo); if (false) legacySaveV2(foo); newSave(foo); }
Afterfunction saveFoo(foo: Foo) { return fooStore.save(foo); }
Zombie Code
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforefunction computeFoo() {} function computeFooOld() {} function computeFooDeprecated() {}
Afterfunction computeFoo() {}
Temporal Coupling
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility, correctness_verification, causality_ordering
- Layer: Enforcement Core
Details
Beforefoo.init(); foo.configure(); foo.start();
Afterconst foo = Foo.start(config);
Action at a Distance
- Kind: anti-pattern
- Severity: discouraged
- Scope: event_messaging
- Layer: Enforcement Core
Details
BeforeglobalThis.fooFlag = true; function runFoo() { if (globalThis.fooFlag) go(); }
Afterfunction runFoo(options: { enabled: boolean }) { if (options.enabled) go(); }
Ambient Context
- Kind: anti-pattern
- Severity: discouraged
- Scope: state_transaction
- Layer: Enforcement Core
Details
Beforefunction saveFoo(foo) { return CurrentTenant.get().db.save(foo); }
Afterfunction saveFoo(foo: Foo, tenant: Tenant) { return tenant.db.save(foo); }
Inconsistent Error Model
- Kind: anti-pattern
- Severity: discouraged
- Scope: ai_governance
- Layer: Enforcement Core
Details
Beforefunction a() { return null; } function b() { throw "bad"; } function c() { return { error: true }; }
Afterfunction a(): Result<Foo, FooError> {} function b(): Result<Bar, FooError> {} function c(): Result<Baz, FooError> {}
Exception Control Flow
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification
- Layer: Enforcement Core
Details
Beforetry { return await fooStore.find(id); } catch (notFound) { return fooStore.create(id); }
Afterconst foo = await fooStore.find(id); return foo ?? fooStore.create(id);
Null Semantics Drift
- Kind: anti-pattern
- Severity: discouraged
- Scope: semantic_consistency
- Layer: Enforcement Core
Details
Beforeconst foo = find(id); if (foo) use(foo);
Afterconst foo = find(id) ?? Foo.none(); foo.use();
Anemic Domain Model
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility, semantic_consistency, ai_governance, domain_boundary
- Layer: Enforcement Core
Details
Beforeclass Foo { status: string; } function shipFoo(foo: Foo) { if (foo.status === "ready") foo.status = "shipped"; }
Afterclass Foo { private status = FooStatus.Ready; ship() { if (this.status !== FooStatus.Ready) throw new NotReadyError(); this.status = FooStatus.Shipped; } }
Transaction Script Sprawl
- Kind: anti-pattern
- Severity: discouraged
- Scope: state_transaction, correctness_verification, domain_boundary, control_coordination
- Layer: Enforcement Core
Details
Beforefunction createFooHandler(req) { validate(req); price(req); tax(req); persist(req); notify(req); }
Afterclass CreateFoo { constructor(private readonly foos: FooRepository) {} execute(input: CreateFooInput) { const foo = Foo.create(input); return this.foos.save(foo); } }
Fat Controller
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification, security_governance, control_coordination
- Layer: Enforcement Core
Details
Beforeclass FooController { create(req) { const foo = { ...req.body }; if (!foo.name) throw 0; db.insert(foo); email(foo); } }
Afterclass FooController { constructor(private readonly createFoo: CreateFoo) {} create(req: Request) { return this.createFoo.execute(req.body); } }
Repository Dump
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification, domain_boundary, control_coordination
- Layer: Enforcement Core
Details
Beforeclass FooRepository { findActiveFoosForBarInRegionSortedByBaz() {} }
Afterclass FooRepository { find(spec: FooSpecification): Foo[] { return this.query(spec.toQuery()); } }
Utility Dump
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, domain_boundary
- Layer: Enforcement Core
Details
Beforeexport function formatFoo() {} export function parseBar() {} export function hashBaz() {}
Afterexport const fooFormatter = { format(foo: Foo): string {} }; export const barParser = { parse(raw: string): Bar {} };
Framework Leakage
- Kind: anti-pattern
- Severity: discouraged
- Scope: domain_boundary
- Layer: Enforcement Core
Details
Beforeclass Foo { @Column() name: string; @OneToMany() bars: Bar[]; }
Afterclass Foo { constructor(readonly name: string, readonly bars: readonly Bar[]) {} } class FooEntity { @Column() name: string; }
Vendor Lock-In Leakage
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, ai_governance, domain_boundary
- Layer: Enforcement Core
Details
Beforeimport { BlobStore } from "acme-blob-sdk"; function saveFoo(foo) { return new BlobStore().putObject(foo); }
Afterinterface FooBlobStore { put(foo: Foo): Promise<void>; } function saveFoo(foo: Foo, store: FooBlobStore) { return store.put(foo); }
Circular Dependency
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity
- Layer: Enforcement Core
Details
Beforeimport { bar } from "./bar"; export const foo = () => bar(); import { foo } from "./foo"; export const bar = () => foo();
Afterexport const foo = (run: () => void) => run(); export const bar = () => {}; foo(bar);
Cyclic Deployment Dependency
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
BeforefooService.callsAtStartup(barService); barService.callsAtStartup(fooService);
AfterfooService.publishes(fooReady); barService.subscribes(fooReady);
Synchronous Chain Trap
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity
- Layer: Enforcement Core
Details
Beforeconst foo = await a(); const bar = await b(foo); const baz = await c(bar); return slowSyncCall(a, b, c);
Afterconst [foo, bar, baz] = await Promise.all([a(), b(), c()]);
Chatty Interface
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, contract_compatibility
- Layer: Enforcement Core
Details
Beforeconst results = []; for (const id of fooIds) results.push(await fooApi.get(id));
Afterconst results = await fooApi.getMany(fooIds);
N Plus One Query
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforeconst foos = await fooStore.all(); for (const foo of foos) foo.bar = await barStore.find(foo.barId);
Afterconst foos = await fooStore.all(); const bars = await barStore.findMany(foos.map(f => f.barId));
Cache Poisoning by Design
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification, security_governance
- Layer: Enforcement Core
Details
BeforefooCache.set(request.path, response);
Afterif (response.ok && response.cacheable) { fooCache.set(cacheKey(request.identity, request.path), response, { ttlMs: 60_000 }); }
Retry Storm
- Kind: anti-pattern
- Severity: discouraged
- Scope: resilience_recovery
- Layer: Enforcement Core
Details
Beforewhile (true) { try { return await call(); } catch { } }
Afterreturn retry(call, { attempts: 5, backoff: exponentialJitter(), giveUp: dlq });
Timeout Omission
- Kind: anti-pattern
- Severity: discouraged
- Scope: resilience_recovery
- Layer: Enforcement Core
Details
Beforeconst foo = await fetch(fooUrl);
Afterconst foo = await fetch(fooUrl, { signal: AbortSignal.timeout(5000) });
Missing Backpressure
- Kind: anti-pattern
- Severity: discouraged
- Scope: resilience_recovery
- Layer: Enforcement Core
Details
Beforestream.on("data", d => queue.push(process(d)));
Afterstream.pipe(new BoundedFooProcessor({ highWaterMark: 100 }));
Silent Data Corruption
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, correctness_verification
- Layer: Enforcement Core
Details
Beforeconst total = Number(a) + Number(b); save(total);
Afterconst total = Money.add(Money.parse(a), Money.parse(b)); save(total);
Lost Update
- Kind: anti-pattern
- Severity: discouraged
- Scope: state_transaction
- Layer: Enforcement Core
Details
Beforeconst foo = await load(id); foo.count += 1; await save(foo);
Afterawait fooStore.update(id, { count: increment(1) }, { expectedVersion: foo.version });
Dual Write
- Kind: anti-pattern
- Severity: discouraged
- Scope: event_messaging
- Layer: Enforcement Core
Details
Beforeawait db.save(foo); await searchIndex.add(foo);
Afterawait db.save(foo); await outbox.append(fooCreatedEvent(foo));
Read-Your-Writes Violation
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility
- Layer: Enforcement Core
Details
Beforeawait primaryDb.write(foo); const view = await replicaDb.read(foo.id);
Afterawait primaryDb.write(foo); const view = await readAfterWrite(foo.id, { consistency: "read-your-writes" });
Security Theater
- Kind: anti-pattern
- Severity: discouraged
- Scope: security_governance, ai_governance
- Layer: Enforcement Core
Details
Beforeif (password.length > 0) grantFooAccess(user);
Afterconst verified = await verifyPassword(password, user.passwordHash); if (!verified) throw new UnauthorizedError(); grantFooAccess(user);
Authorization Scattering
- Kind: anti-pattern
- Severity: discouraged
- Scope: security_governance, ai_governance
- Layer: Enforcement Core
Details
Beforeif (user.role === "admin") deleteFoo(); if (user.role === "admin" || user.id === foo.owner) editFoo();
Afterif (policy.can(user, "delete", foo)) deleteFoo(); if (policy.can(user, "edit", foo)) editFoo();
Secret Sprawl
- Kind: anti-pattern
- Severity: discouraged
- Scope: modularity, security_governance
- Layer: Enforcement Core
Details
Beforeconst key = "sk_live_abc123"; const dbPass = "hunter2";
Afterconst key = await secrets.get("foo.api.key"); const dbPass = await secrets.get("foo.db.password");
PII Oversharing
- Kind: anti-pattern
- Severity: discouraged
- Scope: architecture_evolution
- Layer: Enforcement Core
Details
Beforelogger.info("created foo", { email: user.email, ssn: user.ssn });
Afterlogger.info("created foo", { userId: user.id });
Observability Noise
- Kind: anti-pattern
- Severity: discouraged
- Scope: observability_traceability
- Layer: Enforcement Core
Details
Beforelogger.info("entering loop"); for (const f of foos) logger.info("iter", f);
Afterlogger.info("foo.batch.processed", { count: foos.length, durationMs });
Log-as-Control-Flow
- Kind: anti-pattern
- Severity: discouraged
- Scope: correctness_verification, resilience_recovery
- Layer: Enforcement Core
Details
Beforeif (lastFooLogLine.includes("FooReady")) startBarProcessor();
AfterfooEvents.on("FooReady", startBarProcessor);
Manual Runbook Dependency
- Kind: anti-pattern
- Severity: discouraged
- Scope: resilience_recovery
- Layer: Enforcement Core
Details
Beforeconst RUNBOOK = "on failure, ssh in and run restart-foo.sh";
Afterhealth.onUnhealthy(() => orchestrator.restart("foo"));
Big-Bang Release
- Kind: anti-pattern
- Severity: discouraged
- Scope: state_transaction
- Layer: Enforcement Core
Details
BeforedeployEverything("foo", "bar", "baz");
Afterrelease("foo", { strategy: canary(0.1) });
Irreversible Migration
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, architecture_evolution
- Layer: Enforcement Core
Details
Beforeawait db.exec("ALTER TABLE foo DROP COLUMN legacy_name");
Afterawait migrate({ up: addFooName, down: restoreFooName });
Big-Upfront Frozen Architecture
- Kind: anti-pattern
- Severity: discouraged
- Scope: domain_boundary
- Layer: Enforcement Core
Details
Beforeconst ARCHITECTURE = designAllModulesForNextFiveYears();
Afterconst foo = defineModule("foo", { exports: { createFoo } }); registry.add(foo);
Architecture Astronaut
- Kind: anti-pattern
- Severity: discouraged
- Scope: ai_governance, domain_boundary
- Layer: Enforcement Core
Details
Beforeclass AbstractFooMetaStrategyOrchestrationEngineFactory {}
Afterclass CreateFoo { execute(input: CreateFooInput): Foo {} }
Feature-Only Design
- Kind: anti-pattern
- Severity: discouraged
- Scope: security_governance, performance_scaling
- Layer: Enforcement Core
Details
Beforefunction addFooFeature() { hack(); patch(); bypassLint(); }
Afterfunction addFooFeature(input: CreateFooInput) { return createFoo.execute(input); }
Test Pyramid Inversion
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility
- Layer: Enforcement Core
Details
Beforetest.e2e("create foo", fullBrowserFlow); test.e2e("rename foo", fullBrowserFlow); test.e2e("delete foo", fullBrowserFlow);
Aftertest.unit("FooValidator rejects an empty name", () => expect(() => validateFoo({ name: "" })).toThrow()); test.integration("FooRepository persists a Foo", async () => { await fooRepository.save(foo); expect(await fooRepository.find(foo.id)).toEqual(foo); }); test.e2e("the critical signup path", criticalPathOnly);
Mock Mirage
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, correctness_verification, observability_traceability
- Layer: Enforcement Core
Details
Beforeconst store = { save: fn(), find: fn().returns(foo) };
Afterconst store = new InMemoryFooStore(); runFooStoreContract(store);
Flaky Test Normalization
- Kind: anti-pattern
- Severity: discouraged
- Scope: semantic_consistency, correctness_verification
- Layer: Enforcement Core
Details
Beforetest.retry(5)("foo works sometimes", async () => { await sleep(random()); expect(await getFoo()).toBeTruthy(); });
Aftertest("foo is created deterministically", async () => { const foo = await createFoo.execute(input); expect(foo.id).toBe(expectedId); });
AI Prompt Sprawl
- Kind: anti-pattern
- Severity: discouraged
- Scope: contract_compatibility, ai_governance
- Layer: Enforcement Core
Details
Beforeconst a = model.run("summarize this foo: " + foo); const b = model.run("pls summarize foo " + foo);
Afterconst summary = model.run(FOO_PROMPTS.summarize({ foo }));
Ungrounded AI Output
- Kind: anti-pattern
- Severity: discouraged
- Scope: ai_governance
- Layer: Enforcement Core
Details
Beforeconst answer = await model.run(question); return answer;
Afterconst context = await retrieve(question); const answer = await model.run(FOO_PROMPTS.answer({ question, context })); return withCitations(answer, context);
Model Version Ambiguity
- Kind: anti-pattern
- Severity: discouraged
- Scope: ai_governance
- Layer: Enforcement Core
Details
Beforeconst result = await model.run(prompt);
Afterconst result = await model.run(prompt, { model: "foo-llm-2024-06", temperature: 0 }); logger.info("foo.inference", { model: result.model });
Architecture Review / Evolution / Governance Artifacts
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_assessment["Assessment"]
n_architecture_review["Architecture Review"]
n_design_review["Design Review"]
n_code_review["Code Review"]
n_impact_analysis["Impact Analysis"]
n_gap_analysis["Gap Analysis"]
n_fitness_functions["Fitness Functions"]
n_quality_attributes["Quality Attributes"]
n_architecture_decision_records["Architecture Decision Records (ADR)"]
n_evolutionary_architecture["Evolutionary Architecture"]
n_minimum_viable_architecture["Minimum Viable Architecture"]
n_greenfield_development["Greenfield Development"]
n_first_principles_design["First-Principles Design"]
n_reference_architecture["Reference Architecture"]
n_pattern_consistency["Pattern Consistency"]
n_architectural_consistency["Architectural Consistency"]
n_standardization["Standardization"]
n_assessment --> n_quality_attributes
n_architecture_review --> n_architecture_decision_records
n_architecture_review --> n_architectural_consistency
n_fitness_functions --> n_evolutionary_architecture
n_quality_attributes --> n_architecture_review
n_evolutionary_architecture --> n_fitness_functions
n_greenfield_development --> n_first_principles_design
n_reference_architecture --> n_standardization
n_architectural_consistency --> n_pattern_consistencyAssessment
- Kind: activity
- Severity: recommended
- Scope: codebase, architecture, risk
- Layer: Evolution Principles
Details
BeforeapproveFooArchitecture();
Afterconst assessment = assess(fooArchitecture, { dimensions: ["modularity", "reliability", "security", "operability"], evidence: collectArchitectureEvidence(fooSystem), }); requirePassingAssessment(assessment);
Architecture Review
- Kind: activity
- Severity: recommended
- Scope: system, component, design change
- Layer: Evolution Principles
Details
BeforemergeFooDesign();
Afterconst review = architectureReview({ context: fooContext, decisions: fooDecisions, risks: fooRisks, qualityAttributes: fooQualityAttributes, }); review.requireApproval(["architecture-owner", "security-owner"]);
Design Review
- Kind: activity
- Severity: recommended
- Scope: component, module, feature
- Layer: Evolution Principles
Details
BeforeimplementFooDesign(fooDesign);
Afterconst review = designReview(fooDesign, { contracts: validateContracts, failureModes: analyzeFailureModes, testability: assessTestability, }); if (!review.approved) throw new Error("design rejected");
Code Review
- Kind: activity
- Severity: mandatory
- Scope: code change
- Layer: Evolution Principles
Details
Beforegit.merge(fooChange);
Afterconst review = codeReview(fooChange); review.require({ approvals: 2, passingChecks: ["tests", "types", "security", "architecture"] }); git.merge(review.approvedCommit);
Impact Analysis
- Kind: activity
- Severity: recommended
- Scope: change, dependency graph, API
- Layer: Evolution Principles
Details
BeforerenameFooField("name", "label");
Afterconst impact = dependencyGraph.impactOf({ contract: "FooV1.name", change: "rename-to-label", }); for (const consumer of impact.consumers) requireMigration(consumer); renameFooField("name", "label");
Gap Analysis
- Kind: activity
- Severity: contextual
- Scope: compliance, architecture, capability
- Layer: Evolution Principles
Details
BeforedeclareFooSystemReady();
Afterconst target = fooTargetArchitecture(); const current = inspectFooArchitecture(); const gaps = compareArchitecture(current, target); for (const gap of gaps) assignRemediation(gap);
Fitness Functions
- Kind: mechanism
- Severity: recommended
- Scope: codebase, pipeline, architecture
- Layer: Evolution Principles
Details
BeforearchitectureGuidelines.write("Foo domain must not import infrastructure");
Afterconst fitness = forbidImports({ from: "src/foo/domain/**", to: "src/foo/infrastructure/**" }); pipeline.enforce(fitness);
Quality Attributes
- Kind: model
- Severity: recommended
- Scope: system, service, codebase
- Layer: Performance Core
Details
BeforedesignFooService();
Afterconst attributes = defineQualityAttributes({ availability: "99.95%", p95LatencyMs: 200, recoveryTimeMinutes: 5, dataLossSeconds: 0, }); designFooService(attributes);
Architecture Decision Records (ADR)
- Kind: artifact
- Severity: recommended
- Scope: architecture decision
- Aliases: ADRs
- Layer: Evolution Principles
Details
BeforechooseFooDatabase("postgres");
Afterconst adr = recordDecision({ id: "ADR-0042", title: "Use PostgreSQL for Foo persistence", status: "accepted", context: fooPersistenceForces, decision: "postgres", consequences: fooPersistenceConsequences, });
Evolutionary Architecture
- Kind: approach
- Severity: contextual
- Scope: system, codebase
- Layer: Evolution Principles
Details
BeforedesignFinalFooArchitecture(); freezeArchitectureForever();
Afterconst fooArchitecture = evolveArchitecture({ current: minimumFooArchitecture, fitnessFunctions: fooFitnessFunctions, nextChange: highestValueArchitectureChange, });
Minimum Viable Architecture
- Kind: approach
- Severity: contextual
- Scope: greenfield, early product
- Layer: Evolution Principles
Details
BeforebuildServiceMesh(); buildGlobalEventBus(); buildPluginPlatform(); createFooEndpoint();
Afterconst architecture = defineMinimumArchitecture({ useCase: "create-and-read-foo", components: ["foo-api", "foo-store"], deferredUntilForced: ["service-mesh", "plugin-platform"], });
Greenfield Development
- Kind: model
- Severity: contextual
- Scope: new codebase, system
- Layer: Evolution Principles
Details
BeforecopyLegacyFooModule(); retainLegacyFooFlags(); retainLegacyFooSchema();
Afterconst fooSystem = designFromCurrentForces({ domain: fooDomain, constraints: currentConstraints, contracts: currentContracts, });
First-Principles Design
- Kind: approach
- Severity: recommended
- Scope: architecture, domain, component
- Layer: Evolution Principles
Details
BeforeuseMicroservicesBecauseIndustryUsesMicroservices();
Afterconst forces = identifyForces(fooProblem); const invariants = deriveInvariants(forces); const design = synthesizeArchitecture({ forces, invariants });
Reference Architecture
- Kind: artifact
- Severity: contextual
- Scope: platform, organization, system family
- Layer: Evolution Principles
Details
BeforeteamA.buildFooOneWay(); teamB.buildFooAnotherWay();
Afterconst fooReference = defineReferenceArchitecture({ modules: ["api", "application", "domain", "adapters"], allowedDependencies: fooDependencyRules, }); teamA.instantiate(fooReference); teamB.instantiate(fooReference);
Pattern Consistency
- Kind: quality-attribute
- Severity: recommended
- Scope: codebase, system
- Layer: Evolution Principles
Details
BeforefooModule.useRepository(); barModule.queryDatabaseDirectly(); bazModule.useActiveRecord();
Afterconst persistencePattern = "repository" as const; fooModule.use(persistencePattern); barModule.use(persistencePattern); bazModule.use(persistencePattern);
Architectural Consistency
- Kind: quality-attribute
- Severity: mandatory
- Scope: system, codebase
- Layer: Evolution Principles
Details
BeforefooDomain.imports(sqlClient); barDomain.imports(httpClient);
AfterarchitectureRules.enforce([ forbid("domain", "infrastructure"), requirePortFor("external-io"), ]);
Standardization
- Kind: principle
- Severity: contextual
- Scope: codebase, platform, organization
- Layer: Evolution Principles
Details
BeforeteamA.emit({ foo_id: foo.id }); teamB.emit({ id: foo.id, type: "foo" });
Afterconst FooCreatedV1 = standardEvent({ type: "FooCreated", version: 1, fields: { fooId: FooIdSchema }, }); teamA.emit(FooCreatedV1.create(foo)); teamB.emit(FooCreatedV1.create(foo));
Behavioral Patterns
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_strategy_pattern["Strategy Pattern"]
n_template_method_pattern["Template Method Pattern"]
n_observer_pattern["Observer Pattern"]
n_mediator_pattern["Mediator Pattern"]
n_command_pattern["Command Pattern"]
n_state_pattern["State Pattern"]
n_chain_of_responsibility_pattern["Chain of Responsibility Pattern"]
n_iterator_pattern["Iterator Pattern"]
n_visitor_pattern["Visitor Pattern"]
n_memento_pattern["Memento Pattern"]
n_null_object_pattern["Null Object Pattern"]
n_finite_state_machine["Finite State Machine"]
n_statecharts["Statecharts"]
n_finite_state_machine --> n_state_pattern
n_statecharts --> n_finite_state_machine
n_statecharts --> n_finite_state_machineStrategy Pattern
- Kind: pattern
- Severity: recommended
- Scope: algorithm, policy, behavior
- Layer: Design Patterns Core
Details
Beforefunction priceFoo(kind: string, value: number) { if (kind === "standard") return value; if (kind === "double") return value * 2; return 0; }
Afterinterface FooPricing { price(value: number): number; } const standard: FooPricing = { price: value => value }; const doubled: FooPricing = { price: value => value * 2 }; function priceFoo(strategy: FooPricing, value: number) { return strategy.price(value); }
Template Method Pattern
- Kind: pattern
- Severity: contextual
- Scope: workflow, framework
- Layer: Design Patterns Core
Details
Beforefunction importJsonFoo(raw: string) { validateJson(raw); return saveFoo(parseJson(raw)); } function importCsvFoo(raw: string) { validateCsv(raw); return saveFoo(parseCsv(raw)); }
Afterabstract class FooImporter { import(raw: string) { this.validate(raw); return saveFoo(this.parse(raw)); } protected abstract validate(raw: string): void; protected abstract parse(raw: string): Foo; }
Observer Pattern
- Kind: pattern
- Severity: recommended
- Scope: event notification, runtime
- Layer: Design Patterns Core
Details
Beforeclass FooEditor { save(foo: Foo) { fooStore.save(foo); refreshFooView(foo); sendFooEmail(foo); } }
Afterclass FooEvents { #listeners = new Set<(event: FooEvent) => void>(); subscribe(listener: (event: FooEvent) => void) { this.#listeners.add(listener); } publish(event: FooEvent) { this.#listeners.forEach(listener => listener(event)); } } class FooEditor { constructor(private readonly events: FooEvents) {} save(foo: Foo) { fooStore.save(foo); this.events.publish({ type: "FooSaved", foo }); } } fooEvents.subscribe(event => refreshFooView(event.foo)); fooEvents.subscribe(event => sendFooEmail(event.foo));
Mediator Pattern
- Kind: pattern
- Severity: contextual
- Scope: object coordination, module
- Layer: Design Patterns Core
Details
BeforefooEditor.notify(fooList, fooDetails, fooToolbar, foo); fooList.update(fooDetails, fooToolbar, foo);
Afterclass FooMediator { constructor(private readonly list: FooList, private readonly details: FooDetails) {} handle(event: FooEvent) { this.list.apply(event); this.details.apply(event); } }
Command Pattern
- Kind: pattern
- Severity: recommended
- Scope: behavior, invocation, workflow
- Layer: Design Patterns Core
Details
Beforebutton.onClick = () => fooEditor.delete(foo.id);
Afterinterface FooCommand { execute(): void; undo(): void; } class DeleteFooCommand implements FooCommand { constructor(private readonly id: FooId) {} execute() { fooStore.delete(this.id); } undo() { fooStore.restore(this.id); } } history.run(new DeleteFooCommand(foo.id));
State Pattern
- Kind: pattern
- Severity: recommended
- Scope: behavior, state machine, lifecycle
- Layer: Design Patterns Core
Details
Beforefunction handleFoo(foo: Foo, event: string) { if (foo.status === "draft" && event === "submit") foo.status = "review"; if (foo.status === "review" && event === "approve") foo.status = "published"; }
Afterinterface FooState { submit(): FooState; approve(): FooState; } const published: FooState = { submit: () => published, approve: () => published }; const review: FooState = { submit: () => review, approve: () => published }; const draft: FooState = { submit: () => review, approve: () => draft }; class Foo { constructor(private state: FooState = draft) {} submit() { this.state = this.state.submit(); } approve() { this.state = this.state.approve(); } }
Chain of Responsibility Pattern
- Kind: pattern
- Severity: recommended
- Scope: behavior, request handling, pipeline
- Layer: Design Patterns Core
Details
Beforefunction handleFoo(request: FooRequest) { if (request.size > MAX_SIZE) return reject(request); if (!request.authorized) return deny(request); return process(request); }
Aftertype FooHandler = (request: FooRequest, next: () => FooResult) => FooResult; const enforceSize: FooHandler = (request, next) => request.size > MAX_SIZE ? reject(request) : next(); const enforceAuth: FooHandler = (request, next) => request.authorized ? next() : deny(request); const chain = composeHandlers([enforceSize, enforceAuth, () => process(request)]); chain(request);
Iterator Pattern
- Kind: pattern
- Severity: contextual
- Scope: behavior, traversal, collection
- Layer: Design Patterns Core
Details
Beforefor (let i = 0; i < fooTree.nodes.length; i += 1) visit(fooTree.nodes[i]);
Afterclass FooTree { #roots: FooNode[] = []; *[Symbol.iterator](): Iterator<Foo> { for (const node of this.#roots) yield* this.walk(node); } } for (const foo of fooTree) visit(foo);
Visitor Pattern
- Kind: pattern
- Severity: contextual
- Scope: behavior, operation, type hierarchy
- Layer: Design Patterns Core
Details
Beforefunction renderFoo(node: FooNode) { if (node.kind === "text") return node.value; if (node.kind === "group") return node.children.map(renderFoo).join(""); }
Afterinterface FooVisitor<T> { text(node: TextNode): T; group(node: GroupNode): T; } class RenderFooVisitor implements FooVisitor<string> { text(node: TextNode) { return node.value; } group(node: GroupNode) { return node.children.map(child => child.accept(this)).join(""); } }
Memento Pattern
- Kind: pattern
- Severity: contextual
- Scope: behavior, state capture, history
- Layer: Design Patterns Core
Details
Beforeconst backupName = foo.name; const backupTags = [...foo.tags]; foo.rename(newName); if (cancelled) { foo.name = backupName; foo.tags = backupTags; }
Afterclass FooMemento { constructor(readonly snapshot: Readonly<Foo>) {} } const memento = foo.save(); foo.rename(newName); if (cancelled) foo.restore(memento);
Null Object Pattern
- Kind: pattern
- Severity: contextual
- Scope: behavior, absence, default
- Layer: Design Patterns Core
Details
Beforeconst logger = config.logger; if (logger) logger.info("foo saved");
Afterinterface FooLogger { info(message: string): void; } const NoopFooLogger: FooLogger = { info() {} }; const logger = config.logger ?? NoopFooLogger; logger.info("foo saved");
Finite State Machine
- Kind: model
- Severity: recommended
- Scope: behavior, state modeling, control flow
- Layer: Design Patterns Core
Details
Beforelet isOpen = false, isLoading = false, isError = false; function onClick() { isLoading = true; if (isOpen) isOpen = false; }
Aftertype FooState = "closed" | "loading" | "open" | "error"; const transitions: Record<FooState, Partial<Record<FooEvent, FooState>>> = { closed: { open: "loading" }, loading: { ready: "open", fail: "error" }, open: { close: "closed" }, error: { retry: "loading" }, }; function next(state: FooState, event: FooEvent): FooState { return transitions[state][event] ?? state; }
Statecharts
- Kind: model
- Severity: contextual
- Scope: behavior, state modeling, hierarchy
- Layer: Design Patterns Core
Details
Beforetype S = "idleMuted" | "idleLoud" | "playingMuted" | "playingLoud";
Afterconst fooChart = { initial: "idle", states: { idle: {}, playing: {} }, parallel: { volume: { states: { muted: {}, loud: {} } } }, };
Causality / Ordering / Distributed Time
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_causality["Causality"]
n_causal_consistency["Causal Consistency"]
n_happens_before_relationship["Happens-Before Relationship"]
n_event_ordering["Event Ordering"]
n_causal_dependency["Causal Dependency"]
n_dependency_graph["Dependency Graph"]
n_directed_acyclic_graph["Directed Acyclic Graph (DAG)"]
n_vector_clocks["Vector Clocks"]
n_lamport_clocks["Lamport Clocks"]
n_hybrid_logical_clocks["Hybrid Logical Clocks"]
n_crdts["CRDTs"]
n_total_order_broadcast["Total-Order Broadcast"]
n_cap_theorem["CAP Theorem"]
n_pacelc_theorem["PACELC Theorem"]
n_causality --> n_event_ordering
n_event_ordering --> n_causality
n_causal_dependency --> n_causality
n_vector_clocks --> n_causal_consistency
n_hybrid_logical_clocks --> n_happens_before_relationship
n_hybrid_logical_clocks --> n_causal_consistency
n_hybrid_logical_clocks --> n_event_ordering
n_crdts --> n_causal_consistency
n_total_order_broadcast --> n_event_ordering
n_cap_theorem --> n_causal_consistency
n_pacelc_theorem --> n_cap_theorem
n_pacelc_theorem --> n_cap_theoremCausality
- Kind: principle
- Severity: contextual
- Scope: event, workflow, distributed state
- Layer: Causality Core
Details
Beforeevents.push({ type: "BarCreated", at: Date.now() }); events.push({ type: "FooCreated", at: Date.now() });
Afterconst fooCreated = append({ type: "FooCreated" }); append({ type: "BarCreated", causedBy: fooCreated.id });
Causal Consistency
- Kind: model
- Severity: contextual
- Scope: distributed data, events
- Layer: Causality Core
Details
Beforereplica.apply(barCreated); replica.apply(fooCreated);
Afterreplica.applyWhenReady(barCreated, { requires: [fooCreated.id], }); replica.apply(fooCreated);
Happens-Before Relationship
- Kind: model
- Severity: contextual
- Scope: concurrency, distributed events
- Layer: Causality Core
Details
Beforeconst a = { id: "a", at: Date.now() }; const b = { id: "b", at: Date.now() };
Afterconst a = { id: "a", ordinal: 1 }; const b = { id: "b", ordinal: 2, after: [a.id] }; assert(happensBefore(a, b));
Event Ordering
- Kind: constraint
- Severity: contextual
- Scope: stream, queue, consumer
- Layer: Causality Core
Details
Beforeevents.sort((a, b) => a.timestamp - b.timestamp);
Afterevents.sort((a, b) => a.streamOrdinal - b.streamOrdinal);
Causal Dependency
- Kind: model
- Severity: recommended
- Scope: event, workflow, module
- Layer: Causality Core
Details
BeforeprocessBar(barEvent);
Afterif (!projection.has(barEvent.fooEventId)) defer(barEvent); else processBar(barEvent);
Dependency Graph
- Kind: artifact
- Severity: mandatory
- Scope: codebase, runtime, deployment
- Layer: Causality Core
Details
Beforeconst tasks = [loadFoo, buildBar, publishBaz]; await Promise.all(tasks.map(task => task()));
Afterconst graph = new DependencyGraph(); graph.add("buildBar", { dependsOn: ["loadFoo"] }); graph.add("publishBaz", { dependsOn: ["buildBar"] }); await graph.execute();
Directed Acyclic Graph (DAG)
- Kind: constraint
- Severity: mandatory for dependency architecture
- Scope: dependency graph, workflow, build
- Layer: Causality Core
Details
Beforegraph.addEdge("foo", "bar"); graph.addEdge("bar", "foo");
Afterconst dag = new Dag(); dag.addEdge("foo", "bar"); if (dag.wouldCreateCycle("bar", "foo")) throw new Error("cycle rejected");
Vector Clocks
- Kind: mechanism
- Severity: contextual
- Scope: distributed events, replication
- Layer: Causality Core
Details
Beforeconst winner = a.updatedAt > b.updatedAt ? a : b;
Afterconst relation = compareVectorClocks(a.clock, b.clock); if (relation === "concurrent") return mergeFoo(a, b); return relation === "after" ? a : b;
Lamport Clocks
- Kind: mechanism
- Severity: contextual
- Scope: distributed events
- Layer: Causality Core
Details
Beforeconst event = { at: Date.now(), value: foo };
Afterconst event = { logicalTime: lamport.tick(), value: foo }; lamport.observe(remoteEvent.logicalTime);
Hybrid Logical Clocks
- Kind: mechanism
- Severity: mandatory for distributed systems
- Scope: event, distributed state, time
- Layer: Causality Core
Details
Beforeconst event = { at: Date.now(), value: foo };
Afterconst event = { hlc: hlc.now(), value: foo }; hlc.update(remoteEvent.hlc);
CRDTs
- Kind: mechanism
- Severity: contextual
- Scope: distributed state, replication, convergence
- Layer: Causality Core
Details
Beforefoo.tags = incoming.updatedAt > foo.updatedAt ? incoming.tags : foo.tags;
Afterfoo.tags = orSet.merge(foo.tags, incoming.tags);
Total-Order Broadcast
- Kind: mechanism
- Severity: mandatory for distributed systems
- Scope: event, distributed state, ordering
- Layer: Causality Core
Details
Beforereplica.apply(event);
Afterconst sequenced = await totalOrder.broadcast(event); replica.applyInOrder(sequenced.sequence, sequenced.event);
CAP Theorem
- Kind: model
- Severity: mandatory for distributed systems
- Scope: distributed state, consistency, availability
- Layer: Causality Core
Details
Beforeawait Promise.all(replicas.map(r => r.write(foo))); return "always consistent and available";
Afterconst policy = partitionPolicyFor(foo.class); return policy === "CP" ? writeWithQuorum(foo) : writeAvailableAndReconcile(foo);
PACELC Theorem
- Kind: model
- Severity: contextual
- Scope: distributed state, consistency, latency
- Layer: Causality Core
Details
Beforeconst foo = await readFromAllRegionsStrongly(id);
Afterconst foo = tolerateStaleness(id.class) ? await readLocalReplica(id) : await readStronglyAcrossRegions(id);
Codebase / System Architecture Styles
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_ports_and_adapters_architecture["Ports and Adapters Architecture"]
n_hexagonal_architecture["Hexagonal Architecture"]
n_clean_architecture["Clean Architecture"]
n_layered_architecture["Layered Architecture"]
n_component_based_architecture["Component-Based Architecture"]
n_package_by_feature["Package by Feature"]
n_microservices["Microservices"]
n_monolith_architecture["Monolith Architecture"]
n_pipes_and_filters["Pipes and Filters"]
n_service_oriented_architecture["Service-Oriented Architecture"]
n_space_based_architecture["Space-Based Architecture"]
n_hexagonal_architecture --> n_clean_architecturePorts and Adapters Architecture
- Kind: style
- Severity: recommended
- Scope: application, service, component
- Layer: Structural Core
Details
Beforeclass FooService { save(foo: Foo) { return sql.query("insert into foo values (?)", foo); } }
Afterinterface SaveFooPort { save(foo: Foo): Promise<void>; } class FooService { constructor(private readonly port: SaveFooPort) {} save(foo: Foo) { return this.port.save(foo); } } class SqlFooAdapter implements SaveFooPort { save(foo: Foo) { return sqlFooStore.save(foo); } }
Hexagonal Architecture
- Kind: style
- Severity: recommended
- Scope: application, service
- Layer: Structural Core
Details
Beforeapp.post("/foo", async request => sqlFooStore.save(await request.json()));
Afterclass CreateFooUseCase { constructor(private readonly foos: FooRepository, private readonly events: EventPublisher) {} execute(input: CreateFoo) { return createFooCore(input, this.foos, this.events); } } httpAdapter.bind("POST", "/foo", input => useCase.execute(input));
Clean Architecture
- Kind: style
- Severity: recommended
- Scope: application, system
- Layer: Structural Core
Details
Beforeclass FooController { async create(request: Request) { return orm.foo.create(await request.json()); } }
Afterinterface CreateFooGateway { save(foo: Foo): Promise<void>; } class CreateFooInteractor { constructor(private readonly gateway: CreateFooGateway) {} execute(input: CreateFooInput) { return this.gateway.save(Foo.create(input)); } } class FooController { constructor(private readonly useCase: CreateFooInteractor) {} }
Layered Architecture
- Kind: style
- Severity: contextual
- Scope: application, system
- Layer: Structural Core
Details
Beforefunction createFoo(request: Request) { return sql.query("insert into foo values (?)", JSON.parse(request.body)); }
Afterclass FooController { constructor(private readonly service: FooService) {} } class FooService { constructor(private readonly repository: FooRepository) {} } class SqlFooRepository implements FooRepository { save(foo: Foo) { return fooTable.insert(foo); } }
Component-Based Architecture
- Kind: style
- Severity: recommended
- Scope: component, system
- Layer: Structural Core
Details
Beforeconst app = { createFoo, createBar, renderFoo, saveBar, publishBaz, };
Afterconst fooComponent = defineComponent({ name: "foo", exports: { createFoo, FooView }, requires: { FooStore, EventBus }, });
Package by Feature
- Kind: principle
- Severity: recommended
- Scope: package, module
- Layer: Structural Core
Details
Beforesrc/controllers/foo.ts src/controllers/bar.ts src/services/foo.ts src/services/bar.ts src/repositories/foo.ts src/repositories/bar.ts
Aftersrc/foo/controller.ts src/foo/service.ts src/foo/repository.ts src/bar/controller.ts src/bar/service.ts src/bar/repository.ts
Microservices
- Kind: style
- Severity: contextual
- Scope: system, service, deployment
- Layer: Structural Core
Details
Beforeclass SharedApplication { createFoo(foo: Foo) { return sharedDb.insert("foo", foo); } createBar(bar: Bar) { return sharedDb.insert("bar", bar); } }
Afterclass FooService { constructor(private readonly fooStore: FooStore, private readonly outbox: Outbox) {} create(foo: Foo) { return transact(() => [this.fooStore.save(foo), this.outbox.append(fooCreated(foo))]); } } class BarService { constructor(private readonly barStore: BarStore) {} }
Monolith Architecture
- Kind: style
- Severity: contextual
- Scope: application, deployment
- Layer: Structural Core
Details
Beforeawait http.post("foo-service", foo); await http.post("bar-service", bar); await http.post("baz-service", baz);
Afterclass ModularMonolith { constructor(readonly foo: FooModule, readonly bar: BarModule, readonly baz: BazModule) {} } await app.foo.create(foo); await app.bar.create(bar);
Pipes and Filters
- Kind: style
- Severity: recommended
- Scope: application, data processing, composition
- Layer: Structural Core
Details
Beforefunction processFoo(raw: string) { const parsed = parseFoo(raw); const cleaned = cleanFoo(parsed); return enrichFoo(cleaned); }
Afterconst filters: FooFilter[] = [parseFoo, cleanFoo, enrichFoo]; const fooPipeline = connect(filters); fooPipeline.run(raw);
Service-Oriented Architecture
- Kind: style
- Severity: contextual
- Scope: application, service, integration
- Layer: Structural Core
Details
Beforeclass Application { createFoo() {} createBar() {} createBaz() {} }
Afterconst fooService = registerService("FooService", { create: createFoo }, { contract: FooServiceContract }); serviceBus.expose(fooService);
Space-Based Architecture
- Kind: style
- Severity: contextual
- Scope: application, scalability, distributed state
- Layer: Structural Core
Details
Beforeconst foo = await centralDatabase.find(id);
Afterconst foo = await fooSpace.read(id); fooSpace.on("write", replicateToPeers);
Contracts / Interfaces / Compatibility
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_design_by_contract["Design by Contract"]
n_explicit_contracts["Explicit Contracts"]
n_stable_interfaces["Stable Interfaces"]
n_interface_based_design["Interface-Based Design"]
n_contract_first_design["Contract-First Design"]
n_api_contract["API Contract"]
n_service_contract["Service Contract"]
n_data_contract["Data Contract"]
n_schema_contract["Schema Contract"]
n_semantic_contracts["Semantic Contracts"]
n_preconditions["Preconditions"]
n_postconditions["Postconditions"]
n_invariants["Invariants"]
n_backward_compatibility["Backward Compatibility"]
n_forward_compatibility["Forward Compatibility"]
n_versioning["Versioning"]
n_protocol_compatibility["Protocol Compatibility"]
n_interoperability["Interoperability"]
n_uniform_interface["Uniform Interface"]
n_consumer_driven_contracts["Consumer-Driven Contracts"]
n_design_by_contract --> n_preconditions
n_design_by_contract --> n_postconditions
n_design_by_contract --> n_invariants
n_explicit_contracts --> n_stable_interfaces
n_explicit_contracts --> n_interoperability
n_explicit_contracts --> n_contract_first_design
n_stable_interfaces --> n_versioning
n_stable_interfaces --> n_backward_compatibility
n_interface_based_design --> n_stable_interfaces
n_contract_first_design --> n_explicit_contracts
n_contract_first_design --> n_schema_contract
n_contract_first_design --> n_interoperability
n_contract_first_design --> n_backward_compatibility
n_api_contract --> n_versioning
n_api_contract --> n_stable_interfaces
n_api_contract --> n_interoperability
n_service_contract --> n_api_contract
n_data_contract --> n_interoperability
n_schema_contract --> n_data_contract
n_preconditions --> n_design_by_contract
n_postconditions --> n_invariants
n_backward_compatibility --> n_versioning
n_backward_compatibility --> n_stable_interfaces
n_versioning --> n_stable_interfaces
n_versioning --> n_backward_compatibility
n_protocol_compatibility --> n_versioning
n_protocol_compatibility --> n_interoperability
n_consumer_driven_contracts --> n_explicit_contracts
n_consumer_driven_contracts --> n_backward_compatibility
n_consumer_driven_contracts --> n_contract_first_designDesign by Contract
- Kind: principle
- Severity: recommended
- Scope: API, function, class, service
- Layer: Contracts Core
Details
Beforefunction divideFoo(total: number, count: number) { return total / count; }
Afterfunction divideFoo(total: number, count: number): number { if (!Number.isFinite(total)) throw new Error("pre: total must be finite"); if (!Number.isInteger(count) || count <= 0) throw new Error("pre: count must be positive"); const result = total / count; if (!Number.isFinite(result)) throw new Error("post: result must be finite"); return result; }
Explicit Contracts
- Kind: principle
- Severity: mandatory
- Scope: API, service, data, protocol
- Layer: Contracts Core
Details
Beforefunction saveFoo(foo: any): any { return fooStore.save(foo); }
Afterinterface SaveFoo { execute(input: Readonly<{ id: FooId; name: string }>): Promise<{ saved: true; version: number }>; } const saveFoo: SaveFoo = { execute: input => fooStore.save(input) };
Stable Interfaces
- Kind: quality-attribute
- Severity: mandatory
- Scope: API, module, service
- Aliases: Stable Interface
- Layer: Contracts Core
Details
Beforeclass FooService { createFoo(name: string, tags: string[], notify: boolean, source: string) {} }
Aftertype CreateFooRequest = Readonly<{ name: string; tags: readonly string[]; extensions: Readonly<Record<string, unknown>>; }>; interface FooService { create(request: CreateFooRequest): Promise<FooId>; }
Interface-Based Design
- Kind: principle
- Severity: recommended
- Scope: class, module, service
- Layer: Contracts Core
Details
Beforefunction processFoo(store: SqlFooStore, foo: Foo) { return store.insert(foo); }
Afterinterface FooWriter { save(foo: Foo): Promise<void>; } function processFoo(store: FooWriter, foo: Foo) { return store.save(foo); }
Contract-First Design
- Kind: principle
- Severity: recommended
- Scope: API, service, integration
- Layer: Contracts Core
Details
Beforeapp.post("/foo", async request => fooStore.save(await request.json()));
Aftertype CreateFooRequest = { name: string }; type CreateFooResponse = { id: FooId; version: 1 }; interface CreateFooContract { request: CreateFooRequest; response: CreateFooResponse; } app.post("/foo", implement<CreateFooContract>(createFoo));
API Contract
- Kind: constraint
- Severity: mandatory
- Scope: API, service boundary
- Layer: Contracts Core
Details
Beforeapp.get("/foo/:id", async request => fooStore.find(request.params.id));
Afterconst getFooApi = endpoint({ method: "GET", path: "/v1/foo/{id}", request: FooIdSchema, response: FooResponseSchema, errors: ["FOO_NOT_FOUND"] as const, });
Service Contract
- Kind: constraint
- Severity: mandatory
- Scope: service, integration
- Layer: Contracts Core
Details
Beforeclass FooClient { create(body: any) { return http.post("/foo", body); } }
Afterinterface FooServiceContract { create(input: CreateFoo): Promise<Result<FooCreated, FooError>>; } class FooClient implements FooServiceContract { create(input: CreateFoo) { return transport.call("Foo.Create", input); } }
Data Contract
- Kind: constraint
- Severity: mandatory
- Scope: data, message, persistence, integration
- Layer: Contracts Core
Details
Beforetype FooMessage = Record<string, unknown>; queue.publish("foo", payload);
Aftertype FooMessageV1 = Readonly<{ type: "FooCreated"; version: 1; fooId: FooId; name: string; }>; queue.publish<FooMessageV1>("foo.created.v1", message);
Schema Contract
- Kind: constraint
- Severity: mandatory
- Scope: data, API, message
- Layer: Contracts Core
Details
Beforeconst foo = JSON.parse(raw) as Foo;
Afterconst FooSchema = object({ id: string(), count: integer() }); const foo: Foo = FooSchema.parse(JSON.parse(raw));
Semantic Contracts
- Kind: constraint
- Severity: mandatory
- Scope: domain, API, data
- Layer: Contracts Core
Details
Beforefunction reserveFoo(count: number) { return fooStore.decrement(count); }
Aftertype PositiveCount = number & { readonly __brand: "PositiveCount" }; function reserveFoo(count: PositiveCount): Promise<{ reserved: true }> { return fooInventory.reserveExactly(count); }
Preconditions
- Kind: constraint
- Severity: mandatory
- Scope: function, method, API
- Layer: Contracts Core
Details
Beforefunction renameFoo(foo: Foo, name: string) { foo.name = name; }
Afterfunction renameFoo(foo: Foo, name: string) { if (foo.status !== "active") throw new Error("pre: Foo must be active"); if (name.trim().length === 0) throw new Error("pre: name required"); foo.rename(name.trim()); }
Postconditions
- Kind: constraint
- Severity: recommended
- Scope: function, method, transaction
- Layer: Contracts Core
Details
Beforeasync function createFoo(foo: Foo) { return fooStore.save(foo); }
Afterasync function createFoo(foo: Foo): Promise<FooId> { await fooStore.save(foo); const saved = await fooStore.find(foo.id); if (!saved) throw new Error("post: Foo must be persisted"); return saved.id; }
Invariants
- Kind: constraint
- Severity: mandatory
- Scope: entity, aggregate, module, system
- Layer: Contracts Core
Details
Beforeclass FooAccount { balance = 0; withdraw(amount: number) { this.balance -= amount; } }
Afterclass FooAccount { #balance = 0; withdraw(amount: number) { if (amount <= 0 || amount > this.#balance) throw new Error("invariant: balance >= 0"); this.#balance -= amount; } }
Backward Compatibility
- Kind: constraint
- Severity: mandatory
- Scope: API, schema, protocol
- Layer: Contracts Core
Details
Beforeapp.get("/foo", () => ({ label: "Foo", tags: [] }));
Afterapp.get("/v1/foo", () => ({ name: "Foo" })); app.get("/v2/foo", () => ({ label: "Foo", tags: [] }));
Forward Compatibility
- Kind: constraint
- Severity: recommended
- Scope: API, schema, protocol
- Layer: Contracts Core
Details
Beforefunction readFoo(input: { name: string }) { if (Object.keys(input).length !== 1) throw new Error("unknown field"); return input.name; }
Aftertype FooEnvelope = { name: string; extensions?: Record<string, unknown> }; function readFoo(input: FooEnvelope) { return { name: input.name, extensions: input.extensions ?? {} }; }
Versioning
- Kind: mechanism
- Severity: mandatory
- Scope: API, schema, package, service
- Layer: Contracts Core
Details
Beforequeue.publish("foo.created", { id: foo.id, name: foo.name });
Afterqueue.publish("foo.created.v2", { schemaVersion: 2, id: foo.id, label: foo.name, });
Protocol Compatibility
- Kind: constraint
- Severity: mandatory
- Scope: integration, network, message
- Layer: Contracts Core
Details
Beforesocket.send(JSON.stringify({ action: "save", foo }));
Aftertype FooFrameV1 = { protocol: "foo/1"; type: "save"; payload: Foo }; socket.send(encodeFrame<FooFrameV1>({ protocol: "foo/1", type: "save", payload: foo }));
Interoperability
- Kind: quality-attribute
- Severity: mandatory
- Scope: API, data, protocol, system
- Layer: Contracts Core
Details
BeforefooClient.send(serializeWithPrivateFormat(foo));
Afterconst payload: JsonFooV1 = toJsonFooV1(foo); fooClient.send(JSON.stringify(payload), { contentType: "application/json" });
Uniform Interface
- Kind: constraint
- Severity: recommended
- Scope: API, resource boundary
- Layer: Contracts Core
Details
BeforefooApi.createFoo(foo); barApi.post("/bar", bar); bazApi.execute("DELETE_BAZ", baz.id);
AfterresourceClient.post("/foos", foo); resourceClient.post("/bars", bar); resourceClient.delete(`/bazes/${baz.id}`);
Consumer-Driven Contracts
- Kind: constraint
- Severity: recommended
- Scope: API, service, integration
- Layer: Contracts Core
Details
BeforefooProvider.deploy(newFooApi);
Afterconst expectations = collectContractsFrom(["bar-service", "baz-service"]); const result = verifyProvider(newFooApi, expectations); if (!result.satisfied) throw new BrokenConsumerContractError(result.violations); fooProvider.deploy(newFooApi);
Control / Coordination / Centralization
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_control_plane["Control Plane"]
n_orchestration["Orchestration"]
n_centralized_configuration["Centralized Configuration"]
n_centralized_authentication["Centralized Authentication"]
n_centralized_logging["Centralized Logging"]
n_decentralization["Decentralization"]
n_leader_election["Leader Election"]
n_consensus["Consensus"]
n_choreography["Choreography"]
n_control_plane --> n_orchestration
n_orchestration --> n_control_plane
n_leader_election --> n_consensus
n_leader_election --> n_control_plane
n_choreography --> n_decentralizationControl Plane
- Kind: artifact
- Severity: contextual
- Scope: platform, infrastructure, distributed system
- Layer: Execution Core
Details
Beforefor (const node of fooNodes) { node.configure({ retries: 3, timeoutMs: 500 }); }
AftercontrolPlane.apply("foo-service", { retries: 3, timeoutMs: 500, rollout: "progressive", });
Orchestration
- Kind: mechanism
- Severity: contextual
- Scope: workflow, deployment, services
- Layer: Execution Core
Details
Beforeawait fooService.create(foo); await barService.create(bar); await bazService.create(baz);
Afterawait orchestrator.run("CreateFooFlow", { steps: [ step("foo", () => fooService.create(foo)), step("bar", () => barService.create(bar)), step("baz", () => bazService.create(baz)), ], });
Centralized Configuration
- Kind: pattern
- Severity: contextual
- Scope: service, platform, runtime
- Layer: Execution Core
Details
Beforeconst fooConfig = loadLocalFooConfig(); const barConfig = loadLocalBarConfig(); const bazConfig = loadLocalBazConfig();
Afterconst config = await configService.readVersioned("platform/v3"); fooApp.apply(config.foo); barApp.apply(config.bar); bazApp.apply(config.baz);
Centralized Authentication
- Kind: pattern
- Severity: recommended
- Scope: identity, system
- Layer: Execution Core
Details
BeforefooService.verifyToken(token); barService.verifyToken(token); bazService.verifyToken(token);
Afterconst identity = await identityProvider.authenticate(token); await fooService.handle({ identity }); await barService.handle({ identity }); await bazService.handle({ identity });
Centralized Logging
- Kind: pattern
- Severity: recommended
- Scope: services, platform
- Layer: Execution Core
Details
BeforefooService.writeLocalLog(event); barService.writeLocalLog(event); bazService.writeLocalLog(event);
Afterconst sink = new CentralLogSink(); fooService.useLogger(structuredLogger(sink)); barService.useLogger(structuredLogger(sink)); bazService.useLogger(structuredLogger(sink));
Decentralization
- Kind: principle
- Severity: contextual
- Scope: system, team, service
- Layer: Execution Core
Details
Beforeconst coordinator = new GlobalFooCoordinator(); await coordinator.approveEveryFoo(foo);
Afterawait fooNode.validate(foo); await fooNode.commit(foo); await fooNode.publish({ type: "FooCommitted", fooId: foo.id });
Leader Election
- Kind: mechanism
- Severity: mandatory for distributed systems
- Scope: distributed system, coordination, availability
- Layer: Execution Core
Details
Beforeif (process.env.IS_LEADER === "true") runFooScheduler();
Afterconst lease = await fooCoordinator.acquireLeadership("foo-scheduler", { ttlMs: 10_000 }); lease.onAcquired(() => runFooScheduler()); lease.onLost(() => stopFooScheduler());
Consensus
- Kind: mechanism
- Severity: mandatory for distributed systems
- Scope: distributed system, agreement, consistency
- Layer: Execution Core
Details
BeforefooNodeA.setValue(value);
Afterconst committed = await fooCluster.propose(value, { quorum: majority(fooNodes) }); if (!committed.accepted) throw new NoQuorumError();
Choreography
- Kind: mechanism
- Severity: contextual
- Scope: distributed system, coordination, event
- Layer: Execution Core
Details
Beforeawait orchestrator.run("CreateFoo", [ () => createFoo(foo), () => reserveBar(foo), () => notifyBaz(foo), ]);
AfterfooEvents.on("FooCreated", event => barService.reserve(event.fooId)); barEvents.on("BarReserved", event => bazService.notify(event.fooId));
Core Modular Design
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_single_responsibility["Single Responsibility Principle (SRP)"]
n_separation_of_concerns["Separation of Concerns"]
n_duplicate_code["Do Not Repeat Yourself (DRY)"]
n_high_cohesion["High Cohesion"]
n_low_coupling["Low Coupling"]
n_encapsulation["Encapsulation"]
n_information_hiding["Information Hiding"]
n_abstraction["Abstraction"]
n_modularity["Modularity"]
n_composability["Composability"]
n_composition_over_inheritance["Composition Over Inheritance"]
n_reusability["Reusability"]
n_replaceability["Replaceability"]
n_interchangeability["Interchangeability"]
n_independence["Independence"]
n_autonomy["Autonomy"]
n_single_responsibility --> n_high_cohesion
n_single_responsibility --> n_separation_of_concerns
n_single_responsibility --> n_modularity
n_single_responsibility --> n_replaceability
n_single_responsibility --> n_reusability
n_separation_of_concerns --> n_abstraction
n_separation_of_concerns --> n_single_responsibility
n_separation_of_concerns --> n_modularity
n_separation_of_concerns --> n_replaceability
n_duplicate_code --> n_abstraction
n_duplicate_code --> n_reusability
n_high_cohesion --> n_single_responsibility
n_high_cohesion --> n_modularity
n_high_cohesion --> n_encapsulation
n_high_cohesion --> n_replaceability
n_low_coupling --> n_abstraction
n_low_coupling --> n_modularity
n_low_coupling --> n_replaceability
n_encapsulation --> n_information_hiding
n_encapsulation --> n_abstraction
n_encapsulation --> n_low_coupling
n_information_hiding --> n_encapsulation
n_information_hiding --> n_low_coupling
n_information_hiding --> n_replaceability
n_abstraction --> n_low_coupling
n_abstraction --> n_replaceability
n_modularity --> n_high_cohesion
n_modularity --> n_low_coupling
n_modularity --> n_separation_of_concerns
n_modularity --> n_composability
n_modularity --> n_replaceability
n_composability --> n_low_coupling
n_composability --> n_modularity
n_composability --> n_reusability
n_composition_over_inheritance --> n_low_coupling
n_composition_over_inheritance --> n_replaceability
n_reusability --> n_abstraction
n_reusability --> n_duplicate_code
n_reusability --> n_composability
n_replaceability --> n_low_coupling
n_interchangeability --> n_replaceability
n_independence --> n_low_coupling
n_independence --> n_autonomy
n_autonomy --> n_independenceSingle Responsibility Principle (SRP)
- Kind: principle
- Severity: mandatory
- Scope: class, module, service
- Aliases: SRP, Single Responsibility Principle (SRP)
- Layer: Structural Core
Details
Beforeclass FooService { save(foo: Foo) { fooDb.insert(foo); } send(foo: Foo) { fooMail.send(foo); } report(foo: Foo) { return `${foo.id}:${foo.name}`; } }
Afterclass FooRepository { save(foo: Foo) { return fooDb.insert(foo); } } class FooNotifier { send(foo: Foo) { return fooMail.send(foo); } } class FooReporter { report(foo: Foo) { return `${foo.id}:${foo.name}`; } }
Separation of Concerns
- Kind: principle
- Severity: mandatory
- Scope: module, package, component, system
- Layer: Structural Core
Details
Beforefunction handleFoo(request: Request) { const foo = JSON.parse(request.body); fooDb.insert(foo); return `<div>${foo.name}</div>`; }
Afterfunction parseFoo(request: Request): Foo { return decodeFoo(request.body); } function saveFoo(foo: Foo) { return fooDb.insert(foo); } function renderFoo(foo: Foo) { return `<div>${foo.name}</div>`; }
Do Not Repeat Yourself (DRY)
- Kind: principle
- Severity: mandatory
- Scope: function, module, domain
- Aliases: DRY
- Layer: Structural Core
Details
Beforefunction validateFoo(foo: Foo) { if (!foo.name || foo.name.length > 40) throw new Error("invalid name"); } function validateBar(bar: Bar) { if (!bar.name || bar.name.length > 40) throw new Error("invalid name"); }
Afterfunction validateName(name: string) { if (!name || name.length > 40) throw new Error("invalid name"); } function validateFoo(foo: Foo) { validateName(foo.name); } function validateBar(bar: Bar) { validateName(bar.name); }
High Cohesion
- Kind: quality-attribute
- Severity: mandatory
- Scope: class, module, component
- Layer: Structural Core
Details
Beforeclass FooManager { saveFoo(foo: Foo) { return fooDb.insert(foo); } resizeImage(image: Image) { return image.resize(100, 100); } parseBar(raw: string) { return JSON.parse(raw) as Bar; } }
Afterclass FooRepository { save(foo: Foo) { return fooDb.insert(foo); } load(id: FooId) { return fooDb.find(id); } remove(id: FooId) { return fooDb.delete(id); } } class ImageResizer { resize(image: Image) { return image.resize(100, 100); } } class BarParser { parse(raw: string) { return JSON.parse(raw) as Bar; } }
Low Coupling
- Kind: quality-attribute
- Severity: mandatory
- Scope: module, component, service
- Aliases: Loose Coupling
- Layer: Structural Core
Details
Beforeclass FooService { save(foo: Foo) { const db = new SqlDatabase("foo-prod"); barIndex.update(foo); return db.table("foos").insert(foo); } }
Afterclass FooService { constructor(private readonly events: EventSink) {} save(foo: Foo) { return this.events.emit({ type: "FooSaved", foo }); } }
Encapsulation
- Kind: principle
- Severity: mandatory
- Scope: class, module, component
- Layer: Structural Core
Details
Beforeclass FooCounter { count = 0; } const counter = new FooCounter(); counter.count = -100;
Afterclass FooCounter { #count = 0; increment() { this.#count += 1; } value() { return this.#count; } }
Information Hiding
- Kind: principle
- Severity: mandatory
- Scope: class, module, package
- Layer: Structural Core
Details
Beforeclass FooStore { public readonly rows = new Map<string, Foo>(); } fooStore.rows.set(foo.id, foo);
Afterinterface FooStore { save(foo: Foo): void; find(id: string): Foo | undefined; } class MapFooStore implements FooStore { #rows = new Map<string, Foo>(); save(foo: Foo) { this.#rows.set(foo.id, foo); } find(id: string) { return this.#rows.get(id); } }
Abstraction
- Kind: principle
- Severity: mandatory
- Scope: class, module, service, system
- Layer: Structural Core
Details
Beforefunction saveFoo(foo: Foo) { return sqlClient.query("insert into foos(id,name) values($1,$2)", [foo.id, foo.name]); }
Afterinterface FooRepository { save(foo: Foo): Promise<void>; } class SqlFooRepository implements FooRepository { save(foo: Foo) { return sqlClient.query("insert into foos(id,name) values($1,$2)", [foo.id, foo.name]); } } class HttpFooRepository implements FooRepository { save(foo: Foo) { return http.post("/foos", foo); } } function saveFoo(foo: Foo, repository: FooRepository) { return repository.save(foo); }
Modularity
- Kind: principle
- Severity: mandatory
- Scope: package, component, service, system
- Layer: Structural Core
Details
Beforeclass FooApplication { parse(raw: string) { return JSON.parse(raw) as Foo; } save(foo: Foo) { return fooDb.insert(foo); } publish(foo: Foo) { return fooBus.emit(foo); } }
Afterexport const fooParser = { parse: (raw: string) => decodeFoo(raw) }; export const fooRepository = { save: (foo: Foo) => fooDb.insert(foo) }; export const fooPublisher = { publish: (foo: Foo) => fooBus.emit(foo) };
Composability
- Kind: principle
- Severity: recommended
- Scope: function, component, system
- Layer: Structural Core
Details
Beforefunction processFoo(raw: string) { const foo = JSON.parse(raw) as Foo; const normalized = { ...foo, name: foo.name.trim() }; return fooDb.insert(normalized); }
Afterconst parseFoo = (raw: string): Foo => decodeFoo(raw); const normalizeFoo = (foo: Foo): Foo => ({ ...foo, name: foo.name.trim() }); const saveFoo = (foo: Foo) => fooDb.insert(foo); const processFoo = flow(parseFoo, normalizeFoo, saveFoo);
Composition Over Inheritance
- Kind: principle
- Severity: recommended
- Scope: class, component
- Layer: Structural Core
Details
Beforeclass RetryingSqlFooStore extends SqlFooStore { async save(foo: Foo) { for (let attempt = 0; attempt < 3; attempt += 1) { try { return await super.save(foo); } catch (error) { if (attempt === 2) throw error; } } } }
Afterclass RetryingFooStore implements FooStore { constructor(private readonly inner: FooStore, private readonly attempts: number) {} async save(foo: Foo) { for (let attempt = 0; attempt < this.attempts; attempt += 1) { try { return await this.inner.save(foo); } catch (error) { if (attempt === this.attempts - 1) throw error; } } } }
Reusability
- Kind: quality-attribute
- Severity: recommended
- Scope: function, module, component
- Layer: Structural Core
Details
Beforefunction saveAdminFoo(foo: Foo) { return adminFooDb.insert(foo); } function savePublicFoo(foo: Foo) { return publicFooDb.insert(foo); }
Afterfunction saveFoo(store: FooStore, foo: Foo) { return store.save(foo); } const saveAdminFoo = (foo: Foo) => saveFoo(adminFooStore, foo); const savePublicFoo = (foo: Foo) => saveFoo(publicFooStore, foo);
Replaceability
- Kind: quality-attribute
- Severity: recommended
- Scope: component, service, infrastructure
- Layer: Structural Core
Details
Beforeclass FooService { private readonly store = new SqlFooStore(); save(foo: Foo) { return this.store.save(foo); } }
Afterclass FooService { constructor(private readonly store: FooStore) {} save(foo: Foo) { return this.store.save(foo); } } test("saves without a database", async () => { const store = new MemoryFooStore(); await new FooService(store).save(foo); expect(store.find(foo.id)).toEqual(foo); });
Interchangeability
- Kind: quality-attribute
- Severity: recommended
- Scope: component, plugin, service
- Layer: Structural Core
Details
Beforefunction loadFoo(kind: "sql" | "memory", id: FooId) { if (kind === "sql") return sqlFooStore.find(id); return memoryFooStore.get(id); }
Afterinterface FooStore { find(id: FooId): Promise<Foo | undefined>; } function loadFoo(store: FooStore, id: FooId) { return store.find(id); }
Independence
- Kind: principle
- Severity: recommended
- Scope: module, service, deployment
- Layer: Structural Core
Details
Beforeclass FooModule { create(foo: Foo) { barModule.refresh(foo.id); bazModule.rebuild(foo.id); return fooDb.insert(foo); } }
Afterclass FooModule { constructor(private readonly store: FooStore, private readonly events: EventSink) {} async create(foo: Foo) { await this.store.save(foo); this.events.emit({ type: "FooCreated", fooId: foo.id }); } }
Autonomy
- Kind: principle
- Severity: contextual
- Scope: service, team, bounded context
- Layer: Structural Core
Details
Beforeasync function createFoo(foo: Foo) { const bar = await barService.get(foo.barId); await bazService.validate(foo, bar); return fooStore.save(foo); }
Afterasync function createFoo(foo: Foo) { await fooStore.save(foo); await outbox.append({ type: "FooCreated", fooId: foo.id, barId: foo.barId }); }
Correctness / Determinism / Verification
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_determinism["Determinism"]
n_predictability["Predictability"]
n_referential_transparency["Referential Transparency"]
n_pure_functions["Pure Functions"]
n_immutability["Immutability"]
n_reproducibility["Reproducibility"]
n_repeatability["Repeatability"]
n_correctness["Correctness"]
n_formal_verification["Formal Verification"]
n_specification_based_testing["Specification-Based Testing"]
n_property_based_testing["Property-Based Testing"]
n_static_analysis["Static Analysis"]
n_testability["Testability"]
n_validation["Validation"]
n_verification["Verification"]
n_determinism --> n_predictability
n_determinism --> n_reproducibility
n_predictability --> n_determinism
n_referential_transparency --> n_pure_functions
n_referential_transparency --> n_immutability
n_referential_transparency --> n_determinism
n_referential_transparency --> n_testability
n_pure_functions --> n_testability
n_pure_functions --> n_determinism
n_pure_functions --> n_referential_transparency
n_immutability --> n_predictability
n_reproducibility --> n_determinism
n_repeatability --> n_verification
n_repeatability --> n_predictability
n_correctness --> n_validation
n_formal_verification --> n_correctness
n_specification_based_testing --> n_correctness
n_property_based_testing --> n_correctness
n_testability --> n_pure_functions
n_validation --> n_correctness
n_verification --> n_correctnessDeterminism
- Kind: principle
- Severity: recommended
- Scope: function, process, build, test
- Layer: Computation Core
Details
Beforefunction makeFoo(name: string) { return { id: crypto.randomUUID(), name, createdAt: new Date() }; }
Afterfunction makeFoo(name: string, id: FooId, createdAt: Date): Foo { return { id, name, createdAt }; }
Predictability
- Kind: quality-attribute
- Severity: recommended
- Scope: API, module, runtime
- Layer: Computation Core
Details
Beforefunction saveFoo(foo: Foo) { if (Math.random() > 0.5) return memoryStore.save(foo); return sqlStore.save(foo); }
Afterfunction saveFoo(store: FooStore, foo: Foo) { return store.save(foo); }
Referential Transparency
- Kind: principle
- Severity: contextual
- Scope: function, expression
- Layer: Computation Core
Details
Beforefunction fooTotal(values: number[]) { globalCounter += 1; return values.reduce((a, b) => a + b, 0) + globalCounter; }
Afterfunction fooTotal(values: readonly number[]) { return values.reduce((a, b) => a + b, 0); }
Pure Functions
- Kind: technique
- Severity: recommended
- Scope: function, domain logic
- Layer: Computation Core
Details
Beforefunction normalizeFoo(foo: Foo) { foo.name = foo.name.trim(); fooStore.save(foo); return foo; }
Afterfunction normalizeFoo(foo: Foo): Foo { return { ...foo, name: foo.name.trim() }; }
Immutability
- Kind: principle
- Severity: recommended
- Scope: data, value object, concurrency
- Layer: Computation Core
Details
Beforetype Foo = { name: string; tags: string[] }; function addTag(foo: Foo, tag: string) { foo.tags.push(tag); return foo; }
Aftertype Foo = Readonly<{ name: string; tags: readonly string[] }>; function addTag(foo: Foo, tag: string): Foo { return { ...foo, tags: [...foo.tags, tag] }; }
Reproducibility
- Kind: quality-attribute
- Severity: recommended
- Scope: build, test, deployment, ML
- Layer: Computation Core
Details
Beforeconst result = trainFoo(data, { seed: Math.random() });
Afterconst config = { seed: 42, datasetVersion: "foo-v3", algorithmVersion: "1.2.0" } as const; const result = trainFoo(data, config);
Repeatability
- Kind: quality-attribute
- Severity: mandatory
- Scope: test, build, process
- Layer: Computation Core
Details
Beforetest("foo", () => expect(runFoo(Date.now())).toEqual(snapshot()));
Aftertest("foo", () => { const clock = new FixedClock("2026-01-01T00:00:00Z"); expect(runFoo(clock)).toEqual(expectedFoo); });
Correctness
- Kind: quality-attribute
- Severity: mandatory
- Scope: function, module, system
- Layer: Computation Core
Details
Beforefunction averageFoo(total: number, count: number) { return total / count; }
Afterfunction averageFoo(total: number, count: number) { if (!Number.isFinite(total)) throw new Error("invalid total"); if (!Number.isInteger(count) || count <= 0) throw new Error("invalid count"); return total / count; }
Formal Verification
- Kind: activity
- Severity: contextual
- Scope: algorithm, protocol, critical system
- Layer: Computation Core
Details
Beforefunction transferFoo(a: FooBalance, b: FooBalance, amount: number) { a.value -= amount; b.value += amount; }
Afterfunction transferFoo(state: FooState, amount: PositiveAmount): FooState { requires(state.from >= amount.value); const next = { from: state.from - amount.value, to: state.to + amount.value }; ensures(next.from + next.to === state.from + state.to); return next; }
Specification-Based Testing
- Kind: activity
- Severity: recommended
- Scope: function, API, module
- Layer: Computation Core
Details
Beforetest("saveFoo", async () => expect(await saveFoo(foo)).toBeTruthy());
AfterdescribeContract("FooStore", store => { it("returns the saved Foo", async () => { await store.save(foo); expect(await store.find(foo.id)).toEqual(foo); }); });
Property-Based Testing
- Kind: activity
- Severity: recommended
- Scope: function, algorithm, parser, domain invariant
- Layer: Computation Core
Details
Beforetest("normalizeFoo", () => expect(normalizeFoo({ name: " Foo " }).name).toBe("Foo"));
Afterproperty(string(), name => { const once = normalizeFoo({ name }); const twice = normalizeFoo(once); expect(twice).toEqual(once); });
Static Analysis
- Kind: mechanism
- Severity: mandatory
- Scope: codebase, build
- Layer: Computation Core
Details
Beforeconst foo: any = loadFoo(); foo.nmae.toUpperCase();
Afterconst foo: Foo = loadFoo(); foo.name.toUpperCase(); runTypeCheck({ noImplicitAny: true, strictNullChecks: true });
Testability
- Kind: quality-attribute
- Severity: mandatory
- Scope: class, module, service
- Layer: Computation Core
Details
Beforefunction createFoo(name: string) { return fooDb.save({ id: crypto.randomUUID(), name, createdAt: new Date() }); }
Afterfunction createFoo(name: string, ids: IdSource, clock: Clock, store: FooStore) { return store.save({ id: ids.nextFooId(), name, createdAt: clock.now() }); }
Validation
- Kind: activity
- Severity: mandatory
- Scope: input, behavior, requirement
- Layer: Computation Core
Details
Beforefunction createFoo(input: any) { return fooStore.save(input); }
Afterfunction createFoo(input: unknown) { const foo = CreateFooSchema.parse(input); return fooStore.save(foo); }
Verification
- Kind: activity
- Severity: mandatory
- Scope: implementation, system
- Layer: Computation Core
Details
Beforeawait fooStore.save(foo); return { ok: true };
Afterawait fooStore.save(foo); const persisted = await fooStore.find(foo.id); if (!persisted || persisted.version !== foo.version) throw new Error("verification failed"); return { ok: true } as const;
Creational Patterns
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_factory_pattern["Factory Pattern"]
n_factory_method_pattern["Factory Method Pattern"]
n_abstract_factory_pattern["Abstract Factory Pattern"]
n_builder_pattern["Builder Pattern"]
n_prototype_pattern["Prototype Pattern"]
n_singleton_pattern["Singleton Pattern"]Factory Pattern
- Kind: pattern
- Severity: recommended
- Scope: object creation, module
- Layer: Design Patterns Core
Details
Beforeconst foo = new Foo("foo", 0, [], new Date(), "draft");
Afterfunction makeFoo(name: string): Foo { return new Foo(fooId(), name, 0, [], clock.now(), "draft"); }
Factory Method Pattern
- Kind: pattern
- Severity: contextual
- Scope: class hierarchy, framework
- Layer: Design Patterns Core
Details
Beforeclass FooImporter { import(raw: string) { return new JsonFooParser().parse(raw); } }
Afterabstract class FooImporter { protected abstract parser(): FooParser; import(raw: string) { return this.parser().parse(raw); } } class JsonFooImporter extends FooImporter { protected parser() { return new JsonFooParser(); } }
Abstract Factory Pattern
- Kind: pattern
- Severity: contextual
- Scope: product family, component
- Layer: Design Patterns Core
Details
Beforeconst store = env === "test" ? new MemoryFooStore() : new SqlFooStore(); const bus = env === "test" ? new MemoryFooBus() : new KafkaFooBus();
Afterinterface FooPlatformFactory { store(): FooStore; bus(): FooBus; } class TestFooPlatformFactory implements FooPlatformFactory { store() { return new MemoryFooStore(); } bus() { return new MemoryFooBus(); } }
Builder Pattern
- Kind: pattern
- Severity: recommended
- Scope: object construction, API
- Layer: Design Patterns Core
Details
Beforeconst foo = new Foo("foo_1", "Foo", [], 0, false, undefined, "draft");
Afterconst foo = new FooBuilder() .withId("foo_1") .withName("Foo") .withStatus("draft") .build();
Prototype Pattern
- Kind: pattern
- Severity: contextual
- Scope: object creation, runtime
- Layer: Design Patterns Core
Details
Beforefunction copyFoo(foo: Foo) { return new Foo(foo.id, foo.name, [...foo.tags], foo.settings.theme, foo.settings.mode); }
Afterclass FooPrototype { constructor(private readonly base: Foo) {} clone(overrides: Partial<Foo> = {}): Foo { return structuredClone({ ...this.base, ...overrides }); } } const template = new FooPrototype(await buildExpensiveFoo()); const draft = template.clone({ name: "quick" });
Singleton Pattern
- Kind: pattern
- Severity: contextual/discouraged unless justified
- Scope: object creation, lifetime, composition root
- Layer: Design Patterns Core
Details
Beforelet instance: FooService | undefined; function getFooService() { return instance ??= new FooService(); }
Afterclass FooService {} export function composeApp() { const fooService = new FooService(); return { fooService, fooController: new FooController(fooService) }; }
Domain Architecture
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_domain_driven_design["Domain-Driven Design (DDD)"]
n_domain_model["Domain Model"]
n_bounded_context["Bounded Context"]
n_context_mapping["Context Mapping"]
n_anti_corruption_layer["Anti-Corruption Layer"]
n_explicit_boundaries["Explicit Boundaries"]
n_aggregate["Aggregate"]
n_value_object["Value Object"]
n_entity["Entity"]
n_domain_service["Domain Service"]
n_domain_driven_design --> n_bounded_context
n_domain_driven_design --> n_domain_model
n_bounded_context --> n_explicit_boundaries
n_bounded_context --> n_context_mapping
n_context_mapping --> n_bounded_context
n_context_mapping --> n_explicit_boundaries
n_context_mapping --> n_anti_corruption_layer
n_aggregate --> n_explicit_boundaries
n_entity --> n_domain_model
n_entity -.-> n_value_object
n_domain_service --> n_domain_model
n_domain_service -.-> n_aggregateDomain-Driven Design (DDD)
- Kind: style
- Severity: contextual
- Scope: domain, bounded context, system
- Aliases: DDD
- Layer: Domain Modeling
Details
Beforefunction updateFoo(row: FooRow, name: string) { row.name = name; row.updated_at = Date.now(); return fooTable.save(row); }
Afterclass Foo { private constructor(readonly id: FooId, private name: string) {} rename(name: FooName) { this.name = name.value; } } foo.rename(FooName.create(name));
Domain Model
- Kind: artifact
- Severity: contextual
- Scope: domain, bounded context
- Layer: Domain Modeling
Details
Beforetype Foo = { status: string; count: number }; function closeFoo(foo: Foo) { foo.status = "closed"; }
Afterclass Foo { #status: "open" | "closed" = "open"; close() { if (this.#status === "closed") throw new Error("Foo already closed"); this.#status = "closed"; } }
Bounded Context
- Kind: constraint
- Severity: recommended
- Scope: domain, service, team
- Aliases: Bounded Contexts
- Layer: Domain Modeling
Details
Beforetype FooStatus = "A" | "D"; function priceBar(status: FooStatus) { return status === "A" ? 10 : 0; }
Aftertype FooStatus = "active" | "disabled"; type BarEligibility = "eligible" | "ineligible"; function toBarEligibility(status: FooStatus): BarEligibility { return status === "active" ? "eligible" : "ineligible"; }
Context Mapping
- Kind: activity
- Severity: recommended
- Scope: bounded contexts, integration
- Layer: Domain Modeling
Details
BeforefooService.writeDirectly(barDatabase, foo); barService.readDirectly(fooDatabase, foo.id);
Afterconst contextMap = { upstream: "FooContext", downstream: "BarContext", relationship: "published-language", } as const; fooEvents.publish(toBarIntegrationEvent(foo));
Anti-Corruption Layer
- Kind: pattern
- Severity: recommended
- Scope: integration, bounded context boundary
- Layer: Domain Modeling
Details
Beforefunction createBar(fooResponse: FooApiResponse) { return barService.create({ foo_status: fooResponse.state_code }); }
Aftertype BarInput = { eligible: boolean }; function fromFoo(response: FooApiResponse): BarInput { return { eligible: response.state_code === "A" }; } barService.create(fromFoo(fooResponse));
Explicit Boundaries
- Kind: principle
- Severity: mandatory
- Scope: module, component, service, domain
- Layer: Domain Modeling
Details
Beforeimport { fooDatabase } from "../../foo/infrastructure/database"; export function loadBar(id: string) { return fooDatabase.query(id); }
Afterexport interface FooGateway { find(id: FooId): Promise<FooSnapshot>; } export function loadBar(id: FooId, foos: FooGateway) { return foos.find(id); }
Aggregate
- Kind: pattern
- Severity: contextual
- Scope: domain, consistency boundary, bounded context
- Layer: Domain Modeling
Details
BeforefooOrder.total -= item.price; fooOrderItems.delete(item.id);
Afterclass FooOrder { #items: FooItem[] = []; #total = 0; removeItem(id: FooItemId) { this.#items = this.#items.filter(item => item.id !== id); this.#total = this.#items.reduce((sum, item) => sum + item.price, 0); } }
Value Object
- Kind: pattern
- Severity: recommended
- Scope: domain, modeling, immutability
- Layer: Domain Modeling
Details
Beforefunction priceFoo(amount: number, currency: string) { return { amount, currency }; }
Afterclass Money { private constructor(readonly amount: number, readonly currency: string) {} static of(amount: number, currency: string): Money { if (amount < 0) throw new Error("negative money"); return new Money(amount, currency); } equals(other: Money) { return this.amount === other.amount && this.currency === other.currency; } add(other: Money): Money { return Money.of(this.amount + other.amount, this.currency); } }
Entity
- Kind: pattern
- Severity: contextual
- Scope: domain, identity, lifecycle
- Layer: Domain Modeling
Details
Beforetype Foo = { id: string; name: string; status: string }; foo.status = "active";
Afterclass Foo { constructor(readonly id: FooId, private name: string, private status: FooStatus) {} equals(other: Foo) { return this.id === other.id; } activate() { this.status = "active"; } }
Domain Service
- Kind: pattern
- Severity: contextual
- Scope: domain, behavior, coordination
- Layer: Domain Modeling
Details
Beforeclass FooAccount { transferTo(other: FooAccount, amount: number) { this.balance -= amount; other.balance += amount; } }
Afterclass FooTransferService { transfer(from: FooAccount, to: FooAccount, amount: Money) { from.withdraw(amount); to.deposit(amount); } }
Error Handling / Resilience
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_defensive_programming["Defensive Programming"]
n_fail_fast["Fail Fast"]
n_fail_safe["Fail Safe"]
n_fail_secure["Fail Secure"]
n_graceful_degradation["Graceful Degradation"]
n_fault_tolerance["Fault Tolerance"]
n_resilience["Resilience"]
n_robustness_principle["Robustness Principle"]
n_error_handling["Error Handling"]
n_error_boundaries["Error Boundaries"]
n_fallback_pattern["Fallback Pattern"]
n_retry_pattern["Retry Pattern"]
n_timeout_pattern["Timeout Pattern"]
n_circuit_breaker_pattern["Circuit Breaker Pattern"]
n_bulkhead_pattern["Bulkhead Pattern"]
n_backpressure["Backpressure"]
n_defensive_programming --> n_error_handling
n_defensive_programming --> n_fail_fast
n_fail_fast -.-> n_graceful_degradation
n_fail_safe --> n_resilience
n_graceful_degradation --> n_fault_tolerance
n_fault_tolerance --> n_error_handling
n_fault_tolerance --> n_resilience
n_resilience --> n_fault_tolerance
n_error_handling --> n_resilience
n_error_boundaries --> n_resilience
n_fallback_pattern --> n_graceful_degradation
n_retry_pattern --> n_fault_tolerance
n_circuit_breaker_pattern --> n_fault_tolerance
n_circuit_breaker_pattern --> n_backpressure
n_backpressure --> n_resilienceDefensive Programming
- Kind: principle
- Severity: mandatory
- Scope: function, module, boundary
- Layer: Correctness Core
Details
Beforefunction renameFoo(foo: Foo, name: string) { foo.name = name.trim(); }
Afterfunction renameFoo(foo: Foo | undefined, name: unknown) { if (!foo) throw new Error("Foo required"); if (typeof name !== "string" || name.trim().length === 0) throw new Error("valid name required"); return { ...foo, name: name.trim() }; }
Fail Fast
- Kind: principle
- Severity: recommended
- Scope: input, startup, invariant boundary
- Layer: Correctness Core
Details
Beforeconst fooUrl = process.env.FOO_URL ?? "http://localhost:3000"; startFooApp(fooUrl);
Afterconst fooUrl = process.env.FOO_URL; if (!fooUrl) throw new Error("FOO_URL is required"); startFooApp(new URL(fooUrl));
Fail Safe
- Kind: principle
- Severity: mandatory
- Scope: runtime, operation, security
- Layer: Correctness Core
Details
Beforetry { await openFooGate(); } catch { fooGate.unlock(); }
Aftertry { await openFooGate(); } catch { fooGate.lock(); throw new Error("Foo gate remains locked"); }
Fail Secure
- Kind: principle
- Severity: mandatory
- Scope: auth, access, infrastructure
- Layer: Correctness Core
Details
Beforefunction authorizeFoo(token?: string) { if (!token) return { role: "admin" }; return decodeToken(token); }
Afterfunction authorizeFoo(token?: string): FooIdentity { if (!token) throw new UnauthorizedError(); const identity = verifyToken(token); if (!identity) throw new UnauthorizedError(); return identity; }
Graceful Degradation
- Kind: principle
- Severity: recommended
- Scope: service, UX, system
- Layer: Correctness Core
Details
Beforeasync function renderFooPage() { const foo = await fooService.get(); const bar = await barRecommendations.get(); return render(foo, bar); }
Afterasync function renderFooPage() { const foo = await fooService.get(); const bar = await barRecommendations.get().catch(() => [] as Bar[]); return render(foo, bar); }
Fault Tolerance
- Kind: quality-attribute
- Severity: contextual
- Scope: service, system, infrastructure
- Layer: Correctness Core
Details
Beforeconst foo = await fooReplicaA.read(id);
Afterconst foo = await firstSuccessful([ () => fooReplicaA.read(id), () => fooReplicaB.read(id), () => fooReplicaC.read(id), ]);
Resilience
- Kind: quality-attribute
- Severity: mandatory for production systems
- Scope: service, system, infrastructure
- Layer: Correctness Core
Details
Beforeasync function loadFoo(id: FooId) { return remoteFoo.get(id); }
Afterasync function loadFoo(id: FooId) { return circuitBreaker.execute(() => retry.withBackoff(() => remoteFoo.get(id), { attempts: 3 })); }
Robustness Principle
- Kind: principle
- Severity: contextual
- Scope: protocol, API, input processing
- Layer: Correctness Core
Details
Beforefunction readFoo(message: any) { return { id: message.id, name: message.name }; } function writeFoo(foo: Foo) { return { ...foo, debug: globalThis }; }
Afterfunction readFoo(message: unknown) { const value = FooEnvelopeSchema.parse(message); return { id: value.id, name: value.name }; } function writeFoo(foo: Foo): FooEnvelopeV1 { return { version: 1, id: foo.id, name: foo.name }; }
Error Handling
- Kind: principle
- Severity: mandatory
- Scope: function, module, service
- Layer: Correctness Core
Details
Beforeasync function loadFoo(id: FooId) { try { return await fooStore.find(id); } catch { return null; } }
Aftertype LoadFooResult = | { ok: true; value: Foo } | { ok: false; error: "NOT_FOUND" | "STORE_UNAVAILABLE" }; async function loadFoo(id: FooId): Promise<LoadFooResult> { return fooStore.findResult(id); }
Error Boundaries
- Kind: pattern
- Severity: recommended
- Scope: component, UI, service boundary
- Layer: Correctness Core
Details
Beforefunction renderApp() { return renderFooPanel(loadFoo()); }
Afterfunction FooBoundary({ render }: { render(): View }) { try { return render(); } catch (error) { return renderFooError(toFooError(error)); } } const app = FooBoundary({ render: () => renderFooPanel(loadFoo()) });
Fallback Pattern
- Kind: pattern
- Severity: contextual
- Scope: service, dependency call
- Layer: Correctness Core
Details
Beforeconst foo = await primaryFooStore.find(id);
Afterconst foo = await primaryFooStore.find(id).catch(() => replicaFooStore.find(id)); if (!foo) throw new FooUnavailableError(id);
Retry Pattern
- Kind: pattern
- Severity: contextual
- Scope: network, IO, message handling
- Layer: Correctness Core
Details
Beforeawait remoteFoo.save(foo);
Afterawait retry.withBackoff( () => remoteFoo.save(foo), { attempts: 3, retryIf: isTransientError, jitter: true }, );
Timeout Pattern
- Kind: pattern
- Severity: mandatory
- Scope: network, IO, dependency call
- Layer: Correctness Core
Details
Beforeconst foo = await remoteFoo.find(id);
Afterconst foo = await withTimeout(remoteFoo.find(id), 500, () => new FooTimeoutError(id));
Circuit Breaker Pattern
- Kind: pattern
- Severity: contextual
- Scope: dependency call, service
- Layer: Correctness Core
Details
Beforeasync function loadFoo(id: FooId) { return remoteFoo.find(id); }
Afterconst fooBreaker = new CircuitBreaker({ failureThreshold: 5, resetAfterMs: 30_000 }); async function loadFoo(id: FooId) { return fooBreaker.execute(() => remoteFoo.find(id)); }
Bulkhead Pattern
- Kind: pattern
- Severity: contextual
- Scope: resource pool, service, runtime
- Layer: Correctness Core
Details
Beforeconst pool = new WorkerPool(100); pool.submit(fooTask); pool.submit(barTask);
Afterconst fooPool = new WorkerPool(20); const barPool = new WorkerPool(20); fooPool.submit(fooTask); barPool.submit(barTask);
Backpressure
- Kind: mechanism
- Severity: mandatory for high-load systems
- Scope: stream, queue, service
- Layer: Correctness Core
Details
Beforestream.on("data", foo => processFoo(foo));
Afterfor await (const foo of stream) { await capacity.acquire(); void processFoo(foo).finally(() => capacity.release()); }
Event / Messaging / Asynchronous Architecture
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_event_driven_architecture["Event-Driven Architecture"]
n_publish_subscribe_pattern["Publish/Subscribe Pattern"]
n_message_queue["Message Queue"]
n_message_broker["Message Broker"]
n_event_bus["Event Bus"]
n_event_stream["Event Stream"]
n_event_sourcing["Event Sourcing"]
n_command_query_responsibility_segregation["CQRS"]
n_domain_events["Domain Events"]
n_integration_events["Integration Events"]
n_asynchronous_communication["Asynchronous Communication"]
n_service_autonomy["Service Autonomy"]
n_eventual_consistency["Eventual Consistency"]
n_saga_pattern["Saga Pattern"]
n_outbox_pattern["Outbox Pattern"]
n_compensating_transaction["Compensating Transaction"]
n_append_only_log["Append-Only Log"]
n_dead_letter_queue["Dead-Letter Queue"]
n_idempotent_consumer["Idempotent Consumer"]
n_competing_consumers["Competing Consumers"]
n_event_driven_architecture --> n_asynchronous_communication
n_event_driven_architecture --> n_event_sourcing
n_event_driven_architecture --> n_command_query_responsibility_segregation
n_event_bus --> n_event_driven_architecture
n_event_sourcing --> n_append_only_log
n_event_sourcing --> n_domain_events
n_command_query_responsibility_segregation --> n_event_sourcing
n_command_query_responsibility_segregation -.-> n_eventual_consistency
n_domain_events --> n_event_driven_architecture
n_asynchronous_communication --> n_event_driven_architecture
n_saga_pattern --> n_eventual_consistency
n_compensating_transaction --> n_saga_pattern
n_append_only_log --> n_event_sourcing
n_dead_letter_queue --> n_message_queue
n_idempotent_consumer --> n_eventual_consistency
n_competing_consumers --> n_message_queueEvent-Driven Architecture
- Kind: style
- Severity: contextual
- Scope: service, integration, system
- Layer: Execution Core
Details
Beforeasync function createFoo(foo: Foo) { await fooStore.save(foo); await barService.refresh(foo.id); await bazService.notify(foo.id); }
Afterasync function createFoo(foo: Foo) { await fooStore.save(foo); await events.publish({ type: "FooCreated", fooId: foo.id }); } events.on("FooCreated", updateBarProjection); events.on("FooCreated", notifyBaz);
Publish/Subscribe Pattern
- Kind: pattern
- Severity: contextual
- Scope: integration, eventing
- Layer: Execution Core
Details
Beforefunction saveFoo(foo: Foo) { fooStore.save(foo); auditFoo(foo); indexFoo(foo); }
Afterpublisher.publish("foo.saved", { fooId: foo.id }); subscriber.on("foo.saved", auditFoo); subscriber.on("foo.saved", indexFoo);
Message Queue
- Kind: mechanism
- Severity: contextual
- Scope: integration, async processing
- Layer: Execution Core
Details
Beforefor (const foo of foos) await processFoo(foo);
Afterfor (const foo of foos) await fooQueue.enqueue({ type: "ProcessFoo", foo }); fooWorker.consume(fooQueue, message => processFoo(message.foo));
Message Broker
- Kind: artifact
- Severity: contextual
- Scope: integration, messaging
- Layer: Execution Core
Details
Beforeawait fooService.sendToBar(barMessage); await fooService.sendToBaz(bazMessage);
Afterawait broker.publish("foo.created", fooMessage, { durable: true }); broker.subscribe("foo.created", { group: "bar-consumer", ack: "manual" }, handleBar); broker.subscribe("foo.created", { group: "baz-consumer", ack: "manual" }, handleBaz);
Event Bus
- Kind: mechanism
- Severity: contextual
- Scope: application, integration
- Layer: Execution Core
Details
BeforefooEditor.onSave = foo => fooView.refresh(foo); fooEditor.onDelete = id => fooView.remove(id);
AftereventBus.emit({ type: "FooSaved", foo }); eventBus.emit({ type: "FooDeleted", fooId: id }); eventBus.on("FooSaved", event => fooView.refresh(event.foo));
Event Stream
- Kind: mechanism
- Severity: contextual
- Scope: stream processing, integration
- Layer: Execution Core
Details
Beforeconst latest = await fooApi.getCurrentState(fooId);
Afterconst stream = fooEvents.stream(fooId); for await (const event of stream) fooProjection.apply(event);
Event Sourcing
- Kind: pattern
- Severity: contextual
- Scope: domain, persistence
- Layer: Execution Core
Details
Beforetype FooRow = { id: FooId; name: string; status: string }; await fooTable.update(foo);
Aftertype FooEvent = FooCreated | FooRenamed | FooClosed; await fooEventStore.append(foo.id, foo.uncommittedEvents()); const foo = fooEventStore.read(fooId).reduce(applyFooEvent, emptyFoo());
CQRS
- Kind: pattern
- Severity: contextual
- Scope: application, data access
- Aliases: CQRS
- Layer: Execution Core
Details
Beforeclass FooRepository { save(foo: Foo) {} search(query: string): Foo[] { return complexJoin(query); } }
Afterclass FooCommandStore { save(foo: Foo) { return fooDb.write(foo); } } class FooQueryStore { search(query: string) { return fooReadModel.search(query); } } commandBus.execute(new SaveFoo(foo)); queryBus.execute(new SearchFoos(query));
Domain Events
- Kind: pattern
- Severity: recommended
- Scope: domain, bounded context
- Layer: Execution Core
Details
Beforeclass Foo { rename(name: string) { this.name = name; } }
Afterclass Foo { #events: FooDomainEvent[] = []; rename(name: string) { this.name = name; this.#events.push({ type: "FooRenamed", fooId: this.id, name }); } }
Integration Events
- Kind: pattern
- Severity: recommended
- Scope: service boundary, messaging
- Layer: Execution Core
Details
BeforebarService.consume(fooDomainEvent);
Afterconst integrationEvent: FooCreatedV1 = { type: "com.example.foo-created.v1", fooId: event.fooId, occurredAt: clock.now().toISOString(), }; integrationBus.publish(integrationEvent);
Asynchronous Communication
- Kind: principle
- Severity: contextual
- Scope: service, system
- Layer: Execution Core
Details
Beforeconst bar = await barService.createFromFoo(foo); const baz = await bazService.createFromBar(bar);
Afterawait outbox.append({ type: "FooCreated", fooId: foo.id }); return { accepted: true, fooId: foo.id };
Service Autonomy
- Kind: principle
- Severity: contextual
- Scope: service, bounded context
- Layer: Execution Core
Details
Beforeasync function saveFoo(foo: Foo) { await barDb.verify(foo.barId); await bazDb.reserve(foo.bazId); await fooDb.save(foo); }
Afterasync function saveFoo(foo: Foo) { await fooDb.save(foo); await outbox.append({ type: "FooSaved", fooId: foo.id, barId: foo.barId, bazId: foo.bazId }); }
Eventual Consistency
- Kind: model
- Severity: contextual
- Scope: distributed system, data
- Layer: Execution Core
Details
Beforeawait fooStore.save(foo); await fooSearch.update(foo); await fooAnalytics.update(foo);
Afterawait fooStore.save(foo); fooEvents.emit({ type: "FooSaved", foo }); const view = await fooSearchView.find(foo.id); const converged = view.version >= foo.version; return { foo: view, converged };
Saga Pattern
- Kind: pattern
- Severity: contextual
- Scope: service workflow, distributed system
- Layer: Execution Core
Details
Beforeconst tx = coordinator.begin(); await fooService.prepare(tx, foo); await barService.prepare(tx, bar); await bazService.prepare(tx, baz); await coordinator.commit(tx);
Afterawait saga([ { action: () => fooService.create(foo), compensate: id => fooService.cancel(id) }, { action: () => barService.create(bar), compensate: id => barService.cancel(id) }, { action: () => bazService.create(baz), compensate: id => bazService.cancel(id) }, ]).run();
Outbox Pattern
- Kind: pattern
- Severity: recommended
- Scope: persistence, messaging
- Layer: Execution Core
Details
Beforeawait fooStore.save(foo); await eventBus.publish({ type: "FooSaved", fooId: foo.id });
Afterawait database.transaction(async tx => { await tx.foos.save(foo); await tx.outbox.insert({ id: eventId(), type: "FooSaved", fooId: foo.id }); }); await outboxRelay.publishPending();
Compensating Transaction
- Kind: mechanism
- Severity: contextual
- Scope: workflow, distributed transaction
- Layer: Execution Core
Details
Beforeawait fooService.create(foo); await barService.create(bar);
Afterconst fooId = await fooService.create(foo); try { await barService.create(bar); } catch (error) { await fooService.compensateCreate(fooId); throw error; }
Append-Only Log
- Kind: pattern
- Severity: contextual
- Scope: event store, audit, stream
- Layer: Execution Core
Details
BeforefooState.set(foo.id, foo); fooState.delete(foo.id);
Aftertype FooLogEntry = FooCreated | FooUpdated | FooRemoved; fooLog.append({ seq: nextSeq(), type: "FooRemoved", fooId: foo.id }); const state = projectFooLog(fooLog.read());
Dead-Letter Queue
- Kind: pattern
- Severity: mandatory for production systems
- Scope: service, messaging, resilience
- Layer: Execution Core
Details
Beforeworker.consume(fooQueue, async message => { await processFoo(message); });
Afterworker.consume(fooQueue, async message => { try { await processFoo(message); } catch (error) { if (message.attempts >= 5) return fooDeadLetterQueue.send(message, error); throw error; } });
Idempotent Consumer
- Kind: pattern
- Severity: mandatory for distributed systems
- Scope: service, messaging, correctness
- Layer: Execution Core
Details
Beforeworker.consume(fooQueue, message => chargeFoo(message.fooId, message.amount));
Afterworker.consume(fooQueue, async message => { if (await processedMessages.has(message.id)) return; await chargeFoo(message.fooId, message.amount); await processedMessages.add(message.id); });
Competing Consumers
- Kind: pattern
- Severity: contextual
- Scope: service, messaging, scalability
- Layer: Execution Core
Details
BeforefooWorker.consume(fooQueue, processFoo);
Afterfor (let worker = 0; worker < WORKER_COUNT; worker += 1) { new FooWorker(worker).consume(fooQueue, processFoo); }
Metadata / Self-Description / Declarative Systems
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_self_describing_architecture["Self-Describing Architecture"]
n_self_describing_api["Self-Describing API"]
n_self_describing_structures["Self-Describing Structures"]
n_metadata_driven_design["Metadata-Driven Design"]
n_declarative_configuration["Declarative Configuration"]
n_convention_over_configuration["Convention over Configuration"]
n_capability_declaration["Capability Declaration"]
n_manifest_based_design["Manifest-Based Design"]
n_self_describing_architecture --> n_capability_declaration
n_metadata_driven_design --> n_declarative_configuration
n_manifest_based_design --> n_self_describing_architecture
n_manifest_based_design --> n_capability_declarationSelf-Describing Architecture
- Kind: principle
- Severity: contextual
- Scope: system, runtime, integration
- Layer: Declarative Core
Details
Beforeconst modules = [new FooModule(), new BarModule()];
Aftertype ModuleDescriptor = { name: string; version: string; provides: readonly string[]; requires: readonly string[] }; const fooModule = defineModule({ name: "foo", version: "1.0.0", provides: ["FooStore"], requires: ["EventBus"] });
Self-Describing API
- Kind: principle
- Severity: recommended
- Scope: API, integration
- Layer: Declarative Core
Details
Beforeapp.post("/foo", createFoo);
Afterconst createFooApi = defineEndpoint({ method: "POST", path: "/foos", request: CreateFooSchema, response: FooCreatedSchema, errors: FooErrorSchema, });
Self-Describing Structures
- Kind: principle
- Severity: contextual
- Scope: data, runtime, metadata
- Layer: Declarative Core
Details
Beforeconst node = ["foo", "foo_1", 3, true];
Afterconst node = { kind: "foo", id: "foo_1", count: 3, active: true } as const;
Metadata-Driven Design
- Kind: approach
- Severity: contextual
- Scope: runtime, configuration, framework
- Layer: Declarative Core
Details
Beforeif (field === "name") renderText(); if (field === "count") renderNumber();
Afterconst fooFields = { name: { kind: "text", required: true }, count: { kind: "integer", min: 0 }, } as const; renderForm(fooFields);
Declarative Configuration
- Kind: principle
- Severity: recommended
- Scope: configuration, infrastructure, runtime
- Layer: Declarative Core
Details
Beforeconst app = new FooApp(); app.enableCache(); app.setRetries(3); app.register(new BarPlugin());
Afterconst config = defineFooConfig({ cache: { enabled: true }, retries: 3, plugins: ["bar"], }); const app = FooApp.fromConfig(config);
Convention over Configuration
- Kind: principle
- Severity: contextual
- Scope: framework, application structure
- Layer: Declarative Core
Details
BeforeregisterHandler("foo", "./handlers/foo-handler", "FooHandler"); registerHandler("bar", "./handlers/bar-handler", "BarHandler");
Afterconst handlers = discoverHandlers("./handlers/*.handler.ts");
Capability Declaration
- Kind: mechanism
- Severity: recommended
- Scope: plugin, service, runtime
- Layer: Declarative Core
Details
Beforetry { await plugin.exportFoo(foo); } catch (error) { if (isMissingMethod(error)) return; }
Aftertype FooPlugin = { capabilities: readonly ("read" | "write" | "export")[]; exportFoo?: (foo: Foo) => Promise<void>; }; if (plugin.capabilities.includes("export")) await plugin.exportFoo!(foo);
Manifest-Based Design
- Kind: pattern
- Severity: contextual
- Scope: plugin, module, deployment
- Layer: Declarative Core
Details
BeforeloadPlugin("./foo.js"); loadPlugin("./bar.js");
Afterconst manifest = { name: "foo-suite", plugins: [ { name: "foo", entry: "./foo.js", version: "1.0.0" }, { name: "bar", entry: "./bar.js", version: "1.0.0" }, ], } as const; loadManifest(manifest);
Metaprogramming / Language-Oriented Architecture
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_homoiconicity["Homoiconicity"]
n_code_as_data["Code as Data"]
n_metaprogramming["Metaprogramming"]
n_reflection["Reflection"]
n_introspection["Introspection"]
n_compile_time_evaluation["Compile-Time Evaluation"]
n_runtime_code_generation["Runtime Code Generation"]
n_domain_specific_language["Domain-Specific Language (DSL)"]
n_language_oriented_programming["Language-Oriented Programming"]
n_model_driven_architecture["Model-Driven Architecture"]
n_homoiconicity --> n_metaprogramming
n_code_as_data --> n_homoiconicity
n_reflection --> n_introspectionHomoiconicity
- Kind: quality-attribute
- Severity: contextual
- Scope: language, metaprogramming
- Layer: Declarative Core
Details
Beforefunction evaluateFoo(foo: Foo) { return foo.value * 2; } const fooRule = { operation: "multiply", operand: 2 };
Aftertype Expr = | { op: "value"; key: keyof Foo } | { op: "const"; value: number } | { op: "multiply"; left: Expr; right: Expr }; const fooRule: Expr = { op: "multiply", left: { op: "value", key: "value" }, right: { op: "const", value: 2 } }; const result = evaluate(fooRule, foo);
Code as Data
- Kind: principle
- Severity: contextual
- Scope: language, compiler, runtime
- Layer: Declarative Core
Details
Beforefunction fooRule(foo: Foo) { return foo.count > 3 && foo.active; }
Afterconst fooRule = { op: "and", args: [ { op: "gt", field: "count", value: 3 }, { op: "eq", field: "active", value: true }, ], } as const; executeRule(fooRule, foo);
Metaprogramming
- Kind: technique
- Severity: contextual
- Scope: compile-time, runtime, framework
- Layer: Declarative Core
Details
Beforeclass FooDto { id!: string; name!: string; } class BarDto { id!: string; name!: string; }
Afterconst entity = defineEntity({ id: string(), name: string() }); const FooDto = generateType("FooDto", entity); const BarDto = generateType("BarDto", entity);
Reflection
- Kind: mechanism
- Severity: contextual
- Scope: runtime, metadata, framework
- Layer: Declarative Core
Details
Beforeconst fields = ["id", "name", "count"]; for (const field of fields) renderField(foo[field]);
Afterfor (const [field, metadata] of reflect(FooSchema).entries()) { renderField(field, metadata, foo[field]); }
Introspection
- Kind: mechanism
- Severity: contextual
- Scope: runtime, metadata
- Layer: Declarative Core
Details
Beforefunction supportsExport(plugin: any) { try { plugin.exportFoo(foo); return true; } catch { return false; } }
Afterfunction supportsExport(plugin: Plugin) { return introspect(plugin).methods.includes("exportFoo"); }
Compile-Time Evaluation
- Kind: mechanism
- Severity: contextual
- Scope: compiler, build
- Layer: Declarative Core
Details
Beforeconst fooRoutes = buildRoutesAtStartup(fooRouteDefinitions);
Afterconst fooRoutes = compileTime(() => buildRoutes(fooRouteDefinitions)); export const routeTable = fooRoutes;
Runtime Code Generation
- Kind: mechanism
- Severity: contextual/discouraged unless justified
- Scope: runtime, framework
- Layer: Declarative Core
Details
Beforefunction mapFoo(row: any) { return { id: row["foo_id"], name: row["foo_name"], count: row["foo_count"] }; }
Afterconst mapFoo = generateMapper<FooRow, Foo>({ foo_id: "id", foo_name: "name", foo_count: "count", });
Domain-Specific Language (DSL)
- Kind: pattern
- Severity: contextual
- Scope: domain, configuration, rules
- Layer: Declarative Core
Details
BeforecreateWorkflow([ { type: "validate", target: "foo" }, { type: "save", target: "foo" }, { type: "publish", target: "foo.created" }, ]);
AfterfooWorkflow("create", flow => flow.validate(FooSchema) .save("FooStore") .publish("FooCreated") );
Language-Oriented Programming
- Kind: approach
- Severity: contextual
- Scope: domain, platform, code generation
- Layer: Declarative Core
Details
Beforefunction processFoo(config: Record<string, unknown>) { interpretAdHocConfig(config); }
Afterconst FooPolicyLanguage = defineLanguage({ expressions: ["field", "equals", "all", "any"], typeChecker: fooPolicyTypeChecker, evaluator: fooPolicyEvaluator, }); FooPolicyLanguage.run(fooPolicy, foo);
Model-Driven Architecture
- Kind: approach
- Severity: contextual
- Scope: system, code generation, domain model
- Layer: Declarative Core
Details
Beforeclass FooController {} class FooService {} class FooRepository {} class FooDto {}
Afterconst fooModel = defineModel({ entity: "Foo", fields: { id: "FooId", name: "string" }, operations: ["create", "read", "rename"], }); generateApplication(fooModel);
Observability / Auditability / Traceability
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_observability["Observability"]
n_logging["Logging"]
n_monitoring["Monitoring"]
n_alerting["Alerting"]
n_auditability["Auditability"]
n_audit_logging["Audit Logging"]
n_traceability["Traceability"]
n_correlation_id["Correlation ID"]
n_causation_id["Causation ID"]
n_distributed_tracing["Distributed Tracing"]
n_slo_sli["SLO/SLI"]
n_dashboards["Dashboards"]
n_logging --> n_traceability
n_alerting --> n_monitoring
n_auditability --> n_audit_logging
n_auditability --> n_traceability
n_audit_logging --> n_auditability
n_audit_logging --> n_traceability
n_traceability --> n_correlation_id
n_traceability --> n_auditability
n_correlation_id --> n_distributed_tracing
n_distributed_tracing --> n_observability
n_slo_sli --> n_monitoring
n_slo_sli --> n_observability
n_slo_sli --> n_alerting
n_dashboards --> n_monitoring
n_dashboards --> n_observability
n_dashboards --> n_traceabilityObservability
- Kind: quality-attribute
- Severity: mandatory for production systems
- Scope: service, system, runtime
- Layer: Observability
Details
Beforeasync function processFoo(foo: Foo) { await fooStore.save(foo); }
Afterasync function processFoo(foo: Foo, telemetry: Telemetry) { return telemetry.trace("foo.process", { fooId: foo.id }, async span => { await fooStore.save(foo); span.event("foo.saved"); telemetry.count("foo.processed", 1); }); }
Logging
- Kind: mechanism
- Severity: mandatory
- Scope: application, service
- Layer: Observability
Details
Beforeconsole.log("saved", foo);
Afterlogger.info("foo.saved", { fooId: foo.id, version: foo.version });
Monitoring
- Kind: mechanism
- Severity: mandatory
- Scope: service, infrastructure
- Layer: Observability
Details
BeforesetInterval(() => report(fooQueue.length), 60_000);
Aftermetrics.gauge("foo.queue.depth", () => fooQueue.length); metrics.histogram("foo.processing.duration_ms", fooProcessingDuration);
Alerting
- Kind: mechanism
- Severity: mandatory
- Scope: operations, service
- Layer: Observability
Details
Beforeif (errorRate > 0.05) notify("foo errors");
Afteralerts.define("FooErrorBudgetBurn", { condition: rate("foo.errors", "5m") > 0.05, for: "10m", severity: "critical", });
Auditability
- Kind: quality-attribute
- Severity: mandatory for regulated/sensitive systems
- Scope: system, data, security
- Layer: Observability
Details
Beforefunction renameFoo(foo: Foo, name: string) { foo.name = name; }
Afterfunction renameFoo(foo: Foo, name: string, actor: Actor) { const previous = foo.name; foo.rename(name); audit.append({ action: "FooRenamed", fooId: foo.id, actorId: actor.id, previous, next: name }); }
Audit Logging
- Kind: mechanism
- Severity: mandatory for sensitive systems
- Scope: security, compliance, data mutation
- Layer: Observability
Details
Beforelogger.info(`user ${user.id} changed foo ${foo.id}`);
AfterauditLog.append({ eventId: eventId(), action: "FOO_UPDATE", actorId: user.id, resourceId: foo.id, occurredAt: clock.now().toISOString(), });
Traceability
- Kind: quality-attribute
- Severity: mandatory
- Scope: request, workflow, change
- Layer: Observability
Details
Beforeawait processFoo(foo);
Afterconst trace = traceContext.start({ operation: "processFoo", fooId: foo.id }); await processFoo(foo, trace); trace.finish();
Correlation ID
- Kind: mechanism
- Severity: mandatory for distributed systems
- Scope: request, message, workflow
- Layer: Observability
Details
Beforeawait http.post("/bar", { fooId: foo.id });
Afterconst correlationId = request.headers.get("X-Correlation-ID") ?? idSource.next(); await http.post("/bar", { fooId: foo.id }, { headers: { "X-Correlation-ID": correlationId } });
Causation ID
- Kind: mechanism
- Severity: recommended
- Scope: event, message, workflow
- Layer: Observability
Details
Beforeevents.publish({ id: eventId(), type: "BarCreated", fooId: event.fooId });
Afterevents.publish({ id: eventId(), type: "BarCreated", fooId: event.fooId, correlationId: event.correlationId, causationId: event.id, });
Distributed Tracing
- Kind: mechanism
- Severity: mandatory for distributed systems
- Scope: distributed system, service mesh
- Layer: Observability
Details
Beforeawait fooService.call(); await barService.call();
Afterawait tracer.span("foo.request", async span => { await fooService.call({ traceparent: span.traceparent }); await barService.call({ traceparent: span.traceparent }); });
SLO/SLI
- Kind: constraint
- Severity: mandatory for production systems
- Scope: service, reliability, operations
- Layer: Observability
Details
Beforealert.when(latency > 1000);
Afterconst fooLatencySli = ratio("foo.requests.fast", "foo.requests.total"); defineSLO("foo-latency", { sli: fooLatencySli, objective: 0.99, window: "30d", errorBudget: 0.01 });
Dashboards
- Kind: artifact
- Severity: recommended
- Scope: service, operations, visibility
- Layer: Observability
Details
BeforegrepLogsForFooErrors();
Afterconst fooDashboard = dashboard("foo-health", { panels: [rate("foo.errors"), histogram("foo.latency"), gauge("foo.queue.depth")], });
Plugin / Extensibility / IoC
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_plugin_architecture["Plugin Architecture"]
n_extension_points["Extension Points"]
n_inversion_of_control["Inversion of Control (IoC)"]
n_dependency_injection["Dependency Injection"]
n_service_registry["Service Registry"]
n_registry_pattern["Registry Pattern"]
n_service_locator_pattern["Service Locator Pattern"]
n_feature_toggle["Feature Toggle"]
n_plugin_architecture --> n_extension_points
n_extension_points --> n_plugin_architecture
n_inversion_of_control --> n_dependency_injectionPlugin Architecture
- Kind: style
- Severity: contextual
- Scope: component, runtime, system
- Layer: Extensibility Core
Details
Beforeclass FooApp { run() { new FooExport().run(); new BarExport().run(); } }
Afterinterface FooPlugin { name: string; setup(app: FooApp): void; } class FooApp { constructor(private readonly plugins: readonly FooPlugin[]) {} run() { this.plugins.forEach(plugin => plugin.setup(this)); } }
Extension Points
- Kind: mechanism
- Severity: recommended
- Scope: framework, plugin, module
- Layer: Extensibility Core
Details
Beforefunction saveFoo(foo: Foo) { validateFoo(foo); fooStore.save(foo); sendFooEmail(foo); }
Aftertype FooHooks = { beforeSave: Array<(foo: Foo) => void>; afterSave: Array<(foo: Foo) => void> }; function saveFoo(foo: Foo, hooks: FooHooks) { hooks.beforeSave.forEach(hook => hook(foo)); fooStore.save(foo); hooks.afterSave.forEach(hook => hook(foo)); }
Inversion of Control (IoC)
- Kind: principle
- Severity: recommended
- Scope: framework, runtime, component
- Layer: Extensibility Core
Details
Beforeclass FooJob { run() { const store = new SqlFooStore(); return store.save(makeFoo()); } }
Afterclass FooJob { constructor(private readonly make: () => Foo, private readonly store: FooStore) {} run() { return this.store.save(this.make()); } } container.run(FooJob);
Dependency Injection
- Kind: pattern
- Severity: recommended
- Scope: class, module, component
- Layer: Extensibility Core
Details
Beforeclass FooService { private readonly clock = new SystemClock(); private readonly store = new SqlFooStore(); }
Afterclass FooService { constructor(private readonly clock: Clock, private readonly store: FooStore) {} }
Service Registry
- Kind: mechanism
- Severity: contextual
- Scope: runtime, service, plugin
- Layer: Extensibility Core
Details
Beforeconst fooService = new FooService(new SqlFooStore()); const barService = new BarService(new SqlBarStore());
Afterconst services = new ServiceRegistry(); services.register("FooStore", () => new SqlFooStore()); services.register("FooService", r => new FooService(r.resolve("FooStore")));
Registry Pattern
- Kind: pattern
- Severity: contextual
- Scope: runtime, module, plugin
- Layer: Extensibility Core
Details
Beforefunction makeFoo(kind: string) { if (kind === "foo") return new Foo1(); if (kind === "bar") return new Bar(); throw new Error("unknown kind"); }
Aftertype FooFactory = () => Foo; const registry = new Map<string, FooFactory>(); export const registerFoo = (kind: string, factory: FooFactory) => registry.set(kind, factory); export const makeFoo = (kind: string) => registry.get(kind)?.() ?? fail(`unknown ${kind}`);
Service Locator Pattern
- Kind: pattern
- Severity: discouraged
- Scope: runtime, dependency access
- Layer: Extensibility Core
Details
Beforeclass FooController { save(foo: Foo) { const store = serviceLocator.resolve<FooStore>("FooStore"); return store.save(foo); } }
Afterclass FooController { constructor(private readonly store: FooStore) {} save(foo: Foo) { return this.store.save(foo); } }
Feature Toggle
- Kind: mechanism
- Severity: contextual
- Scope: application, release, runtime
- Layer: Extensibility Core
Details
Beforeif (NEW_FOO_FLOW_ENABLED) runNewFooFlow(); else runOldFooFlow();
Afterif (featureFlags.enabled("new-foo-flow", { user, percentage: 10 })) runNewFooFlow(); else runOldFooFlow();
Portability / Infrastructure / Deployment
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_portability["Portability"]
n_platform_independence["Platform Independence"]
n_environment_parity["Environment Parity"]
n_containerization["Containerization"]
n_infrastructure_as_code["Infrastructure as Code"]
n_standards_compliance["Standards Compliance"]
n_protocol_independence["Protocol Independence"]
n_configuration_externalization["Configuration Externalization"]
n_immutable_infrastructure["Immutable Infrastructure"]
n_platform_independence --> n_portability
n_environment_parity --> n_configuration_externalization
n_environment_parity --> n_infrastructure_as_code
n_containerization --> n_portability
n_containerization --> n_environment_parity
n_protocol_independence --> n_portability
n_configuration_externalization --> n_portability
n_configuration_externalization --> n_environment_parity
n_immutable_infrastructure --> n_infrastructure_as_code
n_immutable_infrastructure --> n_environment_parityPortability
- Kind: quality-attribute
- Severity: contextual
- Scope: application, infrastructure, runtime
- Layer: Resource Core
Details
Beforeconst path = "C:\\foo\\data\\foos.json"; const processId = windowsApi.currentProcessId();
Afterconst path = join(config.dataDirectory, "foos.json"); const processId = runtime.processId();
Platform Independence
- Kind: principle
- Severity: contextual
- Scope: application, runtime
- Layer: Resource Core
Details
Beforefunction saveFoo(foo: Foo) { return winRegistry.write("Foo", foo); }
Afterinterface FooPersistence { save(foo: Foo): Promise<void>; } function saveFoo(foo: Foo, persistence: FooPersistence) { return persistence.save(foo); }
Environment Parity
- Kind: principle
- Severity: recommended
- Scope: dev, test, staging, production
- Layer: Resource Core
Details
Beforeif (env === "dev") useMemoryFooStore(); if (env === "prod") useSqlFooStore();
Afterconst container = buildFooImage("foo-app:1.0.0"); runEnvironment("dev", container, devConfig); runEnvironment("prod", container, prodConfig);
Containerization
- Kind: mechanism
- Severity: contextual
- Scope: application, runtime, deployment
- Layer: Resource Core
Details
BeforeinstallFooDependenciesOnHost(); startFooWithHostRuntime();
Afterconst image = containerImage({ base: "node:22-alpine", copy: ["dist", "package.json"], command: ["node", "dist/main.js"], });
Infrastructure as Code
- Kind: activity
- Severity: mandatory for managed infrastructure
- Scope: infrastructure, deployment
- Aliases: IaC
- Layer: Resource Core
Details
Beforeoperator.createDatabase("foo-prod"); operator.openPort(5432);
Afterconst fooDatabase = databaseResource({ name: "foo-prod", engine: "postgres", encrypted: true, networkPolicy: "foo-only", });
Standards Compliance
- Kind: constraint
- Severity: contextual
- Scope: protocol, security, data, infrastructure
- Layer: Resource Core
Details
Beforeconst payload = encodePrivateFooBinary(foo);
Afterconst payload: JsonFooV1 = toJsonFoo(foo); http.send(JSON.stringify(payload), { contentType: "application/json; charset=utf-8" });
Protocol Independence
- Kind: principle
- Severity: recommended
- Scope: integration, service boundary
- Layer: Resource Core
Details
Beforeclass FooService { handleHttp(request: HttpRequest) { return fooStore.save(request.body); } }
Afterclass CreateFoo { constructor(private readonly store: FooStore) {} execute(input: CreateFooInput) { return this.store.save(Foo.create(input)); } } httpAdapter.bind(createFoo); grpcAdapter.bind(createFoo);
Configuration Externalization
- Kind: principle
- Severity: mandatory
- Scope: application, deployment, runtime
- Layer: Resource Core
Details
Beforeconst config = { fooUrl: "https://foo.prod.example", retries: 3, };
Aftertype FooConfig = Readonly<{ fooUrl: URL; retries: number }>; const config = FooConfigSchema.parse({ fooUrl: process.env.FOO_URL, retries: process.env.FOO_RETRIES, });
Immutable Infrastructure
- Kind: approach
- Severity: mandatory for managed infrastructure
- Scope: infrastructure, deployment, reproducibility
- Layer: Resource Core
Details
Beforessh(server, "apt-get update && systemctl restart foo");
Afterconst image = buildFooImage("foo:1.4.0"); replaceInstances("foo", image);
Runtime Discovery / Dynamic Binding
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_runtime_discovery["Runtime Discovery"]
n_service_discovery["Service Discovery"]
n_auto_discovery["Auto-Discovery"]
n_dynamic_binding["Dynamic Binding"]
n_late_binding["Late Binding"]
n_runtime_binding["Runtime Binding"]
n_dynamic_dispatch["Dynamic Dispatch"]
n_runtime_extensibility["Runtime Extensibility"]
n_runtime_discovery --> n_runtime_extensibility
n_runtime_discovery --> n_service_discovery
n_auto_discovery --> n_runtime_discovery
n_late_binding --> n_dynamic_binding
n_late_binding --> n_runtime_extensibility
n_runtime_binding --> n_dynamic_bindingRuntime Discovery
- Kind: mechanism
- Severity: contextual
- Scope: runtime, plugin, service
- Layer: Extensibility Core
Details
Beforeimport { FooHandler } from "./foo-handler"; import { BarHandler } from "./bar-handler"; const handlers = [new FooHandler(), new BarHandler()];
Afterconst modules = await discover<HandlerModule>("./handlers/*.handler.js"); const handlers = modules.map(module => module.create());
Service Discovery
- Kind: mechanism
- Severity: contextual
- Scope: service, network, runtime
- Layer: Extensibility Core
Details
Beforeconst fooUrl = "http://10.0.0.14:8080"; await http.get(`${fooUrl}/foo/${id}`);
Afterconst endpoint = await serviceDiscovery.resolve("foo-service"); await http.get(new URL(`/foo/${id}`, endpoint));
Auto-Discovery
- Kind: mechanism
- Severity: contextual
- Scope: plugin, module, service
- Layer: Extensibility Core
Details
Beforeregister(new FooPlugin()); register(new BarPlugin()); register(new BazPlugin());
Afterfor (const plugin of await scan<Plugin>("./plugins/*.plugin.js")) register(plugin);
Dynamic Binding
- Kind: mechanism
- Severity: contextual
- Scope: runtime, interface, plugin
- Layer: Extensibility Core
Details
Beforeconst formatter = new JsonFooFormatter(); formatter.format(foo);
Afterconst formatter = formatterRegistry.get(config.format); if (!formatter) throw new Error(`unknown formatter: ${config.format}`); formatter.format(foo);
Late Binding
- Kind: mechanism
- Severity: contextual
- Scope: runtime, plugin, module
- Layer: Extensibility Core
Details
Beforeconst store = new SqlFooStore(); export const fooService = new FooService(store);
Afterexport function bootstrap(config: Config) { const store = storeRegistry.create(config.fooStore); return new FooService(store); }
Runtime Binding
- Kind: mechanism
- Severity: contextual
- Scope: runtime, plugin, service
- Layer: Extensibility Core
Details
Beforeimport { FooPolicy } from "./foo-policy"; const policy = new FooPolicy();
Afterconst policyModule = await import(config.fooPolicyModule); const policy: FooPolicy = policyModule.create(config.fooPolicyOptions);
Dynamic Dispatch
- Kind: mechanism
- Severity: recommended
- Scope: method, interface, runtime
- Layer: Extensibility Core
Details
Beforefunction execute(kind: string, foo: Foo) { if (kind === "save") return saveFoo(foo); if (kind === "publish") return publishFoo(foo); }
Afterconst commands: Record<string, (foo: Foo) => unknown> = { save: saveFoo, publish: publishFoo, }; function execute(kind: string, foo: Foo) { const command = commands[kind]; if (!command) throw new Error(`unknown command ${kind}`); return command(foo); }
Runtime Extensibility
- Kind: quality-attribute
- Severity: contextual
- Scope: runtime, plugin, system
- Layer: Extensibility Core
Details
Beforeswitch (pluginName) { case "foo": return new FooPlugin(); case "bar": return new BarPlugin(); }
Afterexport function registerPlugin(name: string, create: () => Plugin) { pluginRegistry.set(name, create); } const plugin = pluginRegistry.get(pluginName)?.();
Scalability / Performance / Optimization
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_scalability["Scalability"]
n_horizontal_scaling["Horizontal Scaling"]
n_vertical_scaling["Vertical Scaling"]
n_elasticity["Elasticity"]
n_load_balancing["Load Balancing"]
n_sharding["Sharding"]
n_partitioning["Partitioning"]
n_caching["Caching"]
n_statelessness["Statelessness"]
n_concurrency["Concurrency"]
n_parallelism["Parallelism"]
n_throughput["Throughput"]
n_latency["Latency"]
n_performance_engineering["Performance Engineering"]
n_algorithmic_efficiency["Algorithmic Efficiency"]
n_time_complexity["Time Complexity"]
n_space_complexity["Space Complexity"]
n_big_o_notation["Big O Notation"]
n_optimization["Optimization"]
n_profiling["Profiling"]
n_benchmarking["Benchmarking"]
n_bottleneck_analysis["Bottleneck Analysis"]
n_resource_utilization["Resource Utilization"]
n_rate_limiting["Rate Limiting"]
n_memory_efficiency["Memory Efficiency"]
n_cdn_edge_caching["CDN / Edge Caching"]
n_read_replica["Read Replica"]
n_queuing_theory["Queuing Theory"]
n_scalability --> n_performance_engineering
n_horizontal_scaling --> n_elasticity
n_elasticity --> n_scalability
n_load_balancing --> n_scalability
n_sharding --> n_horizontal_scaling
n_partitioning --> n_scalability
n_partitioning --> n_parallelism
n_caching --> n_scalability
n_statelessness --> n_horizontal_scaling
n_statelessness --> n_load_balancing
n_concurrency --> n_throughput
n_parallelism --> n_throughput
n_throughput --> n_scalability
n_throughput -.-> n_latency
n_latency --> n_performance_engineering
n_performance_engineering --> n_profiling
n_performance_engineering --> n_benchmarking
n_performance_engineering --> n_scalability
n_algorithmic_efficiency --> n_scalability
n_time_complexity --> n_algorithmic_efficiency
n_time_complexity -.-> n_space_complexity
n_space_complexity --> n_resource_utilization
n_space_complexity -.-> n_time_complexity
n_big_o_notation --> n_algorithmic_efficiency
n_optimization --> n_profiling
n_optimization --> n_performance_engineering
n_profiling --> n_performance_engineering
n_benchmarking --> n_performance_engineering
n_bottleneck_analysis --> n_profiling
n_bottleneck_analysis --> n_optimization
n_resource_utilization --> n_performance_engineering
n_memory_efficiency --> n_scalability
n_cdn_edge_caching --> n_caching
n_cdn_edge_caching --> n_latency
n_read_replica --> n_horizontal_scaling
n_read_replica --> n_load_balancing
n_queuing_theory --> n_latencyScalability
- Kind: quality-attribute
- Severity: contextual
- Scope: service, system, infrastructure
- Layer: Performance Core
Details
Beforeclass FooServer { private readonly foos = new Map<FooId, Foo>(); handle(request: FooRequest) { return processFoo(request, this.foos); } }
Afterclass FooServer { constructor(private readonly store: DistributedFooStore) {} handle(request: FooRequest) { return processFoo(request, this.store); } }
Horizontal Scaling
- Kind: technique
- Severity: contextual
- Scope: service, infrastructure
- Layer: Performance Core
Details
BeforedeployFoo({ replicas: 1, cpu: 32, memoryGb: 128 });
AfterdeployFoo({ replicas: 12, cpu: 2, memoryGb: 4, stateless: true });
Vertical Scaling
- Kind: technique
- Severity: contextual
- Scope: infrastructure, process
- Layer: Performance Core
Details
BeforedeployFoo({ cpu: 1, memoryGb: 1 }); queueFooWhenSaturated();
AfterdeployFoo({ cpu: 8, memoryGb: 32 }); verifyFooCapacity({ targetConcurrency: 200 });
Elasticity
- Kind: quality-attribute
- Severity: contextual
- Scope: deployment, infrastructure
- Layer: Performance Core
Details
BeforedeployFooWorkers({ replicas: 10 });
AfterdeployFooWorkers({ minReplicas: 2, maxReplicas: 50, target: { queueDepthPerReplica: 100 }, });
Load Balancing
- Kind: mechanism
- Severity: contextual
- Scope: traffic, service
- Layer: Performance Core
Details
Beforeconst endpoint = fooServers[0]; endpoint.handle(request);
Afterconst endpoint = fooLoadBalancer.next({ key: request.fooId }); endpoint.handle(request);
Sharding
- Kind: pattern
- Severity: contextual
- Scope: database, storage, messaging
- Layer: Performance Core
Details
Beforeconst foo = await singleFooDatabase.find(id);
Afterconst shard = fooShardMap.resolve(id); const foo = await shard.find(id);
Partitioning
- Kind: technique
- Severity: contextual
- Scope: data, workload, service
- Layer: Performance Core
Details
Beforeconst events = await fooLog.readAll();
Afterconst partition = hash(fooId) % partitionCount; const events = await fooLog.readPartition(partition);
Caching
- Kind: pattern
- Severity: contextual
- Scope: data access, computation, API
- Layer: Performance Core
Details
Beforeasync function loadFoo(id: FooId) { return fooStore.find(id); }
Afterasync function loadFoo(id: FooId) { const cached = await fooCache.get(id); if (cached) return cached; const foo = await fooStore.find(id); if (foo) await fooCache.set(id, foo, { ttlMs: 60_000 }); return foo; }
Statelessness
- Kind: principle
- Severity: recommended
- Scope: service, process, handler
- Layer: Performance Core
Details
Beforeclass FooHandler { private currentUser?: User; handle(request: Request) { this.currentUser = request.user; return processFoo(request, this.currentUser); } }
Afterclass FooHandler { handle(request: Request) { return processFoo(request, request.user); } }
Concurrency
- Kind: model
- Severity: contextual
- Scope: runtime, service, algorithm
- Layer: Performance Core
Details
Beforefor (const foo of foos) await processFoo(foo);
Afterawait Promise.all(foos.map(foo => processFoo(foo)));
Parallelism
- Kind: technique
- Severity: contextual
- Scope: algorithm, processing, runtime
- Layer: Performance Core
Details
Beforeconst results = foos.map(foo => cpuHeavyFoo(foo));
Afterconst results = await workerPool.map(foos, foo => cpuHeavyFoo(foo));
Throughput
- Kind: metric
- Severity: contextual
- Scope: service, pipeline, system
- Layer: Performance Core
Details
Beforefor (const foo of foos) await fooStore.save(foo);
Afterfor (const batch of chunk(foos, 500)) await fooStore.saveBatch(batch);
Latency
- Kind: metric
- Severity: contextual
- Scope: API, service, user flow
- Layer: Performance Core
Details
Beforeasync function renderFoo(id: FooId) { const foo = await fooStore.find(id); const bar = await barStore.find(foo.barId); const baz = await bazStore.find(foo.bazId); return render(foo, bar, baz); }
Afterasync function renderFoo(id: FooId) { const foo = await fooStore.find(id); const [bar, baz] = await Promise.all([ barStore.find(foo.barId), bazStore.find(foo.bazId), ]); return render(foo, bar, baz); }
Performance Engineering
- Kind: activity
- Severity: recommended
- Scope: codebase, service, system
- Layer: Performance Core
Details
BeforeoptimizeFooCode();
Afterconst budget = { p95LatencyMs: 150, throughputPerSecond: 1000 } as const; const profile = await measureFooWorkload(representativeLoad); const change = optimize(profile.hotspot); assertPerformance(change, budget);
Algorithmic Efficiency
- Kind: principle
- Severity: contextual
- Scope: algorithm, data structure
- Layer: Performance Core
Details
Beforefunction hasFoo(foos: Foo[], id: FooId) { return foos.some(foo => foo.id === id); }
Afterfunction indexFoos(foos: readonly Foo[]) { return new Map(foos.map(foo => [foo.id, foo])); } const hasFoo = (index: ReadonlyMap<FooId, Foo>, id: FooId) => index.has(id);
Time Complexity
- Kind: metric
- Severity: contextual
- Scope: algorithm, function
- Layer: Performance Core
Details
Beforefunction duplicateFooIds(foos: Foo[]) { return foos.filter((foo, index) => foos.findIndex(x => x.id === foo.id) !== index); }
Afterfunction duplicateFooIds(foos: readonly Foo[]) { const seen = new Set<FooId>(); return foos.filter(foo => seen.has(foo.id) || !seen.add(foo.id)); }
Space Complexity
- Kind: metric
- Severity: contextual
- Scope: algorithm, process
- Layer: Performance Core
Details
Beforefunction processFoos(stream: AsyncIterable<Foo>) { return collectAll(stream).then(foos => foos.map(transformFoo)); }
Afterasync function* processFoos(stream: AsyncIterable<Foo>) { for await (const foo of stream) yield transformFoo(foo); }
Big O Notation
- Kind: technique
- Severity: contextual
- Scope: algorithm
- Layer: Performance Core
Details
Beforefunction pairFoosWithBars(foos: Foo[], bars: Bar[]) { return foos.flatMap(foo => bars.filter(bar => bar.fooId === foo.id).map(bar => [foo, bar])); }
Afterfunction pairFoosWithBars(foos: readonly Foo[], bars: readonly Bar[]) { const barsByFoo = groupBy(bars, bar => bar.fooId); return foos.flatMap(foo => (barsByFoo.get(foo.id) ?? []).map(bar => [foo, bar])); }
Optimization
- Kind: activity
- Severity: contextual
- Scope: code, database, system
- Layer: Performance Core
Details
Beforeconst fooCache = new Map<FooId, Foo>(); function loadFoo(id: FooId) { return fooCache.get(id) ?? expensiveLoad(id); }
Afterconst profile = profiler.measure("foo.load", representativeFooIds); if (profile.hotspot === "foo-store-read") { enableBoundedFooCache({ maxEntries: 10_000, ttlMs: 30_000 }); }
Profiling
- Kind: technique
- Severity: recommended
- Scope: runtime, code path
- Layer: Performance Core
Details
BeforerewriteFooParserForSpeed();
Afterconst profile = await profiler.capture(() => parseFooBatch(batch)); const hotspot = profile.topFrame(); optimizeFooFrame(hotspot);
Benchmarking
- Kind: activity
- Severity: recommended
- Scope: function, service, system
- Layer: Performance Core
Details
Beforeconst start = clock.now(); runFoo(); report(clock.now() - start);
Afterbenchmark("foo.parse", { warmup: 100, iterations: 10_000, run: () => parseFoo(fixture), });
Bottleneck Analysis
- Kind: activity
- Severity: recommended
- Scope: code path, system
- Layer: Performance Core
Details
BeforeaddMoreFooWorkers();
Afterconst trace = await measureFooPipeline(); const bottleneck = trace.stages.sort((a, b) => b.waitMs - a.waitMs)[0]; removeBottleneck(bottleneck);
Resource Utilization
- Kind: metric
- Severity: contextual
- Scope: CPU, memory, IO, network
- Layer: Performance Core
Details
BeforedeployFoo({ cpu: 16, memoryGb: 64 });
Afterconst sizing = rightSizeFoo({ cpuP95: metrics.cpu("foo", "p95"), memoryP95: metrics.memory("foo", "p95"), headroom: 0.25, }); deployFoo(sizing);
Rate Limiting
- Kind: mechanism
- Severity: mandatory for public APIs
- Scope: API, service, queue
- Layer: Performance Core
Details
Beforeapp.post("/foo", createFoo);
Afterapp.post("/foo", rateLimit({ key: request => request.identity.id, limit: 100, windowMs: 60_000, }), createFoo);
Memory Efficiency
- Kind: quality-attribute
- Severity: contextual
- Scope: algorithm, process, stream
- Layer: Performance Core
Details
Beforeconst copies = foos.map(foo => structuredClone(foo));
Afterfunction* fooViews(foos: readonly Foo[]) { for (const foo of foos) yield { id: foo.id, name: foo.name }; }
CDN / Edge Caching
- Kind: mechanism
- Severity: contextual
- Scope: service, infrastructure, latency
- Layer: Performance Core
Details
Beforeapp.get("/foo/:id/avatar", serveFooAvatarFromOrigin);
Afterapp.get("/foo/:id/avatar", edgeCache({ ttl: "7d", key: request => request.params.id }), serveFooAvatarFromOrigin, );
Read Replica
- Kind: technique
- Severity: contextual
- Scope: service, database, scalability
- Layer: Performance Core
Details
Beforeconst foo = await primaryDb.query(fooQuery); await primaryDb.write(fooCommand);
Afterconst foo = await replicaRouter.read(fooQuery); await primaryDb.write(fooCommand);
Queuing Theory
- Kind: model
- Severity: contextual
- Scope: performance, capacity, system
- Layer: Performance Core
Details
Beforeconst workers = 4;
Afterconst rho = arrivalRate / (workers * serviceRate); if (rho >= 1) throw new Error("unstable queue: utilization >= 1"); const avgWaitMs = mm1WaitTime({ arrivalRate, serviceRate, servers: workers });
Schema / Canonical Data / Semantics
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_schema_validation["Schema Validation"]
n_type_safety["Type Safety"]
n_canonical_model["Canonical Model"]
n_canonical_data_model["Canonical Data Model"]
n_canonical_schema["Canonical Schema"]
n_canonicalization["Canonicalization"]
n_single_source_of_truth["Single Source of Truth"]
n_normalization["Normalization"]
n_semantic_consistency["Semantic Consistency"]
n_ubiquitous_language["Ubiquitous Language"]
n_intent_revealing_interface["Intent-Revealing Interface"]
n_principle_of_least_surprise["Principle of Least Surprise"]
n_database_normalization["Database Normalization"]
n_canonical_model --> n_semantic_consistency
n_canonical_model --> n_ubiquitous_language
n_canonical_model --> n_single_source_of_truth
n_canonical_data_model --> n_canonical_model
n_canonical_data_model --> n_normalization
n_canonical_schema --> n_canonical_data_model
n_canonical_schema --> n_schema_validation
n_semantic_consistency --> n_ubiquitous_language
n_ubiquitous_language --> n_intent_revealing_interface
n_intent_revealing_interface --> n_principle_of_least_surprise
n_principle_of_least_surprise --> n_intent_revealing_interface
n_database_normalization --> n_single_source_of_truthSchema Validation
- Kind: mechanism
- Severity: mandatory
- Scope: data, API, message
- Layer: Contracts Core
Details
Beforeconst foo = JSON.parse(raw) as Foo;
Afterconst FooSchema = object({ id: string(), name: string().min(1), count: integer().min(0) }); const foo = FooSchema.parse(JSON.parse(raw));
Type Safety
- Kind: mechanism
- Severity: mandatory
- Scope: function, module, API, data
- Layer: Contracts Core
Details
Beforefunction loadFoo(id: string): any { return fooStore.get(id); } const count = loadFoo("x").coutn + 1;
Aftertype FooId = string & { readonly __brand: "FooId" }; type Foo = Readonly<{ id: FooId; count: number }>; function loadFoo(id: FooId): Foo | undefined { return fooStore.get(id); }
Canonical Model
- Kind: principle
- Severity: contextual
- Scope: domain, integration, data
- Layer: Contracts Core
Details
Beforetype ApiFoo = { foo_id: string; label: string }; type DbFoo = { id: string; name: string }; type UiFoo = { key: string; title: string };
Aftertype Foo = Readonly<{ id: FooId; name: string }>; const fromApi = (value: ApiFoo): Foo => ({ id: fooId(value.foo_id), name: value.label }); const toUi = (foo: Foo): UiFoo => ({ key: foo.id, title: foo.name });
Canonical Data Model
- Kind: pattern
- Severity: contextual
- Scope: integration, enterprise data
- Layer: Contracts Core
Details
BeforefooTable.insert({ foo_id: foo.id, foo_name: foo.name }); barTable.insert({ id: foo.id, label: foo.name });
Aftertype CanonicalFoo = Readonly<{ id: FooId; name: string }>; fooRepository.save(canonicalFoo); barProjection.apply(canonicalFoo);
Canonical Schema
- Kind: artifact
- Severity: recommended
- Scope: data, message, API
- Layer: Contracts Core
Details
Beforeconst fooSchema = { id: "string", name: "string" }; const barFooSchema = { fooId: "text", label: "text" };
Afterexport const CanonicalFooSchema = schema({ id: fooIdSchema, name: nonEmptyString }); fooApi.use(CanonicalFooSchema); barProjection.use(CanonicalFooSchema);
Canonicalization
- Kind: technique
- Severity: recommended
- Scope: input, data, security
- Layer: Contracts Core
Details
Beforeconst keys = ["Foo", " foo ", "FOO"]; const map = new Map(keys.map(key => [key, loadFoo(key)]));
Afterfunction canonicalFooKey(value: string) { return value.trim().normalize("NFKC").toLowerCase(); } const map = new Map(keys.map(key => [canonicalFooKey(key), loadFoo(canonicalFooKey(key))]));
Single Source of Truth
- Kind: principle
- Severity: mandatory
- Scope: configuration, data, rule, schema
- Layer: Contracts Core
Details
Beforelet fooCount = 0; const foos: Foo[] = []; function addFoo(foo: Foo) { foos.push(foo); fooCount += 1; }
Afterconst foos: Foo[] = []; function addFoo(foo: Foo) { foos.push(foo); } function fooCount() { return foos.length; }
Normalization
- Kind: technique
- Severity: contextual
- Scope: database, schema, data model
- Layer: Contracts Core
Details
Beforetype Foo = { id: FooId; barName: string; barEmail: string }; const foos: Foo[] = duplicateBarAcrossFoos();
Aftertype Foo = { id: FooId; barId: BarId }; type Bar = { id: BarId; name: string; email: string }; const foos = new Map<FooId, Foo>(); const bars = new Map<BarId, Bar>();
Semantic Consistency
- Kind: quality-attribute
- Severity: mandatory
- Scope: domain, API, data
- Layer: Contracts Core
Details
Beforefunction createFoo(name: string) {} function renameFoo(label: string) {} function findFoo(title: string) {}
Aftertype FooName = string & { readonly __brand: "FooName" }; function createFoo(name: FooName) {} function renameFoo(name: FooName) {} function findFoo(name: FooName) {}
Ubiquitous Language
- Kind: activity
- Severity: recommended
- Scope: bounded context, domain, codebase
- Layer: Contracts Core
Details
Beforefunction changeThingState(record: any, code: string) { record.s = code; }
Afterfunction activateFoo(foo: Foo) { foo.activate(); fooEvents.emit({ type: "FooActivated", fooId: foo.id }); }
Intent-Revealing Interface
- Kind: principle
- Severity: recommended
- Scope: API, method, class, module
- Aliases: Intent-Revealing Interfaces, Intent-Revealing API
- Layer: Contracts Core
Details
Beforefoo.update("s", "A"); foo.apply(3, true);
Afterfoo.activate(); foo.reserve({ quantity: 3, notify: true });
Principle of Least Surprise
- Kind: principle
- Severity: recommended
- Scope: API, UX, module behavior
- Layer: Contracts Core
Details
Beforefunction getFoo(id: FooId) { fooStore.delete(id); return undefined; }
Afterfunction getFoo(id: FooId) { return fooStore.find(id); } function deleteFoo(id: FooId) { return fooStore.delete(id); }
Database Normalization
- Kind: technique
- Severity: recommended
- Scope: schema, data modeling, integrity
- Layer: Contracts Core
Details
Beforetype FooRow = { id: string; customerName: string; customerCity: string; customerCityZip: string };
Aftertype Foo = { id: FooId; customerId: CustomerId }; type Customer = { id: CustomerId; name: string; cityId: CityId }; type City = { id: CityId; name: string; zip: string };
Security / Privacy / Compliance / Governance
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_security_by_design["Security by Design"]
n_defense_in_depth["Defense in Depth"]
n_least_privilege["Least Privilege"]
n_zero_trust_architecture["Zero Trust Architecture"]
n_secure_by_default["Secure by Default"]
n_attack_surface_reduction["Attack Surface Reduction"]
n_threat_modeling["Threat Modeling"]
n_authentication["Authentication"]
n_authorization["Authorization"]
n_access_control["Access Control"]
n_role_based_access_control["RBAC"]
n_attribute_based_access_control["ABAC"]
n_input_validation["Input Validation"]
n_output_encoding["Output Encoding"]
n_encryption_at_rest["Encryption at Rest"]
n_encryption_in_transit["Encryption in Transit"]
n_secrets_management["Secrets Management"]
n_privacy_by_design["Privacy by Design"]
n_compliance["Compliance"]
n_governance["Governance"]
n_policy_enforcement["Policy Enforcement"]
n_policy_as_code["Policy as Code"]
n_risk_management["Risk Management"]
n_continuous_compliance["Continuous Compliance"]
n_csrf_protection["CSRF Protection"]
n_parameterized_queries["Parameterized Queries"]
n_session_management["Session Management"]
n_security_by_design --> n_threat_modeling
n_security_by_design --> n_defense_in_depth
n_security_by_design --> n_compliance
n_defense_in_depth --> n_security_by_design
n_least_privilege --> n_access_control
n_zero_trust_architecture --> n_least_privilege
n_attack_surface_reduction --> n_security_by_design
n_threat_modeling --> n_security_by_design
n_threat_modeling --> n_risk_management
n_authentication --> n_access_control
n_authorization --> n_least_privilege
n_access_control --> n_least_privilege
n_role_based_access_control --> n_access_control
n_privacy_by_design --> n_compliance
n_compliance --> n_governance
n_compliance --> n_risk_management
n_governance --> n_compliance
n_policy_enforcement --> n_compliance
n_policy_as_code --> n_continuous_compliance
n_risk_management --> n_compliance
n_risk_management --> n_security_by_design
n_continuous_compliance --> n_policy_as_code
n_continuous_compliance --> n_compliance
n_csrf_protection --> n_authentication
n_csrf_protection --> n_defense_in_depth
n_parameterized_queries --> n_input_validation
n_parameterized_queries --> n_secure_by_default
n_session_management --> n_authentication
n_session_management --> n_access_control
n_session_management --> n_least_privilegeSecurity by Design
- Kind: principle
- Severity: mandatory
- Scope: system, service, codebase
- Layer: Security Core
Details
Beforefunction createFoo(request: Request) { return fooStore.save(request.body as Foo); }
Afterfunction createFoo(request: Request, identity: Identity) { const input = CreateFooSchema.parse(request.body); authorize(identity, "foo:create"); return fooStore.save(Foo.create(input)); }
Defense in Depth
- Kind: principle
- Severity: mandatory
- Scope: system, infrastructure, application
- Layer: Security Core
Details
Beforeapp.post("/foo", createFoo);
Afterapp.post("/foo", authenticate(), authorize("foo:create"), validate(CreateFooSchema), rateLimit({ limit: 100 }), audit("FOO_CREATE"), createFoo, );
Least Privilege
- Kind: principle
- Severity: mandatory
- Scope: user, service, process, data
- Layer: Security Core
Details
Beforeclass FooJob { constructor(private readonly db: AdminDatabase) {} run(foo: Foo) { return this.db.execute(`insert into foo values (?)`, foo); } }
Afterinterface FooWriter { insert(foo: Foo): Promise<void>; } class FooJob { constructor(private readonly foos: FooWriter) {} run(foo: Foo) { return this.foos.insert(foo); } }
Zero Trust Architecture
- Kind: style
- Severity: contextual
- Scope: system, network, identity
- Layer: Security Core
Details
Beforeif (request.network === "internal") return createFoo(request.body);
Afterconst identity = authenticate(request.credentials); authorize(identity, "foo:create", { resource: request.body.id }); verifyDevice(request.deviceAttestation); return createFoo(CreateFooSchema.parse(request.body));
Secure by Default
- Kind: principle
- Severity: mandatory
- Scope: configuration, API, product
- Layer: Security Core
Details
Beforeconst fooApi = createApi({ public: true, tls: false, audit: false });
Afterconst fooApi = createApi({ public: false, tls: "required", authentication: "required", audit: true, });
Attack Surface Reduction
- Kind: principle
- Severity: mandatory
- Scope: API, service, infrastructure
- Layer: Security Core
Details
Beforeapp.enableDebugConsole(); app.exposeAdminApi(); app.loadAllPlugins();
Afterapp.register(fooPublicApi); app.disable("debug-console"); app.disable("admin-api"); app.loadPlugins(approvedFooPlugins);
Threat Modeling
- Kind: activity
- Severity: mandatory for sensitive systems
- Scope: feature, system, architecture
- Layer: Security Core
Details
BeforedesignFooUpload(); shipFooUpload();
Afterconst threats = modelThreats(fooUploadFlow, ["spoofing", "tampering", "repudiation", "disclosure", "denial", "elevation"]); for (const threat of threats) requireMitigation(threat); shipFooUpload();
Authentication
- Kind: mechanism
- Severity: mandatory
- Scope: user, service, API
- Layer: Security Core
Details
Beforeconst userId = request.headers.get("X-User-ID"); return loadFooFor(userId!);
Afterconst credential = requireHeader(request, "Authorization"); const identity = await authenticator.verify(credential); if (!identity) throw new UnauthorizedError(); return loadFooFor(identity.subject);
Authorization
- Kind: mechanism
- Severity: mandatory
- Scope: API, domain action, data access
- Layer: Security Core
Details
Beforeconst identity = authenticate(request); return fooStore.delete(request.params.id);
Afterconst identity = authenticate(request); authorize(identity, "foo:delete", { fooId: request.params.id }); return fooStore.delete(request.params.id);
Access Control
- Kind: mechanism
- Severity: mandatory
- Scope: API, data, infrastructure
- Layer: Security Core
Details
Beforeif (user.role === "admin") return fooStore.findAll();
Afterconst decision = accessPolicy.evaluate({ subject: user, action: "foo:list", resource: { tenantId: request.tenantId }, }); if (!decision.allowed) throw new ForbiddenError(); return fooStore.findAll(request.tenantId);
RBAC
- Kind: model
- Severity: contextual
- Scope: user, role, resource
- Layer: Security Core
Details
Beforeif (user.name === "Developer") allowDeleteFoo();
Afterconst roles = new Map([ ["foo-reader", ["foo:read"]], ["foo-editor", ["foo:read", "foo:write"]], ["foo-admin", ["foo:read", "foo:write", "foo:delete"]], ]); authorizeRole(user.roles, "foo:delete", roles);
ABAC
- Kind: model
- Severity: contextual
- Scope: user, resource, context
- Layer: Security Core
Details
Beforeif (user.role === "editor") return updateFoo(foo);
Afterconst decision = policy.evaluate({ subject: { id: user.id, department: user.department }, action: "foo:update", resource: { ownerId: foo.ownerId, classification: foo.classification }, environment: { time: clock.now() }, }); if (!decision.allowed) throw new ForbiddenError();
Input Validation
- Kind: mechanism
- Severity: mandatory
- Scope: API, boundary, function
- Layer: Security Core
Details
Beforeconst input = request.body as Foo; fooStore.save(input);
Afterconst input = CreateFooSchema.parse(request.body); fooStore.save(input);
Output Encoding
- Kind: mechanism
- Severity: mandatory
- Scope: UI, API, serialization
- Layer: Security Core
Details
Beforeresponse.html(`<div>${foo.name}</div>`);
Afterresponse.html(`<div>${escapeHtml(foo.name)}</div>`);
Encryption at Rest
- Kind: mechanism
- Severity: mandatory for sensitive data
- Scope: storage, database, backups
- Layer: Security Core
Details
Beforeawait disk.write("foos.json", JSON.stringify(foos));
Afterconst ciphertext = await keyManager.encrypt("foo-data-key", JSON.stringify(foos)); await disk.write("foos.enc", ciphertext);
Encryption in Transit
- Kind: mechanism
- Severity: mandatory
- Scope: network, service communication
- Layer: Security Core
Details
Beforeconst client = new HttpClient("http://foo.internal");
Afterconst client = new HttpClient("https://foo.internal", { tls: { minVersion: "TLSv1.3", verifyPeer: true }, });
Secrets Management
- Kind: activity
- Severity: mandatory
- Scope: config, deployment, runtime
- Layer: Security Core
Details
Beforeconst fooClient = new FooClient({ apiKey: "foo_live_abc123" });
Afterconst apiKey = await secretStore.read("services/foo/api-key"); if (!apiKey) throw new Error("missing foo api key"); const fooClient = new FooClient({ apiKey });
Privacy by Design
- Kind: principle
- Severity: mandatory for PII systems
- Scope: data, product, system
- Layer: Security Core
Details
BeforeauditLog.append({ user, request, foo, headers: request.headers });
AfterauditLog.append({ actorId: pseudonymize(user.id), action: "FOO_READ", fooId: foo.id, purpose: "support", });
Compliance
- Kind: constraint
- Severity: contextual/mandatory when regulated
- Scope: system, organization, process
- Layer: Security Core
Details
BeforestoreFooData(foo);
Afterconst classified = classify(foo); const controls = compliance.requirements(classified, "foo-storage"); await enforceControls(controls); await storeFooData(foo);
Governance
- Kind: principle
- Severity: contextual
- Scope: organization, architecture, platform
- Layer: Security Core
Details
Beforeteams.defineFooApisIndependently();
Afterconst governance = defineArchitecturePolicy({ apiVersioning: "required", schemaRegistry: "required", ownership: "single-team", }); architectureGate.enforce(governance);
Policy Enforcement
- Kind: mechanism
- Severity: mandatory
- Scope: code, infrastructure, runtime
- Layer: Security Core
Details
Beforeif (!policyAllows(user, foo)) fooLog.record("policy violation"); return updateFoo(foo);
Afterif (!policyAllows(user, foo)) throw new ForbiddenError(); return updateFoo(foo);
Policy as Code
- Kind: mechanism
- Severity: recommended
- Scope: infrastructure, deployment, security
- Layer: Security Core
Details
Beforedocument.write("Only foo-admin may delete Foo");
Afterconst fooDeletePolicy = policy({ action: "foo:delete", allow: input => input.subject.roles.includes("foo-admin"), }); policyGate.enforce(fooDeletePolicy);
Risk Management
- Kind: activity
- Severity: contextual
- Scope: architecture, security, delivery
- Layer: Security Core
Details
BeforeshipFooFeature();
Afterconst risk = assessRisk(fooFeature, { likelihood: 3, impact: 5, controls: ["rate-limit", "audit", "rollback"], }); if (risk.residual > riskTolerance) throw new Error("risk not accepted"); shipFooFeature();
Continuous Compliance
- Kind: capability
- Severity: contextual
- Scope: CI/CD, infrastructure, codebase
- Layer: Security Core
Details
BeforerunComplianceAuditOncePerYear();
Afterpipeline.on("change", async change => { const result = await complianceScanner.evaluate(change); if (!result.compliant) throw new ComplianceGateError(result.violations); });
CSRF Protection
- Kind: mechanism
- Severity: mandatory for public APIs
- Scope: service, web, security
- Layer: Security Core
Details
Beforeapp.post("/foo/delete", deleteFoo);
Afterapp.post("/foo/delete", verifyCsrfToken(), requireSameSite(), deleteFoo);
Parameterized Queries
- Kind: mechanism
- Severity: mandatory
- Scope: service, database, security
- Layer: Security Core
Details
Beforedb.query(`select * from foos where id = '${id}'`);
Afterdb.query("select * from foos where id = $1", [id]);
Session Management
- Kind: mechanism
- Severity: mandatory for sensitive systems
- Scope: service, authentication, security
- Layer: Security Core
Details
Beforeres.cookie("userId", user.id);
Afterconst session = await sessions.create(user.id, { ttlMs: 3_600_000, rotateOnAuth: true }); res.cookie("sid", session.id, { httpOnly: true, secure: true, sameSite: "strict" });
Self-Healing / Recovery / Deployment Safety
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_self_healing_architecture["Self-Healing Architecture"]
n_autonomous_recovery["Autonomous Recovery"]
n_health_checks["Health Checks"]
n_failover["Failover"]
n_redundancy["Redundancy"]
n_replication["Replication"]
n_auto_scaling["Auto-Scaling"]
n_auto_remediation["Auto-Remediation"]
n_rollback["Rollback"]
n_blue_green_deployment["Blue-Green Deployment"]
n_canary_deployment["Canary Deployment"]
n_chaos_engineering["Chaos Engineering"]
n_graceful_shutdown["Graceful Shutdown"]
n_raid_redundancy["RAID Redundancy"]
n_self_healing_architecture --> n_health_checks
n_self_healing_architecture --> n_autonomous_recovery
n_failover --> n_redundancy
n_redundancy --> n_failover
n_replication --> n_failover
n_blue_green_deployment --> n_rollback
n_chaos_engineering --> n_self_healing_architecture
n_raid_redundancy --> n_redundancySelf-Healing Architecture
- Kind: capability
- Severity: contextual
- Scope: system, infrastructure, runtime
- Layer: Correctness Core
Details
Beforeprocess.on("error", error => fooLog.record(error));
Aftersupervisor.watch("foo-worker", { start: startFooWorker, health: fooWorkerHealth, restart: { maxAttempts: 5, backoffMs: 1000 }, });
Autonomous Recovery
- Kind: capability
- Severity: contextual
- Scope: service, infrastructure
- Layer: Correctness Core
Details
Beforeif (fooProjection.failed) operator.rebuild(fooProjection);
AfterfooProjection.onFailure(async checkpoint => { await fooProjection.reset(checkpoint.lastValidOffset); await fooProjection.replay(); });
Health Checks
- Kind: mechanism
- Severity: mandatory for services
- Scope: service, deployment, runtime
- Layer: Correctness Core
Details
Beforeapp.get("/health", () => "ok");
Afterapp.get("/health", async () => { const fooStoreOk = await fooStore.ping(); const eventBusOk = await eventBus.ping(); return { state: fooStoreOk && eventBusOk ? "ready" : "blocked", checks: { fooStore: fooStoreOk, eventBus: eventBusOk }, }; });
Failover
- Kind: mechanism
- Severity: contextual
- Scope: service, infrastructure, data
- Layer: Correctness Core
Details
Beforeconst foo = await primaryFooStore.find(id);
Afterconst foo = await failover.read([ primaryFooStore, secondaryFooStore, ], store => store.find(id));
Redundancy
- Kind: mechanism
- Severity: contextual
- Scope: infrastructure, service, data
- Layer: Correctness Core
Details
Beforeconst fooService = deploy({ replicas: 1 });
Afterconst fooService = deploy({ replicas: 3, spreadAcross: ["zone-a", "zone-b", "zone-c"] });
Replication
- Kind: mechanism
- Severity: contextual
- Scope: database, service, cache
- Layer: Correctness Core
Details
Beforeawait primaryFooStore.save(foo);
Afterawait replicatedFooStore.save(foo, { replicas: 3, writeQuorum: 2 });
Auto-Scaling
- Kind: capability
- Severity: contextual
- Scope: deployment, service, infrastructure
- Layer: Correctness Core
Details
BeforedeployFooWorkers({ replicas: 4 });
AfterdeployFooWorkers({ minReplicas: 2, maxReplicas: 20, scaleOn: { queueDepthPerWorker: 100 }, scaleInCooldownSeconds: 300, });
Auto-Remediation
- Kind: capability
- Severity: contextual
- Scope: runtime, infrastructure
- Layer: Correctness Core
Details
Beforealert.on("FooDiskFull", notifyOperator);
Afteralert.on("FooDiskFull", async event => { await fooStorage.compact(event.volumeId); await fooStorage.verify(event.volumeId); });
Rollback
- Kind: mechanism
- Severity: mandatory
- Scope: deployment, release
- Layer: Correctness Core
Details
Beforedeploy(fooVersion);
Afterconst release = await deploy(fooVersion); if (!(await release.verify())) await release.rollback(previousFooVersion);
Blue-Green Deployment
- Kind: pattern
- Severity: contextual
- Scope: deployment, release
- Layer: Correctness Core
Details
BeforerouteAllTraffic(deployFoo("v2"));
Afterconst green = await deployFoo("v2"); await verify(green); await router.switch({ from: "blue", to: "green" });
Canary Deployment
- Kind: pattern
- Severity: contextual
- Scope: deployment, release
- Layer: Correctness Core
Details
Beforeawait router.route("foo-v2", 100);
Afterawait router.route("foo-v2", 5); await verifyCanary({ errorRate: 0.01, latencyP95Ms: 200 }); await router.progressiveShift("foo-v2", [25, 50, 100]);
Chaos Engineering
- Kind: activity
- Severity: contextual
- Scope: system, resilience, operations
- Layer: Correctness Core
Details
BeforeassumeFooSurvivesZoneLoss();
Afterchaos.experiment("foo-zone-loss", { inject: () => killZone("zone-a"), hypothesis: () => fooHealth.available(), });
Graceful Shutdown
- Kind: mechanism
- Severity: mandatory for production systems
- Scope: service, runtime, resilience
- Layer: Correctness Core
Details
Beforeprocess.on("SIGTERM", () => process.exit(0));
Afterprocess.on("SIGTERM", async () => { server.stopAccepting(); await fooQueue.drain(); await server.close(); process.exit(0); });
RAID Redundancy
- Kind: technique
- Severity: mandatory for managed infrastructure
- Scope: storage, redundancy, infrastructure
- Layer: Correctness Core
Details
Beforeconst store = new SingleDiskFooStore("/dev/sda");
Afterconst store = new FooStore({ volume: raidArray({ level: 10, disks: ["/dev/sda", "/dev/sdb", "/dev/sdc", "/dev/sdd"] }), });
SOLID / Object-Oriented Design
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_interface_segregation["Interface Segregation Principle (ISP)"]
n_dependency_inversion["Dependency Inversion Principle (DIP)"]
n_open_closed["Open/Closed Principle (OCP)"]
n_liskov_substitution["Liskov Substitution Principle (LSP)"]
n_polymorphism["Polymorphism"]
n_liskov_substitution --> n_polymorphism
n_polymorphism --> n_open_closedInterface Segregation Principle (ISP)
- Kind: principle
- Severity: mandatory
- Scope: interface, service, module
- Layer: Structural Core
Details
Beforeinterface FooWorker { load(id: FooId): Foo; save(foo: Foo): void; delete(id: FooId): void; export(): string; } class FooReader implements FooWorker {}
Afterinterface FooReader { load(id: FooId): Foo; } interface FooWriter { save(foo: Foo): void; } interface FooRemover { delete(id: FooId): void; } class CachedFooReader implements FooReader { load(id: FooId) { return fooCache.get(id)!; } }
Dependency Inversion Principle (DIP)
- Kind: principle
- Severity: mandatory
- Scope: module, component, layer
- Aliases: DIP
- Layer: Structural Core
Details
Beforeclass FooService { private readonly store = new SqlFooStore(); save(foo: Foo) { return this.store.save(foo); } }
Afterinterface FooStore { save(foo: Foo): Promise<void>; } class FooService { constructor(private readonly store: FooStore) {} save(foo: Foo) { return this.store.save(foo); } }
Open/Closed Principle (OCP)
- Kind: principle
- Severity: recommended
- Scope: class, module, component
- Aliases: OCP
- Layer: Structural Core
Details
Beforefunction priceFoo(kind: string, value: number) { if (kind === "foo") return value; if (kind === "bar") return value * 2; throw new Error("unknown kind"); }
Afterinterface FooPricing { price(value: number): number; } const registry = new Map<string, FooPricing>(); export function registerPricing(kind: string, pricing: FooPricing) { registry.set(kind, pricing); } export function priceFoo(kind: string, value: number) { const pricing = registry.get(kind); if (!pricing) throw new Error(`unknown kind ${kind}`); return pricing.price(value); } registerPricing("bar", { price: value => value * 2 });
Liskov Substitution Principle (LSP)
- Kind: principle
- Severity: mandatory
- Scope: class, interface, type hierarchy
- Aliases: LSP
- Layer: Structural Core
Details
Beforeclass FooStore { save(foo: Foo): Promise<Receipt> { return persist(foo); } } class ReadOnlyFooStore extends FooStore { save(): Promise<Receipt> { throw new Error("not supported"); } }
Afterclass FooStore { save(foo: Foo): Promise<Receipt> { return persist(foo); } } class AuditedFooStore extends FooStore { async save(foo: Foo): Promise<Receipt> { const receipt = await super.save(foo); audit.record(receipt); return receipt; } }
Polymorphism
- Kind: mechanism
- Severity: recommended
- Scope: class, interface, runtime
- Layer: Structural Core
Details
Beforefunction renderFoo(kind: string, foo: Foo) { if (kind === "text") return foo.name; if (kind === "json") return JSON.stringify(foo); throw new Error("unknown renderer"); }
Afterinterface FooRenderer { render(foo: Foo): string; } class TextFooRenderer implements FooRenderer { render(foo: Foo) { return foo.name; } } class JsonFooRenderer implements FooRenderer { render(foo: Foo) { return JSON.stringify(foo); } } function renderFoo(renderer: FooRenderer, foo: Foo) { return renderer.render(foo); }
Streaming / Pipeline / Dataflow Processing
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_streaming_architecture["Streaming Architecture"]
n_single_pass_processing["Single-Pass Processing"]
n_pipeline_architecture["Pipeline Architecture"]
n_lazy_evaluation["Lazy Evaluation"]
n_sequential_access["Sequential Access"]
n_forward_only_processing["Forward-Only Processing"]
n_dataflow_architecture["Dataflow Architecture"]
n_stateless_processing["Stateless Processing"]
n_windowing["Windowing"]
n_fan_out_fan_in["Fan-out/Fan-in"]
n_batch_vs_stream["Batch-vs-Stream"]
n_streaming_architecture --> n_single_pass_processing
n_forward_only_processing --> n_single_pass_processing
n_dataflow_architecture --> n_pipeline_architecture
n_windowing --> n_streaming_architectureStreaming Architecture
- Kind: style
- Severity: contextual
- Scope: data processing, integration
- Layer: Execution Core
Details
Beforeconst foos = await source.readAll(); const results = foos.map(transformFoo); await sink.writeAll(results);
Afterfor await (const foo of source.stream()) { await sink.write(transformFoo(foo)); }
Single-Pass Processing
- Kind: principle
- Severity: contextual
- Scope: algorithm, stream, parser
- Layer: Execution Core
Details
Beforeconst names = foos.map(foo => foo.name); const active = foos.filter(foo => foo.active); const total = foos.reduce((sum, foo) => sum + foo.count, 0);
Afterconst names: string[] = []; const active: Foo[] = []; let total = 0; for (const foo of foos) { names.push(foo.name); if (foo.active) active.push(foo); total += foo.count; }
Pipeline Architecture
- Kind: pattern
- Severity: recommended
- Scope: processing, dataflow, build
- Layer: Execution Core
Details
Beforefunction processFoo(raw: string) { const parsed = JSON.parse(raw); const validated = validateFoo(parsed); const normalized = normalizeFoo(validated); return saveFoo(normalized); }
Afterconst fooPipeline = pipeline( parseJson, validateWith(FooSchema), normalizeFoo, saveFoo, ); fooPipeline.run(raw);
Lazy Evaluation
- Kind: approach
- Severity: contextual
- Scope: computation, collection, stream
- Layer: Execution Core
Details
Beforeconst normalized = millionFoos.map(normalizeFoo); const active = normalized.filter(foo => foo.active); const firstTen = active.slice(0, 10);
Afterconst firstTen = sequence(millionFoos) .map(normalizeFoo) .filter(foo => foo.active) .take(10) .toArray();
Sequential Access
- Kind: pattern
- Severity: contextual
- Scope: file, stream, iterator
- Layer: Execution Core
Details
Beforefor (const id of fooIds) await fooStore.randomRead(id);
Afterfor await (const foo of fooStore.scan({ orderBy: "id" })) { processFoo(foo); }
Forward-Only Processing
- Kind: constraint
- Severity: contextual
- Scope: stream, parser, iterator
- Layer: Execution Core
Details
Beforeconst cursor = fooStream.cursor(); cursor.next(); cursor.previous(); cursor.seek(0);
Afterfor await (const foo of fooStream) { await processFoo(foo); }
Dataflow Architecture
- Kind: style
- Severity: contextual
- Scope: processing, workflow, stream
- Layer: Execution Core
Details
Beforecontroller.runFoo(); controller.runBar(); controller.runBaz();
Afterconst graph = dataflow() .source("foo", fooSource) .map("bar", "foo", toBar) .map("baz", "bar", toBaz) .sink("output", "baz", bazSink); await graph.run();
Stateless Processing
- Kind: principle
- Severity: recommended
- Scope: function, stream processor, service
- Layer: Execution Core
Details
Beforeclass FooProcessor { private previous?: Foo; process(foo: Foo) { const result = merge(this.previous, foo); this.previous = foo; return result; } }
Afterfunction processFoo(foo: Foo, context: Readonly<FooContext>): FooResult { return deriveFooResult(foo, context); }
Windowing
- Kind: mechanism
- Severity: contextual
- Scope: data processing, streaming, aggregation
- Layer: Execution Core
Details
Beforeconst total = allFooEvents.reduce((sum, event) => sum + event.value, 0);
Afterfor await (const window of fooStream.tumbling({ seconds: 60 })) { emit(window.start, window.events.reduce((sum, event) => sum + event.value, 0)); }
Fan-out/Fan-in
- Kind: pattern
- Severity: contextual
- Scope: data processing, parallelism, pipeline
- Layer: Execution Core
Details
Beforeconst report = await buildFullFooReport(foos);
Afterconst partials = await fanOut(partition(foos), buildPartialFooReport); const report = fanIn(partials, mergeFooReports);
Batch-vs-Stream
- Kind: approach
- Severity: contextual
- Scope: data processing, latency, architecture
- Layer: Execution Core
Details
Beforeschedule.daily(() => reprocessAllFoos());
AfterfooStream.subscribe(foo => processFoo(foo));
Structural Patterns
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_adapter_pattern["Adapter Pattern"]
n_facade_pattern["Facade Pattern"]
n_proxy_pattern["Proxy Pattern"]
n_bridge_pattern["Bridge Pattern"]
n_decorator_pattern["Decorator Pattern"]
n_composite_pattern["Composite Pattern"]
n_flyweight_pattern["Flyweight Pattern"]Adapter Pattern
- Kind: pattern
- Severity: mandatory
- Scope: integration, boundary
- Layer: Design Patterns Core
Details
Beforefunction saveFoo(foo: Foo) { return legacyClient.put(foo.id, foo.name, foo.count); }
Afterclass LegacyFooAdapter implements FooStore { constructor(private readonly client: LegacyClient) {} save(foo: Foo) { return this.client.put(foo.id, foo.name, foo.count); } }
Facade Pattern
- Kind: pattern
- Severity: recommended
- Scope: module, subsystem, API
- Layer: Design Patterns Core
Details
Beforeconst foo = fooValidator.validate(fooParser.parse(raw)); await fooStore.save(foo); await fooEvents.publish(foo);
Afterclass FooFacade { async create(raw: string) { const foo = fooValidator.validate(fooParser.parse(raw)); await fooStore.save(foo); await fooEvents.publish(foo); } }
Proxy Pattern
- Kind: pattern
- Severity: contextual
- Scope: access control, remote access, lazy loading
- Layer: Design Patterns Core
Details
Beforefunction loadFoo(id: FooId) { return remoteFooStore.find(id); }
Afterclass CachingFooStoreProxy implements FooStore { constructor(private readonly target: FooStore) {} async find(id: FooId) { const cached = fooCache.get(id); if (cached) return cached; const foo = await this.target.find(id); fooCache.set(id, foo); return foo; } }
Bridge Pattern
- Kind: pattern
- Severity: contextual
- Scope: abstraction, implementation variation
- Layer: Design Patterns Core
Details
Beforeclass SqlJsonFooExporter {} class SqlCsvFooExporter {} class MemoryJsonFooExporter {} class MemoryCsvFooExporter {}
Afterinterface FooSource { read(): Promise<readonly Foo[]>; } interface FooFormat { encode(foos: readonly Foo[]): string; } class FooExporter { constructor(private readonly source: FooSource, private readonly format: FooFormat) {} async export() { return this.format.encode(await this.source.read()); } }
Decorator Pattern
- Kind: pattern
- Severity: contextual
- Scope: behavior composition
- Layer: Design Patterns Core
Details
Beforeclass LoggedSqlFooStore extends SqlFooStore { override save(foo: Foo) { logger.info("foo.saved", { fooId: foo.id }); return super.save(foo); } }
Afterclass LoggedFooStore implements FooStore { constructor(private readonly inner: FooStore, private readonly log: Log) {} save(foo: Foo) { this.log.write(foo.id); return this.inner.save(foo); } }
Composite Pattern
- Kind: pattern
- Severity: recommended
- Scope: structure, tree, hierarchy
- Layer: Design Patterns Core
Details
Beforefunction totalFoo(item: Foo | FooGroup): number { if ("children" in item) return item.children.reduce((sum, child) => sum + totalFoo(child), 0); return item.value; }
Afterinterface FooComponent { total(): number; } class FooLeaf implements FooComponent { constructor(private readonly value: number) {} total() { return this.value; } } class FooGroup implements FooComponent { constructor(private readonly children: readonly FooComponent[]) {} total() { return this.children.reduce((sum, child) => sum + child.total(), 0); } }
Flyweight Pattern
- Kind: pattern
- Severity: contextual
- Scope: structure, memory, sharing
- Layer: Design Patterns Core
Details
Beforeconst icons = foos.map(foo => new FooIcon(foo.position, loadSprite(foo.kind)));
Afterconst spriteCache = new Map<string, Sprite>(); function fooSprite(kind: string) { const cached = spriteCache.get(kind); if (cached) return cached; const sprite = loadSprite(kind); spriteCache.set(kind, sprite); return sprite; } const icons = foos.map(foo => ({ position: foo.position, sprite: fooSprite(foo.kind) }));
Taxonomy / Classification / Naming
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_closed_vocabulary["Closed Vocabulary"]
n_positional_slot_resolution["Positional Slot Resolution"]
n_concern_folder_correspondence["Concern-Folder Correspondence"]
n_glob_resolvable_tree["Glob-Resolvable Tree"]
n_declared_jurisdiction["Declared Jurisdiction"]
n_bounded_nesting_depth["Bounded Nesting Depth"]
n_sideways_overflow["Sideways Overflow"]
n_one_concern_per_file["One Concern Per File"]
n_narrowest_concern["Narrowest Concern"]
n_layer_spine_precedence["Layer Spine Precedence"]
n_agnostic_first_vocabulary["Agnostic-First Vocabulary"]
n_guided_vocabulary_refusal["Guided Vocabulary Refusal"]
n_derived_naming_registry["Derived Naming Registry"]
n_member_never_restates_the_set["Member Never Restates the Set"]
n_manual_identity_migration["Manual Identity Migration"]
n_closed_vocabulary --> n_concern_folder_correspondence
n_positional_slot_resolution --> n_closed_vocabulary
n_concern_folder_correspondence --> n_glob_resolvable_tree
n_glob_resolvable_tree --> n_concern_folder_correspondence
n_declared_jurisdiction --> n_bounded_nesting_depth
n_bounded_nesting_depth --> n_sideways_overflow
n_sideways_overflow --> n_bounded_nesting_depth
n_one_concern_per_file --> n_narrowest_concern
n_narrowest_concern --> n_layer_spine_precedence
n_layer_spine_precedence --> n_narrowest_concern
n_agnostic_first_vocabulary --> n_closed_vocabulary
n_guided_vocabulary_refusal --> n_closed_vocabulary
n_guided_vocabulary_refusal --> n_agnostic_first_vocabulary
n_derived_naming_registry --> n_declared_jurisdictionClosed Vocabulary
- Kind: principle
- Severity: mandatory
- Scope: repository, folder, filename
- Layer: Structural Core
Details
Before<container>/managers/foo.manager.ts -> neither "managers" nor "manager" is a declared word
After<container>/coordinators/foo.coordinator.ts -> the declared concern that already covers the role
Positional Slot Resolution
- Kind: mechanism
- Severity: mandatory
- Scope: filename
- Layer: Structural Core
Details
Beforefoo-registry.ts -> one fused word, so neither slot resolves
Afterfoo.registry.ts -> subject "foo", concern "registry"; position decides, so a concern word is legal in the subject slot too
Concern-Folder Correspondence
- Kind: constraint
- Severity: mandatory
- Scope: folder, filename
- Layer: Structural Core
Details
Before<container>/caches/foo.store.ts -> the folder says cache, the tag says store
After<container>/stores/foo.store.ts -> the tag terminates the name and names the parent folder
Glob-Resolvable Tree
- Kind: mechanism
- Severity: mandatory
- Scope: repository
- Layer: Structural Core
Details
Before<root>/*/validators/*.ts and <root>/*/*/validators/*.ts -> one pattern per depth, and a new grouping adds another
After**/*.validator.ts for the files, **/validators/ for the folders -> two unanchored patterns resolve the concern tree-wide
Declared Jurisdiction
- Kind: principle
- Severity: mandatory
- Scope: repository, root
- Layer: Structural Core
Details
Before"a folder holding no folders is a bucket" -> inferred, so a container that loses its last folder silently reclassifies and its next loose file passes
Aftercontainers{<root>: [...]} + specialContainers{<root>: [...]} -> both kinds declared; a folder in neither is flagged
Bounded Nesting Depth
- Kind: constraint
- Severity: mandatory
- Scope: folder, root
- Layer: Structural Core
Details
Before<container>/foo/pools/lru/bar.pool.ts -> one folder past the cap, and the extra level resolves to no role at all
After<container>/foo/pools/bar.lru.pool.ts -> container, subject, concern, in order and at the cap; the discriminator moved into the variant slot
Sideways Overflow
- Kind: pattern
- Severity: mandatory
- Scope: folder, filename
- Layer: Structural Core
Details
Before<container>/caches/lru/foo.cache.ts beside <container>/caches/fifo/foo.cache.ts -> the collision was relieved by a new level
After<container>/caches/foo.lru.cache.ts beside <container>/caches/foo.fifo.cache.ts -> relieved by the variant slot, at the same depth
One Concern Per File
- Kind: principle
- Severity: mandatory
- Scope: file
- Layer: Structural Core
Details
Beforefoo.store.ts -> holds the state AND validates every write, so its concern is two words
Afterfoo.store.ts + foo.validator.ts -> the ambiguity was the finding; the split is the fix
Narrowest Concern
- Kind: principle
- Severity: mandatory
- Scope: file
- Layer: Structural Core
Details
Beforefoo.manager.ts -> names a stature, so it fits lifecycle owners, caches, registries and coordinators alike
Afterfoo.coordinator.ts -> the narrowest declared role that is accurate; a file that cannot choose is doing both
Layer Spine Precedence
- Kind: mechanism
- Severity: contextual
- Scope: file
- Layer: Structural Core
Details
Beforea file that is irreducibly both is tagged by whichever word came to mind first
Aftermodel (domain) beats schema (infrastructure) -> domain-ward wins, and only as a tie-break after the split test fails
Agnostic-First Vocabulary
- Kind: principle
- Severity: mandatory
- Scope: repository, vocabulary
- Layer: Structural Core
Details
Before<container>/managers/ and <container>/helpers/ -> two catch-all words for roles the agnostic set already names
After<container>/coordinators/ and <container>/predicates/ -> a domain tag is admitted only where no agnostic concern covers the role
Guided Vocabulary Refusal
- Kind: mechanism
- Severity: mandatory
- Scope: repository, vocabulary, tooling
- Layer: Structural Core
Details
Before'foo.manager.ts' -> "'manager' is not a declared concern tag" -> the author guesses again, and the table that already answered this sits in prose no gate reads
Afterrefused word -> rejection-table index -> "'manager' is covered by 'coordinator'" -> foo.coordinator.ts; coverage is decided by the role a file plays, never by a general-language synonym set
Derived Naming Registry
- Kind: artifact
- Severity: mandatory
- Scope: repository, tooling
- Layer: Structural Core
Details
Beforethe vocabulary lives only in prose, so every gate re-reads it by hand and a rule written into the config is read by nobody
Afterdocument holds the reasoning -> registry holds the declarations -> one gate and one classifier read the registry; drift either way is a bug
Member Never Restates the Set
- Kind: constraint
- Severity: mandatory
- Scope: filename
- Layer: Structural Core
Details
Before<container>/foo/behaviors/foo-bar.behavior.ts -> restates what the folder already said
After<container>/foo/behaviors/bar.behavior.ts -> the folder names the set, the file names the member
Manual Identity Migration
- Kind: technique
- Severity: mandatory
- Scope: repository, refactor
- Layer: Structural Core
Details
Beforea rename tool rewrites every literal path; **/*.validator.ts now collects nothing and the gate stays green because nothing is left to check
Afterone container -> rename -> update every importer -> re-point every pattern -> compare collected counts against the previous run -> gate green before the next container
Transactions / State / Concurrency
Every principle in this category. Each record carries its kind, its severity, the scopes it applies at and the layer it lives in, then the edge relations that join it to other records, the records that point back at it, the contracts that answer to it and the tensions it takes part in. The descriptors say how it is violated, detected, measured, repaired and enforced. Where the record carries one, an exemplar shows the shape before and after the principle is applied.
Relations diagram
flowchart LR
n_idempotency["Idempotency"]
n_atomicity["Atomicity"]
n_acid["ACID"]
n_transaction_boundary["Transaction Boundary"]
n_unit_of_work_pattern["Unit of Work Pattern"]
n_consistency["Consistency"]
n_isolation["Isolation"]
n_concurrency_control["Concurrency Control"]
n_optimistic_locking["Optimistic Locking"]
n_pessimistic_locking["Pessimistic Locking"]
n_state_isolation["State Isolation"]
n_controlled_side_effects["Controlled Side Effects"]
n_petri_nets["Petri Nets"]
n_atomicity --> n_transaction_boundary
n_atomicity --> n_consistency
n_acid --> n_atomicity
n_acid --> n_consistency
n_acid --> n_isolation
n_transaction_boundary --> n_atomicity
n_transaction_boundary --> n_unit_of_work_pattern
n_unit_of_work_pattern --> n_transaction_boundary
n_unit_of_work_pattern --> n_atomicity
n_unit_of_work_pattern --> n_consistency
n_isolation --> n_concurrency_control
n_concurrency_control --> n_isolation
n_optimistic_locking --> n_concurrency_control
n_pessimistic_locking --> n_isolationIdempotency
- Kind: principle
- Severity: mandatory
- Scope: API, command, message handler
- Layer: Atomic Boundary
Details
Beforeapp.post("/foo", async request => fooStore.create(await request.json()));
Afterapp.post("/foo", async request => { const key = requireHeader(request, "Idempotency-Key"); const body = await request.json(); return idempotency.execute(key, () => fooStore.create(body)); });
Atomicity
- Kind: principle
- Severity: mandatory
- Scope: transaction, operation, workflow
- Layer: Atomic Boundary
Details
Beforeawait fooStore.remove(from, foo.id); await fooStore.add(to, foo.id);
Afterawait database.transaction(async tx => { await tx.foos.remove(from, foo.id); await tx.foos.add(to, foo.id); });
ACID
- Kind: model
- Severity: contextual
- Scope: database, transaction
- Layer: Atomic Boundary
Details
Beforeawait fooDb.write(foo); await barDb.write(bar);
Afterawait database.transaction({ isolation: "serializable" }, async tx => { await tx.foos.save(foo); await tx.bars.save(bar); assertInvariant(foo, bar); });
Transaction Boundary
- Kind: constraint
- Severity: mandatory
- Scope: unit of work, aggregate, service
- Layer: Atomic Boundary
Details
Beforeawait beginTransaction(); await controller.parse(request); await service.validate(foo); await repository.save(foo); await commitTransaction();
Afterasync function createFoo(input: CreateFoo) { const foo = validateFoo(input); return database.transaction(tx => new FooRepository(tx).save(foo)); }
Unit of Work Pattern
- Kind: pattern
- Severity: recommended
- Scope: application service, persistence
- Aliases: Unit of Work
- Layer: Atomic Boundary
Details
Beforeawait fooRepository.save(foo); await barRepository.save(bar); await eventRepository.save(event);
Afterconst uow = unitOfWork.begin(); uow.foos.save(foo); uow.bars.save(bar); uow.events.append(event); await uow.commit();
Consistency
- Kind: quality-attribute
- Severity: mandatory
- Scope: data, transaction, distributed system
- Layer: Atomic Boundary
Details
Beforefoo.total = foo.items.reduce((sum, item) => sum + item.value, 0); foo.itemCount = externalCount;
Afterfunction rebuildFoo(items: readonly FooItem[]): Foo { return { items, total: sum(items), itemCount: items.length }; } const foo = rebuildFoo(items);
Isolation
- Kind: constraint
- Severity: contextual
- Scope: database, transaction, concurrency
- Layer: Atomic Boundary
Details
Beforeconst foo = await fooStore.find(id); foo.count += 1; await fooStore.save(foo);
Afterawait database.transaction({ isolation: "serializable" }, async tx => { const foo = await tx.foos.lock(id); await tx.foos.save({ ...foo, count: foo.count + 1 }); });
Concurrency Control
- Kind: mechanism
- Severity: mandatory
- Scope: transaction, memory, distributed system
- Layer: Atomic Boundary
Details
Beforeconst foo = await fooStore.find(id); await fooStore.save({ ...foo, count: foo.count + 1 });
Afterawait fooStore.update(id, current => ({ ...current, count: current.count + 1, }), { expectedVersion: foo.version });
Optimistic Locking
- Kind: pattern
- Severity: contextual
- Scope: persistence, transaction
- Layer: Atomic Boundary
Details
Beforeawait fooTable.update({ id: foo.id, name: foo.name });
Afterconst updated = await fooTable.update({ id: foo.id, expectedVersion: foo.version, next: { ...foo, version: foo.version + 1 }, }); if (!updated) throw new ConflictError(foo.id);
Pessimistic Locking
- Kind: pattern
- Severity: contextual
- Scope: persistence, critical section
- Layer: Atomic Boundary
Details
Beforeconst foo = await fooTable.find(id); await fooTable.save(change(foo));
Afterawait database.transaction(async tx => { const foo = await tx.foos.findForUpdate(id); await tx.foos.save(change(foo)); });
State Isolation
- Kind: principle
- Severity: mandatory
- Scope: function, component, service
- Layer: Atomic Boundary
Details
Beforeconst globalFooState: Foo[] = []; function addFoo(foo: Foo) { globalFooState.push(foo); }
Afterclass FooSession { #state: Foo[] = []; add(foo: Foo) { this.#state = [...this.#state, foo]; } snapshot() { return [...this.#state]; } }
Controlled Side Effects
- Kind: principle
- Severity: recommended
- Scope: function, module, boundary
- Layer: Atomic Boundary
Details
Beforefunction calculateFoo(foo: Foo) { foo.count += 1; fooLog.record(foo); fooDb.save(foo); return foo.count; }
Afterfunction nextFoo(foo: Foo): Foo { return { ...foo, count: foo.count + 1 }; } async function applyFoo(foo: Foo, store: FooStore, log: Log) { const next = nextFoo(foo); log.write(next); await store.save(next); return next; }
Petri Nets
- Kind: model
- Severity: contextual
- Scope: concurrency, workflow, verification
- Layer: Atomic Boundary
Details
Beforeacquire(a); acquire(b); work(); release(b); release(a);
Afterconst net = petriNet({ places: { idle: 1, aHeld: 0, bHeld: 0 }, transitions: [ { name: "takeA", consume: { idle: 1 }, produce: { aHeld: 1 } }, { name: "takeB", consume: { aHeld: 1 }, produce: { bHeld: 1 } }, ], }); assertNoDeadlock(reachableMarkings(net));