[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,92 +2,186 @@
id: wiki-2026-0508-객체-지향-소프트웨어-아키텍처-설계
title: 객체 지향 소프트웨어 아키텍처 설계
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-B40B56]
aliases: [OO architecture, OOA/D, Object-Oriented Architecture]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [oop, architecture, design, ddd]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - 객체 지향 소프트웨어 아키텍처 설계"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: python
framework: ddd
---
# [[객체 지향 소프트웨어 아키텍처 설계|객체 지향 소프트웨어 아키텍처 설계]]
# 객체 지향 소프트웨어 아키텍처 설계
## 📌 한 줄 통찰 (The Karpathy Summary)
> **객체 지향 소프트웨어 아키텍처 설계**는 데이터와 행동을 객체(Object) 내에 캡슐화하여 복잡한 시스템을 더 작고 관리하기 쉬운 단위로 구성하는 패러다임입니다 [1, 2]. 이는 코드의 의존성을 줄이고 재사용성을 높여 소프트웨어를 더 이해하기 쉽고, 유연하며, 유지보수가 가능하도록 만드는 것을 핵심 목표로 합니다 [3, 4].
## 한 줄
> **"매 behavior + state 의 cohesive object 의 cluster"**. 매 OO architecture 의 system 의 collaborating object 의 graph 의 model — 매 modern stack 의 DDD + Clean/Hexagonal + SOLID 의 layered.
## 📖 구조화된 지식 (Synthesized Content)
* **객체 캡슐화와 관심사의 분리(SoC):** 1980년대에 대두된 객체 지향 프로그래밍(OOP) 패러다임은 데이터와 행위를 객체 내에 캡슐화함으로써 서로 다른 객체 간의 자연스러운 **관심사 분리([[_뇌와 팔다리의 분리_ - 관심사의 분리 (Separation of Concerns)|Separation of Concerns]])**를 이끌어냈습니다 [1, 2]. 각 객체가 특정한 측면의 기능이나 책임에 집중하게 함으로써 모듈화, 유지보수성, 확장성을 향상시킵니다 [2, 5].
* **SOLID 원칙 기반의 설계:** 객체 지향 아키텍처의 견고한 기반은 **SOLID 원칙**(단일 책임, 개방/폐쇄, 리스코프 치환, 인터페이스 분리, 의존성 역전)에 의해 주도됩니다 [3]. 이 원칙들은 서로 협력하여 컴포넌트 간의 결합도를 낮추고 코드의 부패를 방지합니다 [3]. 특히 '단일 책임 원칙(SRP)'과 '인터페이스 분리 원칙(ISP)'은 관심사의 분리 개념에서 직접적으로 파생된 중요한 요소입니다 [6, 7].
* **객체 지향적인 횡단 관심사(Cross-Cutting Concerns) 처리:** 시스템의 여러 영역에 걸쳐 발생하는 횡단 관심사 문제 역시 SOLID 설계 원칙을 활용해 객체 지향적으로 해결할 수 있습니다 [8]. 다형성(Polymorphism)을 기반으로 확장 가능한 클래스 집합을 생성하고, 추상 기반 클래스를 **템플릿 메서드(Template Method)**나 **전략([[Strategy|Strategy]]) 패턴**을 이용해 오버라이드하는 방식으로 기능을 구현하여 개방-폐쇄 원칙을 준수할 수 있습니다 [8, 9].
* **AOP(관점 지향 프로그래밍)를 통한 아키텍처 보완:** 전통적인 객체 지향 프로그래밍은 모듈을 기능 단위로 수직적 분리하는 데는 효과적이지만, 로깅이나 보안과 같이 시스템 전체에 흩어진 공통 기능들을 완벽히 분리하는 데는 한계가 있습니다 [10]. 이를 보완하기 위해 AOP 접근 방식을 더하여 횡단 관심사를 수평적으로 분리하고 모듈화하면, **OOP 코드를 더욱 단순화하고 역할을 명확하게 분리**할 수 있습니다 [10, 11].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 Layered architecture
- **Domain**: 매 entity, value object, aggregate root.
- **Application**: 매 use case, 매 thin orchestration.
- **Infrastructure**: 매 DB, queue, external API adapter.
- **Interface**: 매 HTTP, CLI, gRPC.
- **Rule**: 매 dependency 의 inward 의 only (Clean Architecture).
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[SOLID 원칙|SOLID 원칙]], [[관심사의 분리 (SoC)|관심사의 분리(SoC]], AOP(관점 지향 프로그래밍)
- **Projects/Contexts:** 소프트웨어 모듈화 및 컴포넌트 설계, 의존성 관리와 횡단 관심사 처리
- **Contradictions/Notes:** 소스에서는 횡단 관심사를 처리할 때 객체 지향 프로그래밍의 다형성과 디자인 패턴(전략 패턴 등)을 통해 확장 가능하도록 설계할 수 있다고 설명하지만 [8], 동시에 OOP가 갖는 수직적 분리의 한계 때문에 코드의 복잡성을 낮추고 중복을 제거하려면 AOP(관점 지향 프로그래밍)를 통한 수평적 분리로 시스템을 보완해야 한다는 점을 함께 지적합니다 [10, 11].
### 매 Building blocks (DDD)
- **Entity**: identity 의 have (User#42).
- **Value object**: identity 의 X, immutable (Money(100, USD)).
- **Aggregate**: consistency boundary, 매 root 의 only 의 외부 의 expose.
- **Repository**: aggregate 의 persist abstraction.
- **Service**: stateless behavior 의 cross-aggregate.
- **Event**: aggregate state change 의 broadcast.
---
*Last updated: 2026-04-18*
### 매 Design principles
- **SOLID**: SRP, OCP, LSP, ISP, DIP.
- **Composition over inheritance**: 매 has-a > is-a.
- **Tell, don't ask**: 매 behavior 의 object 의 push.
- **Law of Demeter**: 매 don't talk to strangers.
---
### 매 응용
1. E-commerce checkout (Order aggregate).
2. Banking transfer (Account + Transaction).
3. SaaS multi-tenant (Tenant boundary).
4. Game state machine.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
## 💻 패턴
**언제 이 지식을 쓰는가:**
- *(TODO)*
### Aggregate root + repository (Python)
```python
from dataclasses import dataclass, field
from decimal import Decimal
from uuid import UUID, uuid4
**언제 쓰면 안 되는가:**
- *(TODO)*
@dataclass(frozen=True)
class Money: # value object
amount: Decimal
currency: str
def __add__(self, o: "Money") -> "Money":
if self.currency != o.currency: raise ValueError
return Money(self.amount + o.amount, self.currency)
## 🧪 검증 상태 (Validation)
@dataclass
class OrderLine:
sku: str
qty: int
price: Money
- **정보 상태:** needs_review
- **출처 신뢰도:** A
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
class Order: # aggregate root
def __init__(self, id: UUID, lines: list[OrderLine]):
self.id = id
self._lines = lines
self._events: list = []
## 🧬 중복 검사 (Duplicate Check)
def add_line(self, line: OrderLine) -> None:
if any(self.id == "shipped" for l in self._lines): raise RuntimeError
self._lines.append(line)
self._events.append(("LineAdded", line))
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
- **처리 방식:** UPDATE (자동 정규화)
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
def total(self) -> Money:
return sum((l.price for l in self._lines), Money(Decimal(0), "USD"))
## 🕓 변경 이력 (Changelog)
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|------|-----------|-----------|--------|
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
## 💻 코드 패턴 (Code Patterns)
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
```text
# TODO
class OrderRepo: # abstraction (port)
def get(self, id: UUID) -> Order: ...
def save(self, order: Order) -> None: ...
```
## 🤔 의사결정 기준 (Decision Criteria)
### Hexagonal port + adapter
```python
from typing import Protocol
**선택 A를 써야 할 때:**
- *(TODO)*
class PaymentGateway(Protocol): # port
def charge(self, amount: Money, token: str) -> str: ...
**선택 B를 써야 할 때:**
- *(TODO)*
class StripeAdapter: # adapter
def charge(self, amount: Money, token: str) -> str:
return stripe.Charge.create(amount=int(amount.amount * 100), source=token).id
**기본값:**
> *(TODO)*
class CheckoutService: # application
def __init__(self, orders: OrderRepo, payments: PaymentGateway):
self._orders, self._payments = orders, payments
## ❌ 안티패턴 (Anti-Patterns)
def checkout(self, order_id: UUID, token: str) -> str:
order = self._orders.get(order_id)
return self._payments.charge(order.total(), token)
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Domain event + handler
```python
from blinker import signal
order_placed = signal("order_placed")
@order_placed.connect
def send_email(sender, order: Order):
mailer.send(order.customer_email, "Receipt", order.total())
```
### Strategy via composition
```python
class ShippingPolicy(Protocol):
def cost(self, order: Order) -> Money: ...
class FlatRate:
def cost(self, order): return Money(Decimal(5), "USD")
class WeightBased:
def cost(self, order): return Money(Decimal(order.weight() * 0.5), "USD")
# inject, not inherit
class Cart:
def __init__(self, shipping: ShippingPolicy): self._shipping = shipping
```
### Bounded context boundary
```
[Sales Context] [Shipping Context]
Order(customer, lines) --→ Shipment(orderId, address)
(own model, own DB) (own model, own DB)
↕ ↕
Anti-Corruption Layer (translate DTOs)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Complex business rules | DDD aggregate |
| CRUD + thin logic | Active Record / transaction script |
| Multi-team scale | Bounded context split |
| External I/O isolation | Hexagonal port/adapter |
| Cross-cutting policy | Decorator / middleware |
**기본값**: Clean Architecture + DDD lite + Hexagonal port.
## 🔗 Graph
- 부모: [[Software Architecture]] · [[Object-Oriented-Programming]]
- 변형: [[Domain-Driven Design]] · [[Hexagonal Architecture]] · [[Clean Architecture]]
- 응용: [[Microservices]] · [[CQRS]] · [[Event Sourcing]]
- Adjacent: [[SOLID]] · [[Refactoring_Best_Practices]] · [[Bounded Context]]
## 🤖 LLM 활용
**언제**: aggregate boundary suggestion, code → DDD pattern mapping, layer violation detection.
**언제 X**: 매 over-engineering trivial CRUD — 매 LLM 의 DDD 의 over-prescribe 의 tendency, 의 push back.
## ❌ 안티패턴
- **Anemic domain**: 매 getter/setter only data class + service 의 logic, 의 behavior 의 entity 의 push.
- **God aggregate**: 매 한 aggregate 의 entire system, 의 split.
- **Leaky abstraction**: 매 ORM model 의 domain 의 exposure, 의 separate.
- **Inheritance for reuse**: 매 deep hierarchy, 의 composition.
- **Layer skipping**: 매 controller → repository 직접, 의 application service 의 통과.
## 🧪 검증 / 중복
- Verified (Evans "DDD" 2003, Vernon "Implementing DDD", Martin "Clean Architecture").
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full OO architecture entry, DDD + Hexagonal patterns |