Livingpattern
Aggregate — consistency boundary
atlas/aggregate-consistency-boundary
general answer 9 · here 8 · aligned
- Constraint
- Order and OrderLine updated in separate transactions caused inconsistency.
- Decision
- Order as aggregate root. Lines change only through the root.
- Outcome
- Large aggregates contend. Boundary design is paramount.
java · Living
class Order {
void addLine(Product p, int qty) { lines.add(new OrderLine(p, qty)); recalcTotal(); }
}Sources:DDD Evans
Livingpatternfintech
API Gateway / BFF — client-facing aggregation
atlas/api-gateway-bff
general answer 8 · here 9 · aligned
- Constraint
- Mobile clients hit five microservices directly, producing chatty APIs.
- Decision
- BFF aggregates responses. Auth and rate limiting at the gateway.
- Outcome
- BFF bloat risk. Document split criteria by team boundary and change frequency.
typescript · BFF
app.get('/mobile/home', async (req) => ({ user: await userSvc.me(), orders: await orderSvc.recent() }));Sources:Building Microservices
Livingpattern⚡ C-4 · Consistency vs local optimumweb-framework
Boundary validation — fix the shape before the handler
atlas/boundary-validation
general answer 8 · here 7 · aligned
- Constraint
- Request JSON, query, and headers are untrusted. Checking inside each handler leads to gaps and inconsistent 400 responses.
- Decision
- Declare validation in struct tags or schemas and reject at bind time or in middleware. Handlers receive only validated values.
- Outcome
- Error responses share one shape, and handlers stay on business logic. In exchange, rules spread across tags and schemas, and pushing business invariants such as stock or cut-off dates into them bloats the boundary.
go · Living
type Login struct {
User string `json:"user" binding:"required"`
Password string `json:"password" binding:"required"`
}
var req Login
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}typescript · Living
app.post('/posts', zValidator('json', z.object({ title: z.string() })), (c) => {
const { title } = c.req.valid('json')
return c.json({ title }, 201)
})Livingpatternfintech
Circuit Breaker — isolating cascading failures
atlas/circuit-breaker-resilience
general answer 9 · here 9 · aligned
- Constraint
- Downstream API failures exhausted the thread pool and stopped the whole system.
- Decision
- Resilience4j / custom CB fast-fails after threshold breach; half-open state for retry.
- Outcome
- Availability improved. Poor fallback design leads to silent degradation.
java · Living
@CircuitBreaker(name = "payments", fallbackMethod = "payFallback")
public PaymentResult charge(Order o) { /* ... */ }go · Living
cb := gobreaker.NewCircuitBreaker(gobreaker.Settings{Name: "payments"})
_, err := cb.Execute(func() (interface{}, error) { return client.Charge(ctx, o) })Sources:Release It! 2nd Ed.
Livingprinciple⚡ C-1 · DRY vs coupling⚡ C-4 · Consistency vs local optimumcobolclone-clusterlegacy-modernization
Name-only cloned COBOL programs and duplicate COPYbooks — safe staged consolidation
atlas/cobol-clone-program-name-only
general answer 2 · here 5
- Constraint
- Maintaining dozens of nearly identical COBOL programs or duplicate COPYbooks that differ only in program identifiers or minor constants multiplies regulatory-change effort and invites missed fixes.
- Decision
- Distinguish harmless display-name differences from business-constant differences, start with thin legacy-name entry wrappers delegating to one shared implementation (zero JCL edits), verify byte-identical outputs, and move to full consolidation only after external job references are confirmed.
- Outcome
- Cuts maintained business logic sharply with per-program rollback safety, while requiring build/link/deployment verification for the wrapper-plus-shared layout.
cobol · Living
* 旧名プログラムを薄い入口として残し、ロジック本体を共通プログラムへ委譲する
PROCEDURE DIVISION.
MOVE "PGM-OLD-A" TO WS-CALLER-NAME.
CALL "PGM-COMMON" USING WS-CALLER-NAME.
STOP RUN.Sources:Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Duplicated Code·Working Effectively with Legacy Code (Michael Feathers) — Safe Incremental Consolidation
Livingprinciple⚡ C-3 · Performance vs readability⚡ C-4 · Consistency vs local optimumcobolnumeric-precisiongolden-master
Fixed-width COBOL layouts (`COMP-3` / `OCCURS`) and implicit row-count or key-order guards
atlas/cobol-fixed-layout-and-threshold-rules
general answer 4 · here 8
- Constraint
- Legacy COBOL codebases frequently embed undocumented fixed-width layouts, packed-decimal (`COMP-3`) rounding, `REDEFINES`/`OCCURS` limits, row-count warning thresholds, and key-order aborts whose silent breakage causes financial or operational incidents during modernization.
- Decision
- Synthesize schema-conformant boundary data from COPYbooks (empty, single-row, threshold+1, negative, out-of-order keys, blank numerics) to lock baseline behavior against the original program, and record human agreement on which constraints are active business/safety rules vs. obsolete limits.
- Outcome
- Requires upfront synthetic baseline data while preventing subtle 1-byte or rounding regressions and clarifying what must be preserved during migration.
cobol · Living
* 固定桁・パック10進・件数上限は「しきい値+1件」「キー逆順」「負数」等の
* 境界合成データで旧プログラムの終了コード・出力を基準値として固定する
01 WS-AMOUNT PIC S9(9)V99 COMP-3.
01 WS-WARN-LIMIT PIC 9(7) VALUE 50000.
Sources:COBOL Fixed-Length Record & Packed Decimal (COMP-3) Migration Best Practices·Working Effectively with Legacy Code (Michael Feathers) — Characterization Tests & Boundary Verification
Livingprinciple⚡ C-1 · DRY vs coupling⚡ C-3 · Performance vs readabilitycobolrefactoringmodularization
`GO TO`, cross-paragraph calls, and mixed file I/O blocking COBOL common-component extraction
atlas/cobol-goto-and-io-blocking-extraction
general answer 3 · here 5
- Constraint
- Even when identical business decisions repeat across dozens of COBOL programs, mixing `READ`/`WRITE` file I/O, `GO TO` jumps, cross-paragraph `PERFORM`s, and shared `WORKING-STORAGE` mutations inside the same paragraph prevents safe extraction into reusable `CALL` components.
- Decision
- Extract only self-contained decision or field-editing blocks with clean `LINKAGE SECTION` inputs/outputs (no file I/O, no `GO TO`), guarding period/scope termination carefully and verifying every branch against the original program.
- Outcome
- Avoids risky rewrites of I/O skeletons while consolidating high-leverage repeated business rules into a single maintained component.
cobol · Living
* ファイル I/O や GO TO を含まない純粋な判定だけを LINKAGE 引数で部品化する
LINKAGE SECTION.
01 LK-IN-CODE PIC X(4).
01 LK-OUT-BRANCH PIC X(3).
PROCEDURE DIVISION USING LK-IN-CODE LK-OUT-BRANCH.
EVALUATE LK-IN-CODE
WHEN "0100" MOVE "BR1" TO LK-OUT-BRANCH
WHEN OTHER MOVE "BR0" TO LK-OUT-BRANCH
END-EVALUATE.
EXIT PROGRAM.Sources:Structured COBOL Programming & Modular Extraction — Control Flow, Side Effects, and LINKAGE Boundaries·Working Effectively with Legacy Code (Michael Feathers) — Sprout/Extract Pure Logic from Side Effects
Livingprinciple⚡ C-3 · Performance vs readability⚡ C-4 · Consistency vs local optimumcobolbatch-iolegacy-modernization
Write-then-read intermediate handoff files in batch chains — I/O overhead vs. restart boundaries
atlas/cobol-intermediate-handoff-file
general answer 4 · here 6
- Constraint
- Chaining batch steps where one program writes a sequential handoff file solely for the next step to read wastes disk I/O and job-step overhead, lengthening overnight batch windows.
- Decision
- Verify that no external job or restart procedure depends on the handoff file, then merge writer and reader into one step validated via byte-level output, return-code, and log comparison against the original chain.
- Outcome
- Eliminating intermediate disk I/O speeds up batch runtime significantly, while operators must confirm partial-output behavior and rerun steps on failure.
cobol · Anti-pattern
* STEP1 が WORK-FILE へ全件出力し、STEP2 がすぐ全件読み込み直す
* 他ジョブ参照もリラン起点も無い場合は不要なディスク I/O になる
WRITE WORK-REC FROM IN-REC.
Sources:Mainframe Batch Design Patterns — Job Step Consolidation & Checkpoint/Restart Boundaries·Working Effectively with Legacy Code (Michael Feathers) — Characterization Testing & Golden Master Comparison
Livingprinciple⚡ C-4 · Consistency vs local optimumcoboldead-codelegacy-modernization
Unused COPYbooks, commented-out code, and unreachable COBOL paths — quarantine before deleting
atlas/cobol-unused-copy-and-dead-code
general answer 3 · here 6
- Constraint
- Commented-out legacy blocks, unreferenced COPYbooks, and apparently unreachable paragraphs clutter impact analysis, yet deleting them solely on partial static scans risks breaking unprovided JCLs, jobnets, or annual manual batches.
- Decision
- Strip only commented-out code while preserving explanatory comments, quarantine unreferenced COPYbooks and uncalled programs (e.g., `_UNUSED`) rather than hard-deleting them, and finalize retirement only after checking external schedulers and sibling systems.
- Outcome
- Reduces daily maintenance noise with instant rollback safety, while requiring operational confirmation before permanent removal.
cobol · Anti-pattern
* 2012-04 OLD-LOGIC (履歴管理があるのに数百行の旧コードがコメントのまま残存)
* IF WS-OLD-FLAG = "1"
* PERFORM OLD-CALC-PARA
* END-IF.
Sources:Working Effectively with Legacy Code (Michael Feathers) — Safe Deletion & Unknown Callers·The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Version Control over Commented-Out Code
Livingprinciple⚡ C-1 · DRY vs coupling
C-1: DRY vs coupling
atlas/conflict-dry-vs-coupling
general answer 7 · here 8 · aligned
- Constraint
- Business rules piled into a shared util; one change rippled across all services.
- Decision
- Share only pure functions. Allow domain rule duplication per bounded context.
- Outcome
- Line count grew, but blast radius shrank.
typescript · Example
// shared: date utils only
// domain: invoice rules stay in billing module
Sources:Pragmatic Programmer
Livingprinciple⚡ C-2 · YAGNI vs extensibility
C-2: YAGNI vs extensibility
atlas/conflict-yagni-vs-extensibility
general answer 5 · here 8
- Constraint
- Abstraction for "10 future payment types" pressured the deadline for the current two.
- Decision
- Deferred Strategy until a second payment method was confirmed. Used if/else + tests meanwhile.
- Outcome
- Refactor cost hit at the third payment method. First release shipped two weeks earlier.
go · YAGNI
func pay(method string, amt int64) error {
switch method { case "card": return payCard(amt); default: return errUnsupported }
}Sources:Extreme Programming
Livingprinciple⚡ C-2 · YAGNI vs extensibility⚡ C-5 · Encapsulation vs testabilityprinciplemodularity
Deep modules — avoid shallow pass-through wrappers
atlas/deep-module-avoid-shallow-wrappers
general answer 8 · here 8 · aligned
- Constraint
- Stacking thin pass-through classes and single-caller wrapper functions across many files hides real behavior behind indirection hops and inflates cognitive load without absorbing real complexity.
- Decision
- Favor deep modules whose simple interface hides substantial implementation complexity (validation, retries, resource cleanup), and delete shallow wrappers that merely forward arguments.
- Outcome
- Call chains become immediately traceable upon opening a file, provided each deep module keeps its public contract focused and explicit.
go · Living
// 呼び出しごとに引数変換・リトライ・タイムアウト・エラー分類を 1 つの単純な境界へ吸収する
func FetchExchangeRate(ctx context.Context, pair CurrencyPair) (Rate, error) {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
return fetchWithBackoffAndValidate(ctx, pair)
}Sources:A Philosophy of Software Design, 2nd Ed. (John Ousterhout) — Ch.4 Modules Should Be Deep / Ch.7 Different Layer, Different Abstraction·Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Middle Man
Livingpattern⚡ C-5 · Encapsulation vs testability
DI — constructor injection
atlas/dependency-injection
general answer 9 · here 8 · aligned
- Constraint
- ServiceLocator polluted global state during tests.
- Decision
- Constructor injection + interfaces. Framework DI only at composition root.
- Outcome
- More boilerplate. Test doubles swap trivially.
java · Living
class OrderService {
private final OrderRepository repo;
OrderService(OrderRepository repo) { this.repo = repo; }
}Sources:Clean Architecture
Deprecatedprinciple
Singleton DB — untestable hotspot
atlas/deprecated-singleton-db
general answer 2 · here 4
- Constraint
- Database.getInstance() called from every layer; only integration tests possible.
- Decision
- DI + testcontainers. Singleton on deletion roadmap.
- Outcome
- Large refactor. Parallel tests become possible.
java · Deprecated
Database.getInstance().query("...");Sources:Legacy code patterns
Livingprinciple⚡ C-1 · DRY vs couplingprinciplebusiness-logic
True DRY — eliminate knowledge duplication, not coincidental syntax
atlas/dry-knowledge-not-syntax
general answer 8 · here 9 · aligned
- Constraint
- Merging two business rules that merely look structurally similar (such as invoice tax rounding vs. payroll rounding) creates tight coupling where changing one regulation breaks the other.
- Decision
- Deduplicate only pieces that share a single authoritative reason to change; keep code with separate business lifecycles independent until real shared knowledge is proven.
- Outcome
- Superficial code-clone detectors may flag similar blocks, but regulatory or product changes stay safely isolated within their own boundary.
typescript · Living
// 変更理由が異なる 2 つの端数規則は、式が似ていても安易に 1 関数へ結合しない
export function roundInvoiceTaxYen(amount: number): number {
return Math.floor(amount); // 適格請求書の端数規約(請求領域の知識)
}
export function roundOvertimePayYen(amount: number): number {
return Math.round(amount); // 労働基準法の端数規約(給与領域の知識)
}Sources:The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Topic 9: DRY - The Evils of Duplication·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第11章・第13章 重複と責務の分離
Evolvedpattern
Result type — curbing exception abuse
atlas/error-handling-result-type
general answer 7 · here 6
- Constraint
- Checked exceptions propagated through layers into try/catch hell.
- Decision
- Result/Either at domain boundaries. Exceptions only in infra.
- Outcome
- Learning curve. Error paths explicit in types.
typescript · Evolved
type Result<T,E> = { ok: true; value: T } | { ok: false; error: E };go · Living
func ParseOrder(raw []byte) (Order, error) { /* ... */ }Sources:Railway oriented programming
Evolvedreading⚡ C-1 · DRY vs couplingfrontend
React — gradual migration from class to Hooks
atlas/facebook-react-hooks-adoption
general answer 8 · here 8 · aligned
- Constraint
- Class components scattered lifecycle; logic reuse via HOC/render props deepened nesting.
- Decision
- Hooks in React 16.8. New code: function components + hooks. Leave existing classes untouched.
- Outcome
- useEffect dependency bugs are a new risk. eslint-plugin-react-hooks enforces rules. Concurrent Features assume hooks.
typescript · Fossilized
class OrderList extends React.Component {
componentDidMount() { fetchOrders().then(...) }
}typescript · Evolved
function OrderList() {
const [orders, setOrders] = useState<Order[]>([]);
useEffect(() => { fetchOrders().then(setOrders); }, []);
}Livingpattern⚡ C-2 · YAGNI vs extensibility
Factory Method — localizing creation logic
atlas/factory-method-creation
general answer 7 · here 7 · aligned
- Constraint
- Scattered new calls meant 50-file edits when creation rules changed.
- Decision
- Centralize creation in Factory / static factory methods.
- Outcome
- Creation paths are traceable. Excessive factories can violate YAGNI.
typescript · Living
export function createNotifier(channel: Channel): Notifier {
switch (channel) { case 'email': return new EmailNotifier(); /* ... */ }
}Sources:GoF Factory Method
Livingpattern
Feature Toggle — separating release from deploy
atlas/feature-toggle
general answer 8 · here 8 · aligned
- Constraint
- Long-lived branches caused merge hell.
- Decision
- Trunk-based + feature flags. Incomplete work defaults off.
- Outcome
- Forgotten flags become tech debt. Operate flag registry with expiry.
typescript · Living
if (flags.isEnabled('new-checkout')) return newCheckout(cart);
return legacyCheckout(cart);Sources:Continuous Delivery
Livingpattern⚡ C-2 · YAGNI vs extensibilityapi-design
Functional options — configuration passed as functions
atlas/functional-options
general answer 8 · here 7 · aligned
- Constraint
- Constructor settings keep growing. New parameters break existing callers, and a config struct cannot tell zero values from unset.
- Decision
- Accept variadic Option values of type func(*T) and apply them in order over the defaults.
- Outcome
- Settings can be added without breaking callers. In exchange, the full list is hard to read from the types, and conflicting options resolve by order, visible only at run time.
go · Living
type OptionFunc func(*Engine)
func New(opts ...OptionFunc) *Engine {
engine := &Engine{ /* defaults */ }
return engine.With(opts...)
}Evolvedreading⚡ C-1 · DRY vs couplinglanguage-design
Go — fourteen years deferring generics
atlas/go-generics-delayed-adoption
general answer 5 · here 8
- Constraint
- At Go 1.0, generics API was unsettled. Language simplicity and consistent style came first.
- Decision
- Used interfaces + code generation (go generate) until Go 1.18 added type parameters.
- Outcome
- 2010s saw more interface{} and reflect, but learning cost stayed low. Post-1.18 enables type-safe map/filter; long coexistence with legacy code.
go · Fossilized
// Pre-1.18: interface{} + type assertion
func MapSlice(in []interface{}, fn func(interface{}) interface{}) []interface{} { ... }go · Evolved
// Go 1.18+: type parameters
func MapSlice[T, U any](in []T, fn func(T) U) []U { ... }Deprecatedprinciple⚡ C-1 · DRY vs coupling⚡ C-2 · YAGNI vs extensibilitylegacy-modernizationoop-antipattern
God Object — dismantling the omnibus Service
atlas/god-object-service
general answer 2 · here 3 · short on both
- Constraint
- When an `OrderFacade` or `CommonManager` grows to thousands of lines spanning auth, inventory, billing, and notifications, no engineer can predict blast radius and single-line edits break unrelated workflows.
- Decision
- Freeze new feature additions to the monolith class and extract cohesive use-case modules incrementally behind characterization tests.
- Outcome
- Safe extraction takes months via incremental strangler steps rather than a risky big-bang rewrite.
java · Anti-pattern
class OrderFacade { /* 8000 lines: auth, inventory, billing, tax, mail... */ }Sources:Working Effectively with Legacy Code (Michael Feathers) — Ch.20 This Class Is Too Big and I Don't Want It to Get Any Bigger·Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Large Class·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第13章 巨大クラス・低凝集の解体
Livingpattern
Hexagonal — Ports & Adapters
atlas/hexagonal-ports-adapters
general answer 8 · here 7 · aligned
- Constraint
- HTTP handlers wrote SQL directly; framework lock-in.
- Decision
- Ports (interfaces) in domain; adapters in infra.
- Outcome
- More files. Framework can be swapped.
go · Living
type OrderPort interface { Place(ctx context.Context, cmd PlaceOrder) error }
type HTTPAdapter struct { svc OrderPort }Sources:Clean Architecture·Ports and Adapters
Livingprinciple⚡ C-1 · DRY vs coupling⚡ C-5 · Encapsulation vs testabilityprinciplemodularity
High cohesion, low coupling — keep co-changing data and behavior together
atlas/high-cohesion-low-coupling
general answer 9 · here 8 · aligned
- Constraint
- When state and the rules governing it are scattered across utility modules and unrelated services, a single business rule tweak triggers cascading breakages and costly impact analysis.
- Decision
- Group data together with its invariants and operations inside one cohesive module or type, exposing only a minimal boundary to callers.
- Outcome
- Changes stay localized and easier to test, though teams must still guard against letting a cohesive module grow into an unbounded god module.
typescript · Living
// 請求金額と割引不変条件を 1 モジュールに凝集させ、外部からは検証済み操作のみ公開する
export type MoneyYen = { readonly amount: number };
export function applyDiscount(price: MoneyYen, ratePercent: number): MoneyYen {
if (ratePercent < 0 || ratePercent > 100) throw new RangeError("invalid discount rate");
return { amount: Math.floor((price.amount * (100 - ratePercent)) / 100) };
}Sources:良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第4章・第5章 低凝集の解消·The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Topic 10: Orthogonality
Livingrulefintech
Idempotency Key — preventing double charges
atlas/idempotency-key
general answer 9 · here 10 · aligned
- Constraint
- Client retries caused double-billing incidents.
- Decision
- Idempotency-Key header + 24h result cache.
- Outcome
- Storage cost. Mandatory precedent for financial systems.
go · Living
func (h *Handler) Charge(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if cached, ok := h.store.Get(key); ok { writeJSON(w, cached); return }
}Sources:Stripe API docs pattern
Livingprinciple⚡ C-4 · Consistency vs local optimumprincipleinvariants
Enforce invariants at construction — forbid half-baked objects
atlas/invariants-no-half-baked-objects
general answer 9 · here 8 · aligned
- Constraint
- Constructing empty objects and mutating them via setter chains allows partially initialized or invalid instances to leak downstream, causing null failures or wrong calculations far from the bug's origin.
- Decision
- Validate required fields and domain invariants (e.g., non-negative money, start <= end) inside constructors or factory functions and prefer immutable values so invalid states cannot be represented.
- Outcome
- Defensive null checks disappear across callers, while multi-step forms or reflection-based ORMs require dedicated input DTOs or persistence mappers.
java · Living
public record DateRange(LocalDate start, LocalDate end) {
public DateRange {
Objects.requireNonNull(start, "start");
Objects.requireNonNull(end, "end");
if (end.isBefore(start)) {
throw new IllegalArgumentException("end must be >= start");
}
}
}Sources:良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第3章 クラス設計(生焼けオブジェクトと不正状態の排除)·Effective Java, 3rd Ed. (Joshua Bloch) — Item 17: Minimize mutability / Item 49: Check parameters for validity
Livingprinciple⚡ C-3 · Performance vs readabilityprinciplereadability
KISS — prefer obvious structure over clever code
atlas/kiss-simple-before-clever
general answer 8 · here 9 · aligned
- Constraint
- Heavy metaprogramming, nested ternaries, and clever one-liners make runtime behavior opaque to teammates and AI agents, raising outage recovery time and regression risk.
- Decision
- Prefer straightforward top-to-bottom control flow and explanatory variables over clever tricks, reserving complex optimizations strictly for measured bottlenecks.
- Outcome
- Code may take a few extra lines, while review accuracy, onboarding speed, and incident diagnosis improve significantly.
typescript · Living
// 複雑な条件式を説明変数へ分解し、意図を上から順に追えるようにする
const isActiveMember = user.status === "active" && !user.suspendedAt;
const meetsMinimumAmount = order.totalYen >= 5000;
const eligibleForFreeShipping = isActiveMember && meetsMinimumAmount;
Sources:The Art of Readable Code (Dustin Boswell, Trevor Foucher) — Ch.7 Making Control Flow Easy to Read / Ch.8 Breaking Down Giant Expressions·The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Simplicity and Clarity
Livingreading⚡ C-2 · YAGNI vs extensibilityinfrastructureoss-governance
Kubernetes — API versioning and staged deprecation
atlas/kubernetes-api-deprecation-policy
general answer 7 · here 9 · aligned
- Constraint
- Breaking API changes on large clusters affect all users immediately. Need both compatibility and evolution speed.
- Decision
- Stages: alpha → beta → GA. Deprecation keeps Deprecated warning period; minimum three releases (~9 months) before removal. Storage version migration for gradual transition.
- Outcome
- Old manifests rarely break overnight. Ops must monitor deprecation warnings. API surface tends to grow.
yaml · Living
apiVersion: apps/v1 # extensions/v1beta1 was deprecated then removed
kind: Deployment
Livingreading⚡ C-4 · Consistency vs local optimumsystemsoss-governance
Linux — no stabilization of internal kernel APIs
atlas/linux-unstable-kernel-api
general answer 6 · here 9
- Constraint
- The kernel evolves fast. Fixing all internal symbols would explode refactor cost.
- Decision
- No stability guarantee for internal APIs (non-export symbols). Only userspace ABI (syscall, /proc, uapi headers) is stable. Drivers must track upstream.
- Outcome
- Third-party kernel modules rebuild per kernel version. Chose development speed over compatibility.
c · Living
// Out-of-tree modules must match exact kernel version
// No stable kABI for arbitrary kernel internals
Evolvedreading
React Hooks — evolution from class components
atlas/living-react-hooks-vs-class
general answer 8 · here 8 · aligned
- Constraint
- Lifecycle scattered caused bugs. HOC nesting hell.
- Decision
- New code uses function components + hooks only. Leave classes untouched.
- Outcome
- useEffect dependency bugs are a new risk. Enforce rules via eslint.
typescript · Evolved
function OrderList() {
const [orders, setOrders] = useState<Order[]>([]);
useEffect(() => { fetchOrders().then(setOrders); }, []);
}Sources:React docs
Livingpattern⚡ C-1 · DRY vs couplingweb-framework
Middleware chain — cross-cutting steps in series via next()
atlas/middleware-chain
general answer 8 · here 7 · aligned
- Constraint
- Auth, logging, and panic recovery apply to every request. Writing them in each handler leads to omissions and duplication.
- Decision
- Give every step the same function type, stack them in order, and hand off with next() (Chain of Responsibility). Pre- and post-processing live in one function.
- Outcome
- Adding or reordering is registration only. In exchange, registration order becomes an implicit spec, and a missing or doubled next() stalls the flow.
go · Living
func Timing() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
log.Printf("%s %v", c.FullPath(), time.Since(start))
}
}typescript · Living
app.use(async (c, next) => {
const start = Date.now()
await next()
c.header('X-Response-Time', `${Date.now() - start}ms`)
})Livingpattern⚡ C-3 · Performance vs readabilitysql-performanceorm
N+1 — classic performance debt (per-row queries inside loops)
atlas/n-plus-one-query
general answer 6 · here 7
- Constraint
- Lazy-loading or querying child rows one-by-one inside a loop turns a single list request or batch into hundreds or thousands of DB round-trips, spiking p99 latency and exhausting connection pools.
- Decision
- Consolidate into constant round-trips via `JOIN FETCH`, `IN (...)` batch loading, `@BatchSize`, DTO projections, or DataLoader.
- Outcome
- Queries and deduplication become slightly more involved, so ORM fetching defaults and result caps must be documented.
java · Fix
@Query("SELECT o FROM Order o JOIN FETCH o.lines WHERE o.id IN :ids")sql · Fix
SELECT o.id, o.customer_id, l.sku, l.qty
FROM orders o
JOIN order_lines l ON l.order_id = o.id
WHERE o.id = ANY($1::bigint[]);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — N+1 Queries & Query Efficiency·SQL パフォーマンス詳解(Markus Winand)— 往復回数(Round-trip)の削減
Livingpattern⚡ C-3 · Performance vs readabilityperformance
Object pool — reuse allocations
atlas/object-pool-reuse
general answer 7 · here 6
- Constraint
- Each request allocates a sizeable struct. Under load, GC pauses and allocation cost drive latency.
- Decision
- Take from sync.Pool, reset, and put back when done. Only for values whose lifetime ends within the request.
- Outcome
- Allocation and GC load drop. In exchange, a reference kept after Put (e.g. passed to a goroutine) reads another request's data. Gin added c.Copy() for that case.
go · Living
c := engine.pool.Get().(*Context)
c.writermem.reset(w)
c.Request = req
c.reset()
engine.handleHTTPRequest(c)
engine.pool.Put(c)
Evolvedpattern⚡ C-1 · DRY vs coupling
Observer — loosely coupled event notification
atlas/observer-event-dispatch
general answer 7 · here 8 · aligned
- Constraint
- Order state changes had to notify email, inventory, and analytics.
- Decision
- Domain Event + subscriber registration (Observer-style). Direct calls forbidden.
- Outcome
- New notifications need only a subscriber. Debug paths multiply; ordering needs separate design.
java · Living
orderEvents.subscribe(new SendEmailOnPlaced());
orderEvents.publish(new OrderPlaced(orderId));
typescript · Evolved
eventBus.on('order.placed', sendEmail);
eventBus.emit('order.placed', { orderId });Livingprinciple⚡ C-2 · YAGNI vs extensibility
OCP — open for extension, closed for modification
atlas/ocp-open-closed
general answer 8 · here 7 · aligned
- Constraint
- Discount rules grew per campaign; calculateTotal's switch bloated.
- Decision
- DiscountRule interface + rule chain. New rules are class additions only.
- Outcome
- Rule lookup cost rises, but change risk to existing rules drops.
typescript · Living
interface DiscountRule { applies(cart: Cart): boolean; apply(cart: Cart): Cart; }Sources:GoF + SOLID
Livingprinciple⚡ C-2 · YAGNI vs extensibility⚡ C-4 · Consistency vs local optimumoop-antipatterndomain-modeling
Anemic domain & fat service — empty data bags paired with giant procedural services
atlas/oop-anemic-domain-fat-service
general answer 4 · here 5
- Constraint
- When entities degrade into getter/setter bags while all state transitions and business rules pile into giant services, invariant checks duplicate across endpoints and state corruption sneaks in via alternative write paths.
- Decision
- Co-locate state-transition rules and invariants with their domain data (via methods or pure domain functions in the same module), keeping services focused on transaction orchestration and external I/O.
- Outcome
- Core business rules become fast to unit-test without databases, while simple CRUD workflows should avoid unnecessary ceremony.
typescript · Living
// 継承や重いクラスではなく、純粋なデータ型と状態遷移関数を同一ドメインモジュールに凝集させる
export function approveOrder(order: Order, approverId: string): Order {
if (order.status !== "submitted") throw new Error("only submitted orders can be approved");
return { ...order, status: "approved", approverId };
}Sources:良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第5章・第13章 データクラスと低凝集サービス·Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Data Class / Long Function·Domain-Driven Design / Patterns of Enterprise Application Architecture (Martin Fowler) — Transaction Script vs Domain Model
Livingpattern⚡ C-1 · DRY vs couplingreadabilityoop-antipattern
Boolean flag arguments — splitting responsibilities and obscuring call sites
atlas/oop-boolean-flag-argument
general answer 3 · here 4
- Constraint
- Controlling function behavior with multiple positional `boolean` flags (`process(order, true, false)`) hides intent at every call site and multiplies execution paths combinatorially.
- Decision
- Split distinct behaviors into explicitly named functions, or pass a named options object / union mode type so intent is unmistakable at call sites.
- Outcome
- Slightly increases function or option-type surface while drastically improving call-site clarity and test coverage.
typescript · Anti-pattern
// 呼び出し側で true, false の意味が全く分からない
export function syncInvoices(orgId: string, isDryRun: boolean, includeArchived: boolean) { /* ... */ }typescript · Fix
export type SyncMode = "dry-run" | "commit";
export function syncInvoices(orgId: string, opts: { mode: SyncMode; includeArchived: boolean }) { /* ... */ }Sources:Refactoring, 2nd Ed. (Martin Fowler) — Ch.11 Remove Flag Argument·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第6章 条件分岐(フラグ引数の弊害)·The Art of Readable Code (Dustin Boswell, Trevor Foucher) — Ch.3 Explaining Meaning with Names & Options
Livingprinciple⚡ C-1 · DRY vs couplinglegacy-modernizationclone-cluster
Copy-paste divergence & shotgun surgery — 95%-identical clones hiding 5% diffs
atlas/oop-copy-paste-divergence
general answer 2 · here 4
- Constraint
- Cloning whole modules or batch jobs and tweaking 5% (`CalcV2`, `RegionB_Billing`) forces shotgun surgery on every bug fix or tax update, where missing one clone causes production regressions.
- Decision
- Separate the shared 95% skeleton from the 5% business variation, unifying true shared rules while isolating legitimate per-contract or per-regulation variations explicitly.
- Outcome
- Requires golden-master verification before consolidation, while slashing ongoing maintenance and regulatory update risk.
go · Living
// 95% の共通骨格は 1 関数にまとめ、異なる 5%(端数・特約ルール)だけを明示パラメータとして渡す
func ComputeSettlement(items []LineItem, policy RoundingPolicy) (int64, error) {
subtotal := sumItems(items)
return policy.Apply(subtotal)
}Sources:Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Duplicated Code / Shotgun Surgery·Working Effectively with Legacy Code (Michael Feathers) — Ch.19–20 Characterization Tests & Separating Responsibilities
Livingprinciple⚡ C-3 · Performance vs readabilityreadabilitycontrol-flow
Deep nesting (arrow anti-pattern) — flatten control flow with guard clauses
atlas/oop-deep-nesting-arrow-code
general answer 3 · here 4
- Constraint
- Nesting `if`/`else` and loops four or more levels deep forces readers to hold a stack of preconditions in working memory, causing missed edge cases and inverted-condition bugs during maintenance.
- Decision
- Reject invalid or edge cases up front via early-return guard clauses so the happy path stays flat at the top indent level, pairing early returns with `defer`/`try-finally` for resource cleanup.
- Outcome
- Happy-path behavior becomes immediately scannable while reducing cognitive load in reviews and incident debugging.
typescript · Anti-pattern
function approve(order: Order, user: User): Result {
if (order) {
if (order.status === "pending") {
if (user.canApprove) {
if (order.totalYen > 0) {
return doApprove(order, user);
}
}
}
}
return { ok: false };
}typescript · Fix
function approve(order: Order | null, user: User): Result {
if (!order || order.status !== "pending") return { ok: false, reason: "invalid_status" };
if (!user.canApprove) return { ok: false, reason: "forbidden" };
if (order.totalYen <= 0) return { ok: false, reason: "invalid_amount" };
return doApprove(order, user);
}Sources:The Art of Readable Code (Dustin Boswell, Trevor Foucher) — Ch.7 Making Control Flow Easy to Read (Guard Clauses & Reducing Nesting)·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第6章 条件分岐(早期リターンによるネスト解消)·Refactoring, 2nd Ed. (Martin Fowler) — Ch.10 Replace Nested Conditional with Guard Clauses
Livingpattern⚡ C-5 · Encapsulation vs testabilityconcurrencytenant-isolation
Implicit global mutable state — cross-request leakage and flaky temporal coupling
atlas/oop-global-mutable-state
general answer 2 · here 2 · short on both
- Constraint
- Mutating module-level or `public static` state during requests risks cross-tenant data leakage under concurrency and creates hidden call-order dependencies that break parallel tests.
- Decision
- Pass request, tenant, and transaction state explicitly via parameters or context objects; restrict module globals strictly to immutable constants or properly synchronized process-wide infrastructure pools.
- Outcome
- Requires explicit parameter plumbing while guaranteeing tenant isolation, thread safety, and deterministic tests.
typescript · Anti-pattern
// 並列リクエストで別テナントの ID に上書きされ、深刻な情報漏洩を起こす
export let activeTenantId = "";
typescript · Fix
// テナント文脈はリクエスト引数として明示的に受け渡す
export async function listInvoices(ctx: { readonly tenantId: string }) { /* ... */ }Sources:良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第4章 不変の活用(可変グローバル状態の危険性)·The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Topic 32: Concurrency & Shared State·Working Effectively with Legacy Code (Michael Feathers) — Ch.9 Static Cling & Global Dependencies
Livingpattern⚡ C-2 · YAGNI vs extensibility⚡ C-5 · Encapsulation vs testabilityoop-antipatternapi-boundarysecurity
Leaky ORM entities at API boundaries — mass assignment and schema coupling
atlas/oop-leaky-orm-entity
general answer 3 · here 4
- Constraint
- Binding persistence `@Entity` models directly to HTTP request bodies or JSON responses risks mass-assignment privilege escalation (`role`, `isAdmin`), unexpected lazy-load N+1 or serialization cycles, and breaking external APIs on every table rename.
- Decision
- Define explicit schema-validated request and response DTOs at external boundaries, keeping persistence models decoupled from wire formats.
- Outcome
- Introduces light boundary mapping while preserving API contract stability and strict property-level security.
java · Anti-pattern
@PostMapping("/users")
public UserEntity create(@RequestBody UserEntity body) { // role や internalFlags が外部上書きされうる
return repo.save(body);
}java · Fix
public record CreateUserRequest(@NotBlank String email, @NotBlank String displayName) {}
public record UserResponse(Long id, String email, String displayName) {}Sources:OWASP API Security Top 10 — API3:2023 Broken Object Property Level Authorization (Mass Assignment)·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第13章 モデルの境界と責務分離·Effective Java, 3rd Ed. (Joshua Bloch) — Item 15: Minimize the accessibility of classes and members
Livingprinciple⚡ C-2 · YAGNI vs extensibilityoop-antipatterntype-safety
Primitive obsession — passing money, IDs, dates, and codes as raw primitives
atlas/oop-primitive-obsession
general answer 3 · here 4
- Constraint
- Passing customer IDs, order IDs, money, tax rates, and postal codes as raw `string` or `number` prevents the compiler from catching swapped arguments or mixed units, scattering validation checks across callers.
- Decision
- Wrap domain concepts that carry invariants or units into lightweight dedicated types (value objects, branded types, Go defined types, Java `record`) validated once at the boundary.
- Outcome
- Adds minor serialization glue at I/O edges while eliminating swapped-ID, unit-confusion, and missing-validation bugs statically.
typescript · Anti-pattern
// customerId と invoiceId、税込額と税抜額を取り違えても型エラーにならない
function issueBill(a: string, b: string, amount: number, rate: number): number {
return amount * rate;
}typescript · Fix
type CustomerId = string & { readonly __brand: "CustomerId" };
type Yen = number & { readonly __brand: "Yen" };Sources:Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Primitive Obsession·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第5章 プリミティブ型執着
Livingrule⚡ C-3 · Performance vs readability⚡ C-4 · Consistency vs local optimumresiliencestability-antipattern
Unbounded timeouts & naive retry loops — cascading hangs and retry storms
atlas/oop-retry-without-timeout-backoff
general answer 2 · here 3 · short on both
- Constraint
- Calling remote endpoints with default infinite timeouts (e.g., Go `http.Get`, default `new RestTemplate()`) or tight unbacked retry loops exhausts worker pools during downstream slowdowns, triggers retry storms, and risks duplicate charges on non-idempotent APIs.
- Decision
- Set explicit timeouts on every external I/O call and restrict retries strictly to idempotent operations with bounded attempts, exponential backoff, and jitter.
- Outcome
- Requires explicit HTTP client construction and idempotency planning, while preventing cascading outages and duplicate mutations.
go · Anti-pattern
// デフォルトクライアントはタイムアウト無限大。相手先ハングでゴルーチンが永遠に残る
resp, err := http.Get("https://partner.example/api/rates")go · Fix
client := &http.Client{Timeout: 5 * time.Second}
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://partner.example/api/rates", nil)
resp, err := client.Do(req)Sources:Release It!, 2nd Ed. (Michael T. Nygard) — Ch.5 Stability Patterns: Timeouts / Circuit Breaker / Steady State·Designing Data-Intensive Applications (Martin Kleppmann) — Ch.8 The Trouble with Distributed Systems: Unreliable Networks & Timeouts
Livingpattern⚡ C-4 · Consistency vs local optimumerror-handlingobservability
Swallowed exceptions — empty `catch` / `except: pass` hiding silent failures
atlas/oop-swallowed-exception
general answer 1 · here 2 · short on both
- Constraint
- Catching exceptions with an empty block masks database write failures, billing errors, and misconfigurations as normal success, turning immediate bugs into silent data corruption discovered weeks later.
- Decision
- Propagate unrecoverable errors explicitly to callers; when an exception is genuinely non-fatal (such as best-effort cache cleanup), catch only the narrow expected type with a rationale comment and telemetry.
- Outcome
- Failures surface loudly and early (fail fast), cutting outage triage time and preventing silent state corruption.
typescript · Anti-pattern
try {
await saveAuditRecord(event);
} catch (e) {
// 監査ログ保存失敗が完全に黙殺される
}typescript · Fix
try {
await saveAuditRecord(event);
} catch (err) {
logger.error("audit_record_save_failed", { eventId: event.id, err });
throw err;
}Sources:Effective Java, 3rd Ed. (Joshua Bloch) — Item 77: Don't ignore exceptions·良いコード/悪いコードで学ぶ設計入門(仙塲大也)— 第10章・第12章 不正状態とエラー処理(握りつぶし禁止)·The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Topic 24: Dead Programs Tell No Lies
Livingpattern
Transactional Outbox — consistency and event delivery
atlas/outbox-pattern
general answer 9 · here 9 · aligned
- Constraint
- Kafka publish failed after DB commit, causing inconsistency.
- Decision
- Outbox table + relay worker. Record events in the same transaction.
- Outcome
- Eventual consistency. Relay monitoring is mandatory in operations.
java · Living
@Transactional void placeOrder(Order o) {
repo.save(o);
outbox.save(new OrderPlacedEvent(o.id()));
}Sources:Microservices Patterns
Livingreading⚡ C-3 · Performance vs readabilitydatabaseinfrastructure
PostgreSQL — one process forked per connection
atlas/postgresql-one-process-per-connection
general answer 5 · here 8
- Constraint
- In 1980s design, process isolation beat threads for crash isolation and implementation simplicity.
- Decision
- Postmaster forks a child per client connection. Shared memory + MVCC for concurrency. Connection pooling is app/middleware responsibility.
- Outcome
- Process count scales linearly with connections; memory is the pain point. PgBouncer etc. became ecosystem standard. Crash isolation and stability are high.
sql · Living
-- Each client session = one backend process (visible in pg_stat_activity)
SELECT pid, usename, application_name FROM pg_stat_activity;
Livingpattern⚡ C-3 · Performance vs readabilityweb-framework
Prefix-tree routing — match paths against a tree
atlas/prefix-tree-routing
general answer 8 · here 6
- Constraint
- As routes grow, linear matching that tries each pattern in turn has a worst case proportional to the route count.
- Decision
- Register routes in a tree grouped by shared prefixes (radix tree / trie) and walk it from the start of the path. Parameters and wildcards are child node types.
- Outcome
- Matching scales with path length, not route count. In exchange, overlaps such as /users/:id vs /users/new are handled differently per implementation, with registration errors or precedence rules to learn.
go · Living
type node struct {
path string
indices string
wildChild bool
nType nodeType
children []*node
handlers HandlersChain
}typescript · Living
import { TrieRouter } from 'hono/router/trie-router'
const app = new Hono({ router: new TrieRouter() })Livingrule⚡ C-4 · Consistency vs local optimumjp-invoicefintech
Proration rounding — spec-aligned switch (Strategy rejected)
atlas/proration-switch-not-strategy
general answer 4 · here 9
- Constraint
- Japan invoice rounding is fixed by National Tax Agency guidance. Accounting reconciliation requires 1:1 mapping to spec process IDs.
- Decision
- No Strategy abstraction; switch by process ID with IDs embedded in method names.
- Outcome
- Looks like OCP violation globally, but audit reconciliation effort dropped to one-third. Rule changes ship with spec revisions.
java · Corporate
switch (processId) {
case "PRC-001": return truncateYen(amount);
default: throw new IllegalProcessException(processId);
}Sources:国税庁 適格請求書等 Q&A
Livingpattern⚡ C-5 · Encapsulation vs testabilityapi-client
Proxy — build calls through a stand-in object
atlas/proxy-object
general answer 7 · here 5
- Constraint
- Hand-writing a client function per API route drifts from the server definition and lags behind new routes.
- Decision
- Use a stand-in object that intercepts property access and calls (JavaScript Proxy) to build requests from the path and arguments (GoF remote proxy).
- Outcome
- New routes need no hand-written client. In exchange, calls with no concrete body are hard to follow in debuggers and completion, and untyped call sites can reach routes that do not exist.
typescript · Living
import { hc } from 'hono/client'
import type { AppType } from './server'
const client = hc<AppType>('http://localhost:8787/')
const res = await client.posts.$post({ form: { title: 'Hello' } })Evolvedreading⚡ C-2 · YAGNI vs extensibilitylanguage-design
Python — GIL threading model and evolution toward free-threading
atlas/python-gil-free-threading
general answer 4 · here 7
- Constraint
- CPython reference-count GC needs the GIL for thread safety. Hard to balance multi-core CPU use with simple C extension API.
- Decision
- Kept GIL for years; CPU parallelism via multiprocessing. PEP 703 introduces optional free-threading builds gradually (3.13+ experimental).
- Outcome
- I/O-bound parallelism often fine with threading. CPU-bound needed process split, but C extension compatibility preserved.
python · Living
import threading
# CPU-bound: prefer multiprocessing, not threads (GIL)
from concurrent.futures import ProcessPoolExecutor
Livingpatternfintech
Token Bucket — API rate limiting
atlas/rate-limit-token-bucket
general answer 8 · here 9 · aligned
- Constraint
- Partner API burst traffic violated SLA.
- Decision
- Token bucket at gateway. 429 + Retry-After.
- Outcome
- Document trade-off between burst tolerance and fairness in parameters.
go · Living
limiter := rate.NewLimiter(rate.Limit(100), 200)
if !limiter.Allow() { http.Error(w, "rate limit", 429); return }Sources:Release It!
Livingreading⚡ C-2 · YAGNI vs extensibilityinfrastructuredatabase
Redis — single-threaded event loop design
atlas/redis-single-threaded-event-loop
general answer 6 · here 9
- Constraint
- As an in-memory KVS, low latency is mandatory. Multi-threading increases lock contention and debugging complexity.
- Decision
- Command processing is serialized on a single-threaded event loop. I/O is async via epoll/kqueue; CPU-bound work is delegated to forked child processes (RDB/AOF).
- Outcome
- CPU utilization per instance is limited, but latency stays predictable and the implementation stays simple. Scale horizontally via sharding.
c · Living
// redis-server: one thread runs the event loop
// aeMain(aeEventLoop *eventLoop) { ... process clients ... }Livingpattern
Repository — persistence abstraction
atlas/repository-pattern
general answer 8 · here 8 · aligned
- Constraint
- JPA entities leaked into the domain; unit tests required a DB.
- Decision
- Domain Repository interface + infra implementation. Domain uses Aggregates, not entities.
- Outcome
- Mapping layer cost. Domain tests run with in-memory repos.
java · Living
interface OrderRepository { Optional<Order> findById(OrderId id); void save(Order order); }go · Living
type OrderRepository interface {
FindByID(ctx context.Context, id OrderID) (*Order, error)
Save(ctx context.Context, o *Order) error
}Sources:DDD Evans Ch.6
Livingpattern⚡ C-1 · DRY vs couplingweb-framework
Route groups — bundle a prefix with its middleware
atlas/route-group-composition
general answer 7 · here 7 · aligned
- Constraint
- The same prefix and auth repeat across dozens of routes, such as everything under /api/v1. One omission becomes an authorization gap.
- Decision
- Create a group (sub-app) that owns the prefix and shared middleware, register routes on it, then mount it on the parent.
- Outcome
- Authorization and versioning line up per boundary, and features split cleanly into files. In exchange, path and middleware combinations spread across files, and the final route table is visible only by listing it at startup.
go · Living
v1 := router.Group("/v1", AuthRequired())
v1.GET("/users/:id", getUser)
v1.POST("/users", createUser)typescript · Living
const books = new Hono()
books.get('/', listBooks)
books.get('/:id', getBook)
const app = new Hono()
app.route('/books', books)Livingpattern⚡ C-2 · YAGNI vs extensibilityweb-frameworkserverless
Runtime adapter — absorb entry-point differences in a thin layer
atlas/runtime-adapter
general answer 8 · here 6
- Constraint
- The same app should run on Lambda, Cloudflare, Vercel, and Service Workers. Each runtime has its own event and response format.
- Decision
- The core handles only standard Request / Response. A per-runtime handle() converts the event into a Request and the Response back into the runtime format (Adapter).
- Outcome
- Core tests run without any runtime. In exchange, runtime-specific features such as streaming, binary bodies, and connection info still differ per adapter, and the support matrix needs upkeep.
typescript · Living
import { Hono } from 'hono'
import { handle } from 'hono/aws-lambda'
const app = new Hono()
app.get('/', (c) => c.text('Hello Lambda'))
export const handler = handle(app)Livingpatternweb-frameworkstreaming
Server-Sent Events — one-way push from the server
atlas/server-sent-events
general answer 7 · here 6
- Constraint
- Progress or generated output should arrive incrementally. WebSocket brings bidirectional connection management and proxy setup overhead.
- Decision
- Keep an HTTP response open as text/event-stream and append event and data lines. Reconnection is left to the browser's EventSource.
- Outcome
- Runs on the existing HTTP stack (auth, routing). In exchange, proxy buffering and idle timeouts cut streams easily, and client-to-server messages need separate requests.
go · Living
c.Stream(func(w io.Writer) bool {
msg, ok := <-events
if !ok {
return false
}
c.SSEvent("progress", msg)
return true
})typescript · Living
app.get('/sse', (c) =>
streamSSE(c, async (stream) => {
await stream.writeSSE({ event: 'progress', data: '42' })
})
)Livingprinciple⚡ C-1 · DRY vs coupling⚡ C-3 · Performance vs readabilityprincipledata-integrity
Single Source of Truth (SSOT) — do not duplicate derivable state
atlas/single-source-of-truth-state
general answer 9 · here 8 · aligned
- Constraint
- Storing derivable totals, flags, or counters across multiple tables or UI states causes silent drift the moment one write path forgets to synchronize them.
- Decision
- Establish one authoritative system of record and derive computed values from it; when snapshots or projections are required, mark them explicitly as immutable point-in-time records or rebuildable derived views.
- Outcome
- Synchronization bugs disappear structurally, though high-volume read paths may require explicit materialized projections or caching layers.
typescript · Living
// 元のデータは明細配列のみとし、画面上の合計は別 state に持たず毎回計算する
export function calculateSubtotalYen(lines: ReadonlyArray<{ unitYen: number; qty: number }>): number {
return lines.reduce((sum, line) => sum + line.unitYen * line.qty, 0);
}Sources:Designing Data-Intensive Applications (Martin Kleppmann) — Ch.11 Stream Processing: Derived Data vs. Systems of Record·The Pragmatic Programmer, 2nd Ed. (David Thomas, Andrew Hunt) — Topic 9: DRY & Single Source of Truth
Livingpattern⚡ C-2 · YAGNI vs extensibilitysql-antipatternmaster-data
31 Flavors — hardcoding mutable business categories in SQL ENUM / CHECK constraints
atlas/sql-31-flavors-enum
general answer 4 · here 5
- Constraint
- Listing evolving plans, categories, or statuses directly inside SQL `ENUM` or `CHECK (... IN (...))` forces schema migrations, table locks, and deploys for every business change and makes retiring legacy values painful.
- Decision
- Store mutable domain categories in a lookup table with foreign key constraints and active/effective flags; reserve `ENUM`/`CHECK` strictly for truly invariant small sets.
- Outcome
- Requires seed/reference table management, while enabling zero-DDL additions, retirements, and label updates.
sql · Anti-pattern
CREATE TABLE contracts (
id BIGINT PRIMARY KEY,
plan ENUM('free', 'starter', 'standard', 'pro', 'enterprise') NOT NULL
);sql · Fix
CREATE TABLE contract_plans (
code VARCHAR(32) PRIMARY KEY,
label VARCHAR(100) NOT NULL,
is_active BOOLEAN NOT NULL DEFAULT TRUE
);
CREATE TABLE contracts (
id BIGINT PRIMARY KEY,
plan_code VARCHAR(32) NOT NULL REFERENCES contract_plans(code)
);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.11 31 Flavors·達人に学ぶ DB 設計 徹底指南書(ミック)— 第4章 コード体系とマスタテーブル設計
Livingpattern⚡ C-2 · YAGNI vs extensibility⚡ C-3 · Performance vs readabilitysql-antipatterndata-modeling
Entity-Attribute-Value (EAV) — losing types, NOT NULL, and joins in generic key/value tables
atlas/sql-entity-attribute-value
general answer 2 · here 4
- Constraint
- Modeling domain columns as generic `attr_name` / `attr_value` rows strips away SQL data types, NOT NULL constraints, foreign keys, and straightforward queries, forcing expensive self-joins to reconstruct one entity.
- Decision
- Model known business attributes as typed columns or subtype tables, isolating only genuinely dynamic tenant-defined fields into schema-validated JSONB or a strictly bounded extension table.
- Outcome
- New core attributes require schema migrations, while data integrity, indexing, and query simplicity remain intact.
sql · Anti-pattern
CREATE TABLE contract_attributes (
contract_id BIGINT NOT NULL,
attr_name VARCHAR(100) NOT NULL,
attr_value TEXT -- 数値も日付もすべて文字列になり型・必須検証が効かない
);
sql · Fix
CREATE TABLE contracts (
id BIGINT PRIMARY KEY,
effective_on DATE NOT NULL,
amount_yen BIGINT NOT NULL CHECK (amount_yen >= 0),
custom_fields JSONB NOT NULL DEFAULT '{}'::jsonb -- 動的拡張だけを隔離
);Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.6 Entity-Attribute-Value·達人に学ぶ DB 設計 徹底指南書(ミック)— 第8章 データベース設計のアンチパターン(メタテーブル・EAV)
Livingpattern⚡ C-4 · Consistency vs local optimumsql-antipatternthree-valued-logic
Fear of the Unknown — SQL NULL three-valued logic traps (`= NULL`, `NOT IN`)
atlas/sql-fear-of-the-unknown-null
general answer 2 · here 3 · short on both
- Constraint
- Because SQL `NULL` evaluates under three-valued logic, `col = NULL` or `col != NULL` never matches, and `NOT IN (SELECT ...)` silently returns zero rows if the subquery contains even a single `NULL`.
- Decision
- Use `IS NULL` / `IS NOT NULL` / `IS DISTINCT FROM` and `NOT EXISTS` instead of `NOT IN`, and enforce `NOT NULL` with explicit status values where distinct business meanings exist.
- Outcome
- Prevents silent empty-result bugs and eliminates ambiguous missing-value semantics across reporting and billing queries.
sql · Anti-pattern
-- サブクエリ結果に NULL が 1 件でも含まれると全件 0 件になる
SELECT id FROM orders WHERE customer_id NOT IN (SELECT customer_id FROM blocked_customers);
sql · Fix
SELECT o.id
FROM orders o
WHERE NOT EXISTS (
SELECT 1 FROM blocked_customers b WHERE b.customer_id = o.customer_id
);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.13 Fear of the Unknown·達人に学ぶ DB 設計 徹底指南書(ミック)— 第7章 論理設計とバッドノウハウ(NULL の罠)
Livingrule⚡ C-3 · Performance vs readabilitysql-antipatternfintechmoney
Floating-point money — rounding errors from FLOAT / DOUBLE monetary columns
atlas/sql-floating-point-money
general answer 1 · here 2 · short on both
- Constraint
- Binary floating-point types cannot represent decimal fractions like 0.1 exactly, causing penny/yen drift and broken SUM reconciliations in billing, tax, and accounting pipelines.
- Decision
- Store monetary amounts and tax rates using exact `NUMERIC`/`DECIMAL` or integer minor units (`BIGINT`), and use exact decimal or integer arithmetic in application code with explicit rounding rules.
- Outcome
- Exact decimal arithmetic is slightly slower than hardware floats, while guaranteeing audit-grade monetary reconciliation.
sql · Anti-pattern
CREATE TABLE invoice_lines (
id BIGINT PRIMARY KEY,
unit_price DOUBLE PRECISION NOT NULL, -- 2進誤差で請求合計が合わない
tax_rate FLOAT NOT NULL
);
sql · Fix
CREATE TABLE invoice_lines (
id BIGINT PRIMARY KEY,
unit_price_yen BIGINT NOT NULL CHECK (unit_price_yen >= 0),
tax_rate NUMERIC(5, 4) NOT NULL -- 例: 0.1000
);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.10 Rounding Errors·Effective Java, 3rd Ed. (Joshua Bloch) — Item 60: Avoid float and double if exact answers are required
Livingpattern⚡ C-2 · YAGNI vs extensibility⚡ C-3 · Performance vs readabilitysql-antipatterndata-boundary
Implicit columns (`SELECT *`) — breaking index-only scans and leaking newly added columns
atlas/sql-implicit-columns-select-star
general answer 3 · here 4
- Constraint
- Production `SELECT *` queries break index-only scans, increase payload sizes when wide columns are added, risk accidentally serializing newly added sensitive columns, and break positional mapping.
- Decision
- Explicitly project only the required columns in application queries and maintain an explicit mapping boundary to external responses.
- Outcome
- Adds minor verbosity when introducing columns, while protecting least-privilege data flow and covering index performance.
sql · Anti-pattern
SELECT * FROM accounts WHERE org_id = $1;
-- 後日 encrypted_secret 列を追加した瞬間に不要転送・誤シリアライズのリスクが生じる
sql · Fix
SELECT id, email, display_name, role
FROM accounts
WHERE org_id = $1;
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.16 Implicit Columns·SQL パフォーマンス詳解(Markus Winand)— Index-Only Scan と射影コスト
Livingpattern⚡ C-3 · Performance vs readabilitysql-antipatterndata-modeling
Jaywalking — storing comma-separated IDs in a single column
atlas/sql-jaywalking-csv-column
general answer 2 · here 3 · short on both
- Constraint
- Packing multiple IDs into one delimited string column prevents foreign keys, index lookups, deduplication, and SQL aggregation, forcing brittle LIKE or FIND_IN_SET queries.
- Decision
- Normalize multi-valued associations into an intersection table with composite primary keys and foreign key constraints.
- Outcome
- Schema adds one join table, while the database engine enforces referential integrity, indexing, and reliable aggregation.
sql · Anti-pattern
CREATE TABLE work_orders (
id BIGINT PRIMARY KEY,
assignee_ids VARCHAR(255) -- 例: '101,204,309'(FK もインデックスも効かない)
);
sql · Fix
CREATE TABLE work_order_assignees (
work_order_id BIGINT NOT NULL REFERENCES work_orders(id),
assignee_id BIGINT NOT NULL REFERENCES users(id),
PRIMARY KEY (work_order_id, assignee_id)
);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.2 Jaywalking·達人に学ぶ DB 設計 徹底指南書(ミック)— 第3章 論理設計と正規化(第1正規形違反)
Livingrule⚡ C-3 · Performance vs readability⚡ C-4 · Consistency vs local optimumtransactionresiliencemvcc
External I/O inside a DB transaction — pool exhaustion, lock storms, and MVCC bloat
atlas/sql-long-transaction-external-io
general answer 2 · here 3 · short on both
- Constraint
- Calling payment gateways, mailers, or remote HTTP APIs while holding an open DB transaction pins database connections and row locks for the entire network round-trip, causing pool exhaustion, deadlocks, and MVCC bloat whenever a downstream slows down.
- Decision
- Keep DB transactions strictly scoped to fast local DB operations; move external calls outside the transaction or record them via the Transactional Outbox pattern with idempotency keys.
- Outcome
- Introduces explicit asynchronous/eventual-consistency handling, while isolating database stability from third-party outages.
typescript · Anti-pattern
await db.transaction(async (tx) => {
await tx.insert(orders).values(order);
await fetch("https://billing.example/charge", { method: "POST", body }); // 外部遅延中ずっと DB ロック保持
});typescript · Fix
await db.transaction(async (tx) => {
await tx.insert(orders).values(order);
await tx.insert(outboxEvents).values({ type: "order.charge", payload: order });
});
// 別ワーカーが Outbox から外部決済 API をべき等キー付きで実行するSources:Designing Data-Intensive Applications (Martin Kleppmann) — Ch.7 Transactions & Isolation / Ch.9 Consistency·Database Internals(Alex Petrov / 邦題『詳解 データベース』)— Ch.5 Transaction Processing & MVCC·Release It!, 2nd Ed. (Michael T. Nygard) — Ch.4 Stability Antipatterns: Cascading Failures & Blocked Threads
Livingpattern⚡ C-1 · DRY vs coupling⚡ C-3 · Performance vs readabilitysql-antipatterndata-modeling
Multicolumn attributes — repeating numbered columns (`tag1`, `tag2`, `tag3`)
atlas/sql-multicolumn-attributes
general answer 2 · here 3 · short on both
- Constraint
- Storing repeating values in numbered columns hard-caps cardinality, breaks every query when a fourth slot is needed, forces slow OR chains across columns, and allows duplicate values across slots.
- Decision
- Extract repeating attributes into a child table keyed by `(parent_id, value)` with a foreign key constraint.
- Outcome
- Queries join or aggregate the child table, while cardinality becomes unbounded and indexing plus deduplication work naturally.
sql · Anti-pattern
CREATE TABLE incidents (
id BIGINT PRIMARY KEY,
tag1 VARCHAR(50),
tag2 VARCHAR(50),
tag3 VARCHAR(50) -- 4個目のタグ追加で DDL と全 SQL が壊れる
);
sql · Fix
CREATE TABLE incident_tags (
incident_id BIGINT NOT NULL REFERENCES incidents(id),
tag VARCHAR(50) NOT NULL,
PRIMARY KEY (incident_id, tag)
);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.8 Multicolumn Attributes·達人に学ぶ DB 設計 徹底指南書(ミック)— 第3章 繰り返しグループの排除
Livingpattern⚡ C-3 · Performance vs readabilitysql-performanceindexing
Non-sargable predicate — wrapping indexed columns in functions or leading `%` LIKE
atlas/sql-non-sargable-index-predicate
general answer 3 · here 4
- Constraint
- Wrapping filtered columns in functions (`YEAR(created_at)`, `LOWER(email)`) or using leading wildcards (`LIKE '%foo%'`) defeats standard B-Tree indexes and triggers full table scans as data grows.
- Decision
- Rewrite date filters as half-open ranges (`>=` and `<`), and when case-insensitive or substring search is required, pair it explicitly with an expression index, `citext`, or `pg_trgm`/full-text indexing.
- Outcome
- Small predicate adjustments preserve predictable logarithmic lookup times as tables scale by orders of magnitude.
sql · Anti-pattern
SELECT id, total_yen FROM orders WHERE DATE(created_at) = '2026-12-01';
-- created_at の B-Tree インデックスが使えずフルスキャンになる
sql · Fix
SELECT id, total_yen
FROM orders
WHERE created_at >= '2026-12-01T00:00:00Z'
AND created_at < '2026-12-02T00:00:00Z';
Sources:SQL パフォーマンス詳解(Markus Winand / Use The Index, Luke!)— 第2章 Where 句と関数インデックス・LIKE 検索·SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.18 Poor Man's Search Engine·Database Internals(Alex Petrov / 邦題『詳解 データベース』)— Ch.2 B-Tree 探索の順序前提
Livingpattern⚡ C-1 · DRY vs coupling⚡ C-4 · Consistency vs local optimumsql-antipatternreferential-integrity
Polymorphic associations — breaking foreign keys with `entity_type` + `entity_id`
atlas/sql-polymorphic-associations
general answer 3 · here 4
- Constraint
- Pointing one child table at multiple parent tables via string `entity_type` and untyped `entity_id` prevents database foreign keys, allowing orphaned rows and mismatched references to accumulate silently.
- Decision
- Split into per-parent join tables or introduce a shared parent supertype table so standard foreign key constraints enforce referential integrity.
- Outcome
- Adds explicit association tables, while eliminating orphan rows and misdirected joins at the database boundary.
sql · Anti-pattern
CREATE TABLE attachments (
id BIGINT PRIMARY KEY,
entity_type VARCHAR(50) NOT NULL, -- 'invoice' | 'contract' など(FK が張れない)
entity_id BIGINT NOT NULL
);
sql · Fix
CREATE TABLE invoice_attachments (
invoice_id BIGINT NOT NULL REFERENCES invoices(id),
attachment_id BIGINT NOT NULL REFERENCES attachments(id),
PRIMARY KEY (invoice_id, attachment_id)
);
Sources:SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.7 Polymorphic Associations·達人に学ぶ DB 設計 徹底指南書(ミック)— 第8章 ダブルミーニングと参照整合性
Livingpattern⚡ C-3 · Performance vs readabilitysql-performancestorage-engineb-tree
Random UUID v4 primary keys — B-Tree fragmentation and page splits on write-heavy tables
atlas/sql-random-uuid-btree-fragmentation
general answer 5 · here 6
- Constraint
- Using random UUID v4 values directly as primary keys on high-write tables scatters inserts across random B-Tree leaf pages, triggering frequent page splits, poor buffer-cache locality, and write-ahead log amplification.
- Decision
- Prefer time-ordered UUID v7 / ULID or monotonic `BIGINT` identity keys (with a separate public UUID column if opaque external IDs are needed) to preserve right-edge B-Tree append locality.
- Outcome
- UUID v7 embeds coarse creation timestamps (unsuitable for secret bearer tokens), while substantially improving write throughput and index density on transactional tables.
sql · Anti-pattern
CREATE TABLE audit_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), -- 高頻度追記で B-Tree ページ分割が頻発
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
sql · Fix
CREATE TABLE audit_events (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, -- または UUID v7
public_id UUID NOT NULL UNIQUE DEFAULT gen_random_uuid(),
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
Sources:Database Internals(Alex Petrov / 邦題『詳解 データベース』)— Ch.2 B-Tree Basics / Ch.4 Page Splits & Write Amplification·Designing Data-Intensive Applications (Martin Kleppmann) — Ch.3 Storage and Retrieval: B-Trees and Write-Ahead Logs·RFC 9562 (UUID Version 7)
Livingrule⚡ C-3 · Performance vs readability⚡ C-4 · Consistency vs local optimumsql-antipatternaudit-trailbusiness-system
Soft delete (`deleted_at` / `del_flg`) — UNIQUE collisions and leaked queries
atlas/sql-soft-delete-unique-conflict
general answer 4 · here 7
- Constraint
- Adding `deleted_at` or `del_flg` blindly to every table causes re-registration UNIQUE constraint failures, silent data leaks whenever one query omits `WHERE deleted_at IS NULL`, and dangling references to soft-deleted parents.
- Decision
- Clarify why records must survive deletion (statutory retention, undo, or history) and deliberately choose archive/history tables, explicit lifecycle states, or partial unique indexes (`WHERE deleted_at IS NULL`) with enforced query boundaries.
- Outcome
- Requires explicit per-table lifecycle design instead of a blanket flag, preventing ghost data exposure and index bloat.
sql · Anti-pattern
CREATE TABLE users (
id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE, -- 論理削除後に同じ email で再登録できない
deleted_at TIMESTAMPTZ
);
sql · Fix
-- 方式A: 履歴/アーカイブ分離。論理削除が必須なら部分一意インデックスで境界を閉じる
CREATE TABLE users (
id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL,
deleted_at TIMESTAMPTZ
);
CREATE UNIQUE INDEX uq_users_active_email ON users (email) WHERE deleted_at IS NULL;
Sources:達人に学ぶ DB 設計 徹底指南書(ミック)— 第8章・第9章 論理削除の罠と履歴テーブル設計·SQL Antipatterns, Vol. 1 (Bill Karwin) — Ch.13 Fear of the Unknown (NULL & Unique Constraints)
Livingreading⚡ C-3 · Performance vs readabilityembeddeddatabase
SQLite — zero external deps + 100% branch coverage
atlas/sqlite-zero-deps-branch-coverage
general answer 8 · here 9 · aligned
- Constraint
- Embedded, offline, single-file distribution required. External libraries and resident servers unacceptable.
- Decision
- Self-contained on standard C library only. Tests target 100% branch coverage and MC/DC as quality philosophy.
- Outcome
- Build and deploy stay extremely simple. High test effort, low adoption barrier in embedded. Not suited for large concurrent writes.
c · Living
// Single amalgamation file, no external deps
sqlite3 *db;
sqlite3_open("app.db", &db);Livingprinciple⚡ C-5 · Encapsulation vs testability
SRP — one reason to change
atlas/srp-single-responsibility
general answer 9 · here 8 · aligned
- Constraint
- UserService handled auth, profile, and billing notifications; unrelated tests broke on every change.
- Decision
- Split into AuthService / ProfileService / BillingNotifier.
- Outcome
- More classes, but changes localize and reviews get easier.
java · Living
class ProfileService { void updateProfile(UserId id, Profile p) { /* ... */ } }go · Living
type ProfileUpdater interface { Update(ctx context.Context, id UserID, p Profile) error }Sources:Clean Architecture Ch.7
Livingpattern⚡ C-4 · Consistency vs local optimumweb-framework
Standard handler boundary — conform to http.Handler / fetch
atlas/standard-handler-interface
general answer 9 · here 7 · aligned
- Constraint
- A framework-specific entry point does not plug into existing servers, test tools, or middleware. Every runtime change means a rewrite.
- Decision
- Shape the entry point after the language or platform standard. Go uses ServeHTTP(ResponseWriter, *Request); the web uses fetch(Request) → Response.
- Outcome
- Standard tools (httptest, the net/http server, each runtime) work as-is. In exchange, features outside the standard (path params, typed context) move into a framework Context, leaving two API layers to learn.
go · Living
// ServeHTTP conforms to the http.Handler interface.
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) { /* ... */ }
http.ListenAndServe(":8080", router)typescript · Living
const app = new Hono()
app.get('/', (c) => c.text('ok'))
export default { fetch: app.fetch }Livingpattern⚡ C-2 · YAGNI vs extensibilityfintech
Strategy Pattern — escaping if-else hell
atlas/strategy-pattern-payment
general answer 8 · here 7 · aligned
- Constraint
- Payment methods were added every quarter; a single function's if/else chain approached 500 lines.
- Decision
- Split into a PaymentStrategy interface and implementations; Processor only injects a strategy.
- Outcome
- New payment methods require only a new class. Tests run per strategy. Velocity dipped briefly in the first month due to abstraction cost.
java · Living
interface PaymentStrategy { PaymentResult process(Money amount); }
class CreditCardPayment implements PaymentStrategy { /* ... */ }typescript · Evolved
type PayFn = (amount: number) => Promise<Result>;
const strategies: Record<string, PayFn> = { credit: payCredit, paypal: payPaypal };go · Living
type PaymentStrategy interface { Process(ctx context.Context, amount int64) error }Livingpattern
Structured Logging — observability foundation
atlas/structured-logging
general answer 9 · here 9 · aligned
- Constraint
- printf logs made incidents untraceable.
- Decision
- JSON structured logs + trace_id propagation.
- Outcome
- Log volume grows. Search and correlation improve dramatically.
go · Living
slog.Info("order placed", "order_id", id, "trace_id", traceID(ctx))typescript · Living
logger.info({ orderId, traceId }, 'order placed');Sources:Observability Engineering
Livingreading⚡ C-5 · Encapsulation vs testabilitylanguage-designfrontend
TypeScript — design without runtime type checking
atlas/typescript-structural-types-no-runtime
general answer 7 · here 9 · aligned
- Constraint
- Riding the JavaScript ecosystem requires avoiding runtime overhead and bundle bloat.
- Decision
- Types compile-time only (structural typing). Runtime validation is opt-in (zod/io-ts). Emit erases to JS.
- Outcome
- Type safety only at build time. API boundaries need a separate validation layer. Max JS interop.
typescript · Living
interface User { id: string; name: string }
// Erased at runtime — no typeof User check
const u: User = JSON.parse(body);Livingrulefintech
Value Object — type-safe Money
atlas/value-object-money
general answer 9 · here 9 · aligned
- Constraint
- Mixed int/float caused currency unit bugs in production.
- Decision
- Enforce Money value object (amount + currency) at boundaries.
- Outcome
- More conversion boilerplate. Bug class dropped sharply.
java · Living
record Money(BigDecimal amount, Currency currency) {
Money add(Money other) { /* same currency check */ }
}Sources:DDD Evans
Livingprinciple⚡ C-2 · YAGNI vs extensibilityprinciplearchitecture-tradeoff
YAGNI & over-engineering threshold — match architecture layers to real complexity
atlas/yagni-overengineering-threshold
general answer 8 · here 8 · aligned
- Constraint
- Applying heavy multi-layer Clean Architecture or full tactical DDD rituals to straightforward CRUD apps forces six-file edits for every trivial field change and stalls delivery.
- Decision
- Build only for confirmed current requirements and introduce heavy domain/layer abstractions only when invariant complexity, team scale, or real swappable external boundaries justify the cost.
- Outcome
- Initial delivery stays fast and readable, while teams must track review points to refactor cleanly when real domain complexity arrives.
go · Living
// 実装が 1 つだけの時期に推測で Repository/UseCase/Presenter インターフェースを量産しない
func CreateCustomer(ctx context.Context, db *sql.DB, in CustomerInput) (Customer, error) {
if err := in.Validate(); err != nil {
return Customer{}, err
}
return insertCustomer(ctx, db, in)
}Sources:A Philosophy of Software Design, 2nd Ed. (John Ousterhout) — Ch.4 Modules Should Be Deep / Complexity·Refactoring, 2nd Ed. (Martin Fowler) — Ch.3 Bad Smells in Code: Speculative Generality·Clean Architecture (Robert C. Martin) — Boundaries & Pragmatic Trade-offs