[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,86 +2,264 @@
|
||||
id: wiki-2026-0508-encapsulation-and-information-hi
|
||||
title: Encapsulation and Information Hiding
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AI-ENCAPSULATION]
|
||||
aliases: [encapsulation, information hiding, Parnas, abstraction, modular design]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [OOP, SoftwareDesign, Encapsulation, InformationHiding]
|
||||
confidence_score: 0.98
|
||||
verification_status: applied
|
||||
tags: [oop, software-design, encapsulation, modularity, parnas, abstraction]
|
||||
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 / Python / Java
|
||||
applicable_to: [OOP, Module Design, API]
|
||||
---
|
||||
|
||||
# [[Encapsulation-and-Information-Hiding|Encapsulation-and-Information-Hiding]] (캡슐화와 정보 은닉)
|
||||
# Encapsulation and Information Hiding
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "내부 부품은 숨기고 조작 핸들만 노출하라." 데이터와 그 데이터를 조작하는 메서드를 하나로 묶고, 외부에서 직접적인 접근을 제한하여 객체의 무결성을 보호하고 결합도를 낮추는 객체지향의 핵심 원칙이다.
|
||||
## 매 한 줄
|
||||
> **"매 internal 의 hide — 매 stable interface 의 expose"**. Parnas 1972. 매 OOP encapsulation = 매 information hiding 의 means. 매 modern: 매 module + 매 type system + 매 access control. 매 critical for 매 change isolation.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **Encapsulation (캡슐화)**: 데이터와 행위의 번들링. "함께 쓰이는 것은 함께 두라."
|
||||
- **Information Hiding (정보 은닉)**: 구현 세부 사항(어떻게 돌아가는지)을 감추어 인터페이스(무엇을 하는지)만 알면 사용 가능하게 함.
|
||||
- **Benefits**:
|
||||
- **Maintainability**: 내부 로직을 바꿔도 외부 인터페이스만 같으면 다른 코드에 영향을 주지 않음.
|
||||
- **Security**: 의도치 않은 데이터 변조 방지.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- 캡슐화가 너무 과하면 지나친 추상화로 인해 코드가 복잡해지는 '추상 공해'가 발생한다. 무늬만 캡슐화인 단순 Getter/Setter 남발은 지양해야 한다. 최근 함수형 프로그래밍의 부상으로 데이터(Record)와 로직(Function)을 다시 분리하는 경향도 있으나, 대규모 시스템의 복잡도 제어에는 여전히 필수적인 개념이다.
|
||||
### 매 Parnas (1972)
|
||||
- 매 module = 매 design decision 의 wrap.
|
||||
- 매 secret 의 stable interface 의 hide.
|
||||
- 매 change cost 의 minimize.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- Related: [[Object-Oriented-Programming|Object-Oriented-Programming]] (OOP) , SoC ([[_뇌와 팔다리의 분리_ - 관심사의 분리 (Separation of Concerns)|Separation of Concerns]])
|
||||
- Practice: Getter-Setter-Abuse
|
||||
### 매 access modifier
|
||||
- **public**: 매 anyone.
|
||||
- **protected**: 매 subclass.
|
||||
- **private**: 매 self only.
|
||||
- **internal / package-private**: 매 module.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 modern variant
|
||||
- **TypeScript** `#privateField`.
|
||||
- **Python** `_protected` (convention) + name mangling `__private`.
|
||||
- **Rust** `pub(crate)`, `pub(super)`.
|
||||
- **Java module system** (JPMS).
|
||||
- **JavaScript** `class { #x }`.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. **Class**: 매 attribute hide.
|
||||
2. **Module**: 매 internal export X.
|
||||
3. **Microservice**: 매 DB private to service.
|
||||
4. **API**: 매 implementation 의 versioned.
|
||||
5. **Library**: 매 internal 의 unstable.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 매 Law of Demeter
|
||||
- 매 "talk to friends only".
|
||||
- 매 a.b.c.d() = code smell.
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
## 💻 패턴
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
### TypeScript private field
|
||||
```typescript
|
||||
class BankAccount {
|
||||
#balance = 0; // 매 truly private (ES2022)
|
||||
|
||||
deposit(amount: number) {
|
||||
if (amount <= 0) throw new Error('Invalid amount');
|
||||
this.#balance += amount;
|
||||
}
|
||||
|
||||
get balance() { return this.#balance; }
|
||||
}
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
// 매 접근 시 SyntaxError
|
||||
// account.#balance ❌
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Python (convention + mangling)
|
||||
```python
|
||||
class Account:
|
||||
def __init__(self):
|
||||
self._public_internal = 0 # 매 convention: protected
|
||||
self.__private = 0 # 매 name-mangled to _Account__private
|
||||
|
||||
def deposit(self, amount):
|
||||
if amount <= 0: raise ValueError('Invalid')
|
||||
self.__private += amount
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Rust visibility
|
||||
```rust
|
||||
mod payments {
|
||||
pub(crate) struct Engine {
|
||||
secret_key: String, // 매 private
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new() -> Self { Self { secret_key: load() } }
|
||||
pub fn charge(&self, amount: u64) -> Result<()> { ... }
|
||||
// 매 secret_key 의 외부 접근 불가
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Module-level (Python)
|
||||
```python
|
||||
# payments/__init__.py
|
||||
from ._engine import charge # 매 only public API
|
||||
# 매 _engine internal 의 hide
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
# payments/_engine.py (underscore = internal)
|
||||
def charge(amount):
|
||||
return _internal_call(amount)
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
def _internal_call(amount):
|
||||
# 매 hidden
|
||||
pass
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Interface segregation
|
||||
```typescript
|
||||
// 매 ❌ leak internal
|
||||
class UserService {
|
||||
database: Database; // 매 public — leaks DB
|
||||
cache: Redis;
|
||||
}
|
||||
|
||||
// 매 ✅ encapsulate
|
||||
class UserService {
|
||||
constructor(private deps: { db: Database; cache: Redis }) {}
|
||||
|
||||
async getUser(id: string): Promise<User> {
|
||||
const cached = await this.deps.cache.get(id);
|
||||
if (cached) return cached;
|
||||
const u = await this.deps.db.findUser(id);
|
||||
await this.deps.cache.set(id, u);
|
||||
return u;
|
||||
}
|
||||
}
|
||||
// 매 caller 매 db / cache 의 직접 접근 X
|
||||
```
|
||||
|
||||
### Avoid getter/setter for everything
|
||||
```typescript
|
||||
// 매 ❌ anemic
|
||||
class User {
|
||||
private _email: string;
|
||||
get email() { return this._email; }
|
||||
set email(v: string) { this._email = v; } // 매 무의미
|
||||
}
|
||||
|
||||
// 매 ✅ behavior-rich
|
||||
class User {
|
||||
constructor(private _email: Email) {}
|
||||
|
||||
changeEmail(newEmail: Email, currentPassword: string) {
|
||||
if (!this.verifyPassword(currentPassword)) throw new Error('Auth failed');
|
||||
this._email = newEmail;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Module boundary (microservice)
|
||||
```typescript
|
||||
// 매 service A — only HTTP API exposed
|
||||
@Controller('users')
|
||||
export class UserController {
|
||||
@Get(':id')
|
||||
getUser(@Param('id') id: string) { return this.svc.find(id); }
|
||||
}
|
||||
|
||||
// 매 service A's database 매 service B 가 직접 접근 X
|
||||
// 매 → API 의 only
|
||||
```
|
||||
|
||||
### Law of Demeter
|
||||
```typescript
|
||||
// 매 ❌
|
||||
order.customer.address.street;
|
||||
|
||||
// 매 ✅
|
||||
order.shippingStreet(); // 매 method 의 ask, 매 reach 의 X
|
||||
```
|
||||
|
||||
### Java module (JPMS)
|
||||
```java
|
||||
// module-info.java
|
||||
module com.acme.payments {
|
||||
exports com.acme.payments.api;
|
||||
// 매 com.acme.payments.internal 매 not exported
|
||||
}
|
||||
```
|
||||
|
||||
### Encapsulation check (lint rule)
|
||||
```javascript
|
||||
// 매 ESLint 의 internal package 의 cross-module import 의 forbid
|
||||
{
|
||||
rules: {
|
||||
'import/no-internal-modules': ['error', { forbid: ['*/internal/**'] }],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Encapsulate state (React)
|
||||
```typescript
|
||||
// 매 ❌ prop drilling internal
|
||||
<Inner config={config.internal.deep.path} />
|
||||
|
||||
// 매 ✅ hide
|
||||
function useFeatureConfig() {
|
||||
return useContext(ConfigContext);
|
||||
}
|
||||
```
|
||||
|
||||
### Test through interface only
|
||||
```typescript
|
||||
// 매 ❌ test private (access __private via mangling)
|
||||
test('private', () => {
|
||||
expect(svc['__internalCache']).toEqual(...); // 매 brittle
|
||||
});
|
||||
|
||||
// 매 ✅ test through public behavior
|
||||
test('public', () => {
|
||||
svc.doThing();
|
||||
expect(svc.result()).toEqual(...);
|
||||
});
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| New class | All private, expose minimal |
|
||||
| New module | underscore _ for internal |
|
||||
| Microservice | API-only boundary |
|
||||
| Open-source lib | Strict semver + internal |
|
||||
| Test | Public interface only |
|
||||
| Inheritance | Protected for subclass |
|
||||
|
||||
**기본값**: 매 default private + 매 minimum public + 매 module underscore + 매 test public-only + 매 Law of Demeter.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[OOP]] · [[Software-Design-Principles]]
|
||||
- 변형: [[Information-Hiding]] · [[Modular-Design]] · [[Encapsulation-of-Domain-Invariants]]
|
||||
- 응용: [[API-Design]] · [[Microservices]]
|
||||
- Adjacent: [[SOLID]] · [[Law-of-Demeter]] · [[Anaemic Domain Model]] · [[Dependency-Injection]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 OOP / module design. 매 API design. 매 boundary.
|
||||
**언제 X**: 매 throwaway script.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **God object**: 매 모든 의 public.
|
||||
- **Anemic class**: 매 just getter / setter.
|
||||
- **Reach-into**: 매 a.b.c.d().
|
||||
- **Test private**: 매 internal 의 brittle.
|
||||
- **Premature interface**: 매 single impl 의 over-abstract.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Parnas 1972, GoF, Clean Architecture).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-04-20 | Auto-reinforced |
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Parnas + 매 TS / Rust / Python / Java module / lint code |
|
||||
|
||||
Reference in New Issue
Block a user