[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,87 +2,184 @@
id: wiki-2026-0508-god-object-antipattern
title: God Object Antipattern
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-GOD-OBJECT]
aliases: [God Class, Blob, Monster Class]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [SoftwareEngineering, AntiPattern, CleanCode, Refactoring]
confidence_score: 0.9
verification_status: applied
tags: [architecture, antipattern, oop, refactoring, code-smell]
raw_sources: []
last_reinforced: 2026-04-20
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: language-agnostic
---
# [[God-Object-Antipattern|God-Object-Antipattern]] (신 객체 안티패턴)
# God Object Antipattern
## 📌 한 줄 통찰 (The Karpathy Summary)
> "모든 것을 알고, 모든 것을 하려다 결국 아무것도 못 하게 만드는 거대 클래스의 재앙." 단일 책임 원칙(SRP)을 무시하고 너무 많은 기능을 한 클래스에 몰아넣어, 유지보수가 불가능한 '블랙홀' 같은 코드를 만드는 현상이다.
## 한 줄
> **"매 single class/module 의 too many responsibilities 의 absorption 의 통한 maintainability 의 collapse"**. 매 Brown et al. "AntiPatterns" (1998) 의 catalog, 매 procedural code 의 OOP 로 의 lift-and-shift 의 결과 — 매 modern microservices 시대 의 "God Service" 로 의 mutation.
## 📖 구조화된 지식 (Synthesized Content)
- **Symptoms**:
- 클래스 이름이 `Manager`, `System`, `Controller`처럼 너무 포괄적임.
- 소스 코드 줄 수가 수천 줄을 넘어가며, 거의 모든 다른 기능과 연결되어 있음.
- 작은 기능 수정 하나가 연쇄적인 부작용(Side Effect)을 일으켜 테스트가 불가능함.
- **Root Cause**: 초기 설계가 부족할 때, 새로운 기능을 기존의 가장 큰 곳에 쑤셔 넣는 '게으른 개발 습관'에서 비롯됨.
- **[[Solution|Solution]]**: 로직을 관심사별로 쪼개어 각각의 전문 클래스로 분리하고, 이들을 조합(Composition)하는 방식으로 리팩토링해야 한다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 때로는 성능 최적화(캐시 히트율, 함수 호출 오버헤드 감소)를 위해 일부러 데이터를 모아두는 경우가 있으나, 이는 극히 예외적인 상황이다. 현대의 가독성과 테스트 중심 개발 환경에서 '신 객체'는 프로젝트의 수명을 갉아먹는 암적 존재로 간주된다.
### 매 Symptoms
- 1000+ LOC class, 50+ methods.
- 매 unrelated domain 의 mix (User + Order + Payment + Logging).
- 매 import 의 fan-in 의 high — 매 module 의 reference 의 most.
- Test 의 setup 의 100+ lines mock.
- Git log 의 churn 의 highest hot-spot.
## 🔗 지식 연결 (Graph)
- Related: Single-Responsibility-Principle (SRP) , Cohesion-and-Coupling
- Action: Refactoring-Techniques
### 매 Causes
- SRP (Single Responsibility) 의 violation.
- Premature centralization ("Manager", "Controller", "Helper" suffix).
- Feature 의 incremental 의 add 의 always-cheapest-place 의 dump.
- Refactoring fear (test 의 X, dependency 의 web).
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용 (detection)
1. SonarQube "Brain Class" rule.
2. Lizard / radon 의 cyclomatic + LOC metric.
3. CodeScene hotspot map.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Smell — God Class
```typescript
// 🚨 God Object
export class ApplicationManager {
users: User[] = [];
orders: Order[] = [];
cart: Cart;
paymentGateway: Stripe;
logger: Logger;
cache: Redis;
// ... 47 more fields
## 🧪 검증 상태 (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
registerUser(...) { /* 80 lines */ }
authenticateUser(...) { /* 60 lines */ }
createOrder(...) { /* 120 lines, calls payment, cache, log */ }
refundOrder(...) { /* 90 lines */ }
sendEmail(...) { /* 40 lines */ }
generateReport(...) { /* 200 lines */ }
// ... 50 more methods
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Refactor — Extract Class (SRP)
```typescript
export class UserService {
constructor(private repo: UserRepository, private hasher: PasswordHasher) {}
async register(input: RegisterInput) { /* ... */ }
async authenticate(creds: Credentials) { /* ... */ }
}
**선택 A를 써야 할 때:**
- *(TODO)*
export class OrderService {
constructor(
private repo: OrderRepository,
private payment: PaymentGateway,
private events: EventBus,
) {}
async create(input: CreateOrderInput) { /* ... */ }
async refund(orderId: string) { /* ... */ }
}
**선택 B를 써야 할 때:**
- *(TODO)*
export class ReportingService { /* ... */ }
```
**기본값:**
> *(TODO)*
### Replace Conditional with Polymorphism
```typescript
// Before: god method 의 switch
processPayment(method: string, amount: number) {
if (method === 'card') { /* ... */ }
else if (method === 'paypal') { /* ... */ }
else if (method === 'crypto') { /* ... */ }
}
## ❌ 안티패턴 (Anti-Patterns)
// After: Strategy
interface PaymentMethod { charge(amount: number): Promise<Receipt>; }
class CardPayment implements PaymentMethod { /* ... */ }
class PayPalPayment implements PaymentMethod { /* ... */ }
class CryptoPayment implements PaymentMethod { /* ... */ }
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
class PaymentService {
constructor(private methods: Map<string, PaymentMethod>) {}
charge(method: string, amount: number) {
return this.methods.get(method)!.charge(amount);
}
}
```
### Extract Aggregate (DDD)
```typescript
// God 의 split → Aggregate Root + Value Objects
export class Order {
private constructor(
public readonly id: OrderId,
private items: LineItem[],
private status: OrderStatus,
) {}
static create(customerId: CustomerId, items: LineItem[]): Order { /* ... */ }
addItem(item: LineItem) { /* invariant 의 enforce */ }
confirm(): DomainEvent[] { /* ... */ }
}
```
### ESLint Rule (max-lines-per-function/class)
```json
{
"rules": {
"max-lines": ["error", { "max": 400, "skipBlankLines": true }],
"max-lines-per-function": ["error", 60],
"complexity": ["error", 10]
}
}
```
### SonarQube Detection
```properties
sonar.cpd.exclusions=**/*.test.ts
# Rule: java:S2972 (Inner classes should not have too many lines)
# Rule: typescript:S138 (Functions should not have too many lines)
# Rule: common:DuplicatedBlocks
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Class > 500 LOC | Extract Class by responsibility |
| Method > 60 LOC | Extract Method, Replace Temp with Query |
| Long parameter list | Introduce Parameter Object |
| Switch on type | Replace Conditional with Polymorphism |
| Cross-domain mix | Extract Bounded Context (DDD) |
**기본값**: 매 SRP — 매 class 의 one reason to change.
## 🔗 Graph
- 부모: [[Antipatterns]] · [[Code-Smells]]
- 변형: [[God-Service]] · [[Big-Ball-of-Mud]] · [[Distributed-Monolith]]
- 응용: [[Refactoring]] · [[SOLID]] · [[DDD]]
- Adjacent: [[High-Cohesion-Low-Coupling]] · [[Single-Responsibility-Principle]] · [[Bounded-Context]]
## 🤖 LLM 활용
**언제**: god class 의 detect, extract-class 의 refactor 의 suggest, responsibility 의 cluster 의 propose.
**언제 X**: 매 large refactor 의 final commit (test coverage 의 human verification 필수).
## ❌ 안티패턴
- **Manager/Helper suffix**: 매 dumping ground 의 invitation.
- **Static God**: `Utils` static class 의 grow → 매 testability 의 destroy.
- **God Service**: microservice 시대 의 god — single service 의 매 domain 의 own.
- **Refactor without tests**: 매 god 의 split 의 시 behavior 의 break 의 silent.
- **Premature split**: 매 50 LOC class 의 over-decompose → 매 anemic + indirection 의 hell.
## 🧪 검증 / 중복
- Verified (Brown et al. "AntiPatterns" 1998, Fowler "Refactoring" 2nd ed., SonarSource rules).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — god object antipattern 의 full content |