docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
---
|
||||
id: wiki-2026-0508-open-closed-principle-ocp
|
||||
title: Open-Closed Principle (OCP)
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [OCP, Open Closed Principle, SOLID OCP]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [solid, ocp, design-principles, oop, architecture]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: TypeScript
|
||||
framework: none
|
||||
---
|
||||
|
||||
# Open-Closed Principle (OCP)
|
||||
|
||||
## 매 한 줄
|
||||
> **"매 extension 에 open, modification 에 closed"**. Bertrand Meyer (1988) 매 originally inheritance, Robert Martin (1996) 매 abstraction-based redefinition. 새 behavior 매 *추가* 의 way 로, 매 existing code 의 *수정* 없이 — strategy / plugin / open enum 등 매 광범위 응용.
|
||||
|
||||
## 매 핵심
|
||||
|
||||
### 매 두 가지 해석
|
||||
- **Meyer's OCP**: 매 inheritance — class 매 closed for modification (매 published interface 안정), open for extension (매 subclass).
|
||||
- **Polymorphic OCP** (Martin): 매 abstraction (interface) 의존, 매 implementation 추가 만 으로 extend.
|
||||
|
||||
### 매 왜 중요
|
||||
- 매 regression 위험 줄임 (existing 안 건드림).
|
||||
- 매 plugin / extension model 가능.
|
||||
- 매 testability — 매 mock implementation 추가 만.
|
||||
|
||||
### 매 응용
|
||||
1. Strategy pattern — payment processor (Stripe, Toss, PayPal).
|
||||
2. Discriminated union 의 add new variant.
|
||||
3. Plugin architecture (Vite plugin, ESLint rule).
|
||||
4. Visitor pattern.
|
||||
5. Middleware chain (Koa, Express).
|
||||
|
||||
## 💻 패턴
|
||||
|
||||
### Strategy interface (TS)
|
||||
```ts
|
||||
interface PaymentProcessor {
|
||||
charge(amount: number, token: string): Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
class StripeProcessor implements PaymentProcessor {
|
||||
async charge(amount: number, token: string) {
|
||||
return { id: `stripe_${Date.now()}` };
|
||||
}
|
||||
}
|
||||
|
||||
class TossProcessor implements PaymentProcessor {
|
||||
async charge(amount: number, token: string) {
|
||||
return { id: `toss_${Date.now()}` };
|
||||
}
|
||||
}
|
||||
|
||||
// New processor → just add new class. CheckoutService unchanged.
|
||||
class CheckoutService {
|
||||
constructor(private processor: PaymentProcessor) {}
|
||||
pay(amt: number, t: string) { return this.processor.charge(amt, t); }
|
||||
}
|
||||
```
|
||||
|
||||
### Discriminated union + exhaustiveness
|
||||
```ts
|
||||
type Shape =
|
||||
| { kind: "circle"; r: number }
|
||||
| { kind: "square"; side: number }
|
||||
| { kind: "triangle"; base: number; height: number };
|
||||
|
||||
function area(s: Shape): number {
|
||||
switch (s.kind) {
|
||||
case "circle": return Math.PI * s.r ** 2;
|
||||
case "square": return s.side ** 2;
|
||||
case "triangle": return (s.base * s.height) / 2;
|
||||
default: {
|
||||
const _exhaust: never = s;
|
||||
throw new Error(_exhaust);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Add 'pentagon' → TS error in `area`, no silent miss.
|
||||
```
|
||||
|
||||
### Plugin / hook registry
|
||||
```ts
|
||||
type Hook<T> = (ctx: T) => void | Promise<void>;
|
||||
class HookRegistry<T> {
|
||||
private hooks: Hook<T>[] = [];
|
||||
add(h: Hook<T>) { this.hooks.push(h); }
|
||||
async run(ctx: T) { for (const h of this.hooks) await h(ctx); }
|
||||
}
|
||||
|
||||
const onUserCreated = new HookRegistry<{ userId: string }>();
|
||||
onUserCreated.add(({ userId }) => sendWelcomeEmail(userId));
|
||||
onUserCreated.add(({ userId }) => analytics.track("user_created", userId));
|
||||
// New behavior → add new hook, no service change.
|
||||
```
|
||||
|
||||
### Visitor pattern
|
||||
```ts
|
||||
interface NodeVisitor<R> {
|
||||
visitNumber(n: NumberNode): R;
|
||||
visitBinary(n: BinaryNode): R;
|
||||
}
|
||||
|
||||
abstract class AstNode { abstract accept<R>(v: NodeVisitor<R>): R; }
|
||||
class NumberNode extends AstNode {
|
||||
constructor(public val: number) { super(); }
|
||||
accept<R>(v: NodeVisitor<R>) { return v.visitNumber(this); }
|
||||
}
|
||||
class BinaryNode extends AstNode {
|
||||
constructor(public op: "+"|"-", public l: AstNode, public r: AstNode) { super(); }
|
||||
accept<R>(v: NodeVisitor<R>) { return v.visitBinary(this); }
|
||||
}
|
||||
|
||||
// New traversal (printer, evaluator, optimizer) → new visitor class.
|
||||
```
|
||||
|
||||
### Middleware chain
|
||||
```ts
|
||||
type Middleware<C> = (ctx: C, next: () => Promise<void>) => Promise<void>;
|
||||
|
||||
function compose<C>(mws: Middleware<C>[]): (ctx: C) => Promise<void> {
|
||||
return async (ctx) => {
|
||||
let i = -1;
|
||||
const dispatch = async (idx: number): Promise<void> => {
|
||||
if (idx <= i) throw new Error("next() called multiple times");
|
||||
i = idx;
|
||||
const fn = mws[idx];
|
||||
if (!fn) return;
|
||||
await fn(ctx, () => dispatch(idx + 1));
|
||||
};
|
||||
await dispatch(0);
|
||||
};
|
||||
}
|
||||
|
||||
const app = compose<{ req: Request; res?: Response }>([
|
||||
async (c, next) => { console.log("log"); await next(); },
|
||||
async (c, next) => { c.res = new Response("ok"); await next(); },
|
||||
]);
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Multiple swappable algos | Strategy / interface |
|
||||
| Closed set of variants | Discriminated union + exhaustive switch |
|
||||
| Open set of behaviors | Plugin / hook registry |
|
||||
| Tree traversal, multiple ops | Visitor |
|
||||
| Pipeline | Middleware chain |
|
||||
| Just one impl, no plans | Don't pre-abstract (YAGNI) |
|
||||
|
||||
**기본값**: 매 second variation 발견 시 abstract — 매 first time 의 over-abstraction X.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[SOLID Principles]] · [[Design-Principles]]
|
||||
- 변형: [[Visitor-Pattern]]
|
||||
- 응용: [[Middleware]] · [[API Response & State Modeling|Discriminated-Unions]] · [[Dependency_Injection_(DI)|Dependency-Injection]]
|
||||
- Adjacent: [[DIP]] · [[Composition-over-Inheritance]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 add-only domain (payment processor, plugin, parser AST), variant 매 자주 추가.
|
||||
**언제 X**: 매 small / unchanging code — 매 abstraction 의 cost > benefit.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Premature abstraction**: 매 single impl 의 interface — 매 indirection 만 추가, value 0.
|
||||
- **Speculative generality**: 매 "혹시 나중에" — YAGNI.
|
||||
- **Inheritance for code reuse**: 매 LSP 위반 risk. Composition 우선.
|
||||
- **Open everything**: 매 모든 method virtual / hook — 매 cognitive load 폭증.
|
||||
- **Ignore exhaustiveness**: 매 switch default fallback — 매 new variant 의 silent skip.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Meyer "Object-Oriented Software Construction", Martin "Clean Architecture", refactoring.guru).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — strategy, discriminated union, plugin/visitor/middleware 패턴 |
|
||||
Reference in New Issue
Block a user