[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,93 +2,160 @@
|
||||
id: wiki-2026-0508-solid-principles
|
||||
title: SOLID Principles
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-AUTO-WIKI-ARCH-001]
|
||||
aliases: [SOLID, SOLID 원칙, OOD Principles]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.95
|
||||
tags: [architecture, ooad, solid-principles, maintainability, code-review, p-reinforce]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [oop, design-principles, clean-code]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-01
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: none
|
||||
---
|
||||
|
||||
# [[SOLID Principles]]
|
||||
# SOLID Principles
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "소프트웨어의 유지보수성과 확장성을 보장하기 위한 5가지 핵심 설계 기둥: 인지적 부하를 낮추고, 변화에 유연하며, 결합도가 낮은 강건한 시스템을 구축하기 위한 객체지향 설계의 표준 지침."
|
||||
## 매 한 줄
|
||||
> **"매 5개 OOD 원칙 — 매 변경에 견디는 클래스 설계의 기본기"**. Robert C. Martin이 2000년대 초 정리한 5원칙(SRP/OCP/LSP/ISP/DIP)은 매 객체지향 설계의 lingua franca. 2026년에도 매 TypeScript/Kotlin/Swift 코드 review의 매 첫 lens.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
SOLID 원칙은 코드 리뷰와 시스템 설계의 무결성을 평가하는 핵심 기준입니다.
|
||||
## 매 핵심
|
||||
|
||||
1. **[[Single Responsibility Principle (SRP)]]**: 클래스나 함수는 단 하나의 변경 이유만을 가져야 합니다. 모듈화를 통해 가독성과 테스트 용이성을 극대화합니다.
|
||||
2. **Open-Closed Principle (OCP)**: 확장에는 열려 있고 수정에는 닫혀 있어야 합니다. 기존 코드를 건드리지 않고 새로운 기능을 추가할 수 있는 구조를 지향합니다.
|
||||
3. **Liskov Substitution Principle (LSP)**: 하위 타입은 언제나 상위 타입으로 교체 가능해야 합니다. 상속 구조에서의 행동 일관성을 보장합니다.
|
||||
4. **Interface Segregation Principle (ISP)**: 클라이언트가 사용하지 않는 메서드에 의존하도록 강요해서는 안 됩니다. 거대한 인터페이스보다 구체적이고 작은 인터페이스 여러 개가 낫습니다.
|
||||
5. **[[Dependency Inversion Principle (DIP)]]**: 고수준 모듈은 저수준 모듈에 의존해서는 안 되며, 둘 다 추상화에 의존해야 합니다. 구체적인 구현이 아닌 추상화에 의존하여 결합도를 낮춥니다.
|
||||
### 매 5원칙
|
||||
- **S**RP — Single Responsibility: 매 클래스는 매 한 가지 변경 이유.
|
||||
- **O**CP — Open/Closed: 매 확장에 열려, 수정에 닫혀.
|
||||
- **L**SP — Liskov Substitution: 매 서브타입은 매 부모 대체 가능.
|
||||
- **I**SP — Interface Segregation: 매 client는 매 unused method 의존 X.
|
||||
- **D**IP — Dependency Inversion: 매 추상에 의존, 구체에 의존 X.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **추상화의 비용**: 확장성을 위해 인터페이스와 추상화를 과도하게 도입할 경우, 코드의 직관성이 떨어지고 오버엔지니어링(Over-engineering)으로 이어질 수 있습니다. 현재의 요구사항과 미래의 유연성 사이의 실용적 타협(Trade-off)이 필수적입니다.
|
||||
- **실행 흐름 파악의 어려움**: DI(의존성 주입)를 극한으로 활용할 경우 런타임에 의존성이 결정되므로, 코드 정적 분석만으로는 전체 실행 흐름을 파악하기 어려워질 수 있습니다. 이를 보완하기 위한 명확한 문서화와 추적 로직이 필요합니다.
|
||||
### 매 적용 원리
|
||||
- **결합도 ↓**: 매 DIP/ISP가 핵심.
|
||||
- **응집도 ↑**: 매 SRP가 driver.
|
||||
- **다형성 안전성**: 매 LSP/OCP.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[Single Responsibility Principle (SRP)]]: 첫 번째 원칙의 심화.
|
||||
- [[Dependency Injection (DI)]]: DIP를 실현하는 구체적 기법.
|
||||
- [[Clean Architecture]]: SOLID를 애플리케이션 전체로 확장한 구조.
|
||||
- [[Abstraction & Over-engineering]]: 설계 시 경계해야 할 트레이드오프.
|
||||
- [[Test-Driven Development (TDD)]]: 테스트하기 좋은 코드를 만드는 원칙으로서의 연결.
|
||||
---
|
||||
### 매 응용
|
||||
1. Hexagonal/Clean Architecture 의 layering 근거.
|
||||
2. DI container (Spring, NestJS) 의 설계 정당성.
|
||||
3. AI agent tool interface 분리 (ISP).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
## 💻 패턴
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### SRP — 책임 분리
|
||||
```typescript
|
||||
// X — 매 두 책임 (저장 + 알림)
|
||||
class Order {
|
||||
save() { db.insert(this); }
|
||||
notify() { mailer.send(this.user, "ordered"); }
|
||||
}
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
// O
|
||||
class Order { /* domain only */ }
|
||||
class OrderRepo { save(o: Order) { db.insert(o); } }
|
||||
class OrderNotifier { notify(o: Order) { mailer.send(o.user, "ordered"); } }
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### OCP — 확장 가능 구조
|
||||
```typescript
|
||||
interface Discount { apply(price: number): number; }
|
||||
class SeasonalDiscount implements Discount { apply(p: number) { return p * 0.9; } }
|
||||
class VipDiscount implements Discount { apply(p: number) { return p * 0.8; } }
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
class Checkout {
|
||||
constructor(private d: Discount) {}
|
||||
total(p: number) { return this.d.apply(p); }
|
||||
}
|
||||
// 새 할인 추가 = 새 구현만, Checkout 수정 X.
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### LSP — 안전한 대체
|
||||
```typescript
|
||||
// X — Square가 Rectangle invariant 깨뜨림
|
||||
class Rectangle { setW(w:number){} setH(h:number){} }
|
||||
class Square extends Rectangle { setW(w:number){ super.setW(w); super.setH(w); } }
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// O — 분리된 계층
|
||||
interface Shape { area(): number; }
|
||||
class Rectangle implements Shape { constructor(public w:number, public h:number){} area(){ return this.w*this.h; } }
|
||||
class Square implements Shape { constructor(public s:number){} area(){ return this.s*this.s; } }
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### ISP — fat interface 분리
|
||||
```typescript
|
||||
// X
|
||||
interface Worker { code(): void; eat(): void; }
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// O — robot은 eat 안함
|
||||
interface Codeable { code(): void; }
|
||||
interface Eatable { eat(): void; }
|
||||
class Human implements Codeable, Eatable { code(){} eat(){} }
|
||||
class Robot implements Codeable { code(){} }
|
||||
```
|
||||
|
||||
### DIP — 의존성 역전
|
||||
```typescript
|
||||
// 매 high-level은 abstraction에 의존
|
||||
interface Logger { log(msg: string): void; }
|
||||
class ConsoleLogger implements Logger { log(m:string){ console.log(m); } }
|
||||
|
||||
class OrderService {
|
||||
constructor(private logger: Logger) {} // 매 추상 의존
|
||||
place() { this.logger.log("ordered"); }
|
||||
}
|
||||
new OrderService(new ConsoleLogger()).place();
|
||||
```
|
||||
|
||||
### React/Hook 적용 (SRP + DIP)
|
||||
```typescript
|
||||
// 매 hook 분리 + DI
|
||||
function useOrders(repo: OrderRepo = defaultRepo) {
|
||||
return useQuery(["orders"], () => repo.list());
|
||||
}
|
||||
```
|
||||
|
||||
### NestJS DI (DIP 자연스러움)
|
||||
```typescript
|
||||
@Injectable()
|
||||
class OrderService {
|
||||
constructor(@Inject("OrderRepo") private repo: OrderRepo) {}
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 작은 script | 매 SOLID 강제 X. 매 over-engineering 위험. |
|
||||
| 매 production service | 매 5원칙 routinely 적용. |
|
||||
| 매 plugin/extension architecture | OCP+DIP 우선. |
|
||||
| 매 legacy refactor | SRP부터. 매 클래스 분리. |
|
||||
|
||||
**기본값**: 매 production code → 5원칙 review. 매 prototype → 무시 OK.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Object-Oriented Design]] · [[Clean Code]]
|
||||
- 변형: [[GRASP]] · [[CUPID]]
|
||||
- 응용: [[Hexagonal Architecture]] · [[Clean Architecture]] · [[Dependency Injection]]
|
||||
- Adjacent: [[Single Responsibility Principle (SRP)]] · [[Open Closed Principle]] · [[Liskov Substitution]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 코드 review, 매 architecture 결정 정당화, 매 refactor 우선순위 산정.
|
||||
**언제 X**: 매 throwaway script, 매 학습용 toy code.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **SOLID 광신**: 매 모든 클래스를 5원칙 강제 → 매 over-abstraction.
|
||||
- **SRP 오해**: 매 "한 메서드 = 한 클래스" 로 해석.
|
||||
- **DIP 표면적 적용**: 매 interface만 만들고 매 구현 1개 → 매 abstraction noise.
|
||||
- **LSP 명목적 통과**: 매 throw NotImplemented로 매 LSP 우회.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (R.C. Martin "Agile Software Development", Clean Architecture).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — 5원칙 working code patterns 추가 |
|
||||
|
||||
Reference in New Issue
Block a user