[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,89 +2,180 @@
|
||||
id: wiki-2026-0508-modular-programming
|
||||
title: Modular Programming
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AI-MODULAR]
|
||||
aliases: [Modularity, Module System, Separation of Concerns]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [SoftwareEngineering, Modularization, Architecture, Separation]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [modularity, architecture, software-design, decoupling]
|
||||
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: any
|
||||
---
|
||||
|
||||
# [[Modular-Programming|Modular-Programming]] (모듈형 프로그래밍)
|
||||
# Modular Programming
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "레고 블록처럼 독립적이고 교체 가능한 부품들의 집합체." 거대한 시스템을 작고 관리 가능한 단위(모듈)로 쪼개어, 각 모듈이 하나의 명확한 역할만 수행하게 함으로써 복잡성을 다루는 가장 근본적인 전략이다.
|
||||
## 매 한 줄
|
||||
> **"매 module = 1 concern, 1 contract, 1 owner"**. Parnas 1972 의 information hiding 매 origin. 2026 modular 의 매 form: ES modules, Rust crates, Python packages, Bazel targets — 매 boundary 의 explicit dependency graph.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **[[Principles|Principles]] of [[Modularity|Modularity]]**:
|
||||
- **High Cohesion (고응집)**: 모듈 내부의 요소들은 서로 밀접하게 연관되어 있어야 함.
|
||||
- **Low Coupling (저결합)**: 모듈 간의 연결은 최소화하고 명확한 통로(Interface)만 둬야 함.
|
||||
- **Benefits**:
|
||||
- **Reusability**: 한 프로젝트의 모듈을 다른 곳에 그대로 가져다 쓸 수 있음.
|
||||
- **Parallelism**: 팀원들이 서로의 코드를 건드리지 않고 개별 모듈에 집중 가능.
|
||||
- **Isolations**: 한 부분의 에러가 전체 시스템으로 번지는 것을 방지.
|
||||
- **Techniques**: 패키지 매니저(NPM), 마이크로서비스, 컴포넌트 기반 아키텍처.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- 너무 잘게 쪼개면 '모듈 간 통신 비용(Latentcy, Complexity)'이 관리 비용보다 커지는 **'나노서비스'**의 함정에 빠진다. "어디까지 쪼갤 것인가"는 정답이 없으며, 프로젝트의 규모와 팀의 소통 능력에 따라 유동적으로 결정해야 하는 '엔지니어링적 감각'의 영역이다.
|
||||
### 매 원칙
|
||||
- **High cohesion**: 매 module 의 single responsibility.
|
||||
- **Low coupling**: 매 inter-module 의 narrow interface.
|
||||
- **Information hiding**: 매 implementation detail 의 hide. Public surface 의 minimize.
|
||||
- **Acyclic dependency**: 매 graph 의 DAG. Cycle = refactor signal.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Related: [[Loose-Coupling|Loose-Coupling]] , Single-Responsibility-Principle (SRP)
|
||||
- Result: [[Microservices-Architecture|Microservices-Architecture]]
|
||||
### 매 boundary type
|
||||
- **Logical**: namespace / package.
|
||||
- **Physical**: separate compile unit / artifact.
|
||||
- **Process**: separate deployable (microservice).
|
||||
- **Trust**: separate security domain.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Library author: 매 stable public API + private internals.
|
||||
2. App architect: 매 feature module + shared kernel.
|
||||
3. Platform team: 매 plugin host + extension points.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### ES Module barrel + private
|
||||
```typescript
|
||||
// src/auth/index.ts (public surface)
|
||||
export { signIn, signOut } from "./session";
|
||||
export type { User } from "./types";
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
// src/auth/_internal/hash.ts (convention: _ prefix = private)
|
||||
export function hashPassword(p: string) { /* ... */ }
|
||||
|
||||
- **정보 상태:** 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
|
||||
// consumer
|
||||
import { signIn } from "@/auth"; // ✅
|
||||
import { hashPassword } from "@/auth/_internal/hash"; // ❌ lint rule
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### ESLint boundary rule
|
||||
```json
|
||||
{
|
||||
"rules": {
|
||||
"no-restricted-imports": ["error", {
|
||||
"patterns": [{
|
||||
"group": ["**/_internal/**"],
|
||||
"message": "Internal module — import via public barrel."
|
||||
}]
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Hexagonal port/adapter
|
||||
```typescript
|
||||
// port (module boundary)
|
||||
export interface UserRepo {
|
||||
find(id: string): Promise<User | null>;
|
||||
save(u: User): Promise<void>;
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// adapter (Postgres impl)
|
||||
export class PgUserRepo implements UserRepo {
|
||||
constructor(private db: Pool) {}
|
||||
async find(id: string) { /* ... */ }
|
||||
async save(u: User) { /* ... */ }
|
||||
}
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
// core (depends on port only)
|
||||
export class UserService {
|
||||
constructor(private repo: UserRepo) {}
|
||||
async promote(id: string) {
|
||||
const u = await this.repo.find(id);
|
||||
if (!u) throw new Error("not found");
|
||||
u.role = "admin";
|
||||
await this.repo.save(u);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Dependency injection
|
||||
```typescript
|
||||
const repo = new PgUserRepo(pool);
|
||||
const svc = new UserService(repo);
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// test: swap impl
|
||||
const fake: UserRepo = { find: async () => mockUser, save: async () => {} };
|
||||
new UserService(fake);
|
||||
```
|
||||
|
||||
### Rust crate boundary
|
||||
```toml
|
||||
# Cargo.toml
|
||||
[workspace]
|
||||
members = ["crates/core", "crates/api", "crates/db"]
|
||||
|
||||
[workspace.dependencies]
|
||||
core = { path = "crates/core" }
|
||||
```
|
||||
|
||||
### Python namespace package
|
||||
```python
|
||||
# myapp/auth/__init__.py
|
||||
from .session import sign_in, sign_out
|
||||
from .types import User
|
||||
|
||||
__all__ = ["sign_in", "sign_out", "User"]
|
||||
```
|
||||
|
||||
### Acyclic check
|
||||
```bash
|
||||
npx madge --circular --extensions ts src/
|
||||
# Or: nx graph --focus=auth
|
||||
```
|
||||
|
||||
### Module facade
|
||||
```typescript
|
||||
// payments/index.ts — single entry point
|
||||
export const payments = {
|
||||
charge: (amt: number) => /* ... */,
|
||||
refund: (id: string) => /* ... */,
|
||||
webhook: (req: Request) => /* ... */,
|
||||
};
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Small app (<10k LOC) | Logical modules (folders) |
|
||||
| Medium (10k-100k) | Package boundary + barrel exports |
|
||||
| Large (>100k) | Bazel/Nx targets + enforced graph |
|
||||
| Multi-team | Process boundary (services) |
|
||||
|
||||
**기본값**: 매 logical module + barrel + ESLint boundary rule.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Software-Architecture]] · [[Information-Hiding]]
|
||||
- 변형: [[Microservices]] · [[Hexagonal-Architecture]] · [[Clean-Architecture]]
|
||||
- 응용: [[Monorepo]] · [[Library-Design]] · [[Plugin-Architecture]]
|
||||
- Adjacent: [[Domain-Driven-Design]] · [[SOLID]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 module boundary 의 propose, dependency graph 의 visualize, refactor 의 split-suggest.
|
||||
**언제 X**: 매 domain ownership decision, team org boundary — Conway's law 의 human judgment.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **God module**: 매 utils.ts 의 1000+ exports. Cohesion = 0.
|
||||
- **Circular dependency**: A → B → A. Test 의 hard, build 의 slow.
|
||||
- **Leaky abstraction**: public surface 의 internal type 의 expose.
|
||||
- **Premature modularization**: 100 LOC 매 5개 module = over-engineering.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Parnas 1972 "On the Criteria...", Clean Architecture by Martin, Software Engineering at Google).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — modular programming principles + boundary patterns |
|
||||
|
||||
Reference in New Issue
Block a user