---
id: wiki-2026-0508-encapsulation-and-information-hi
title: Encapsulation and Information Hiding
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [encapsulation, information hiding, Parnas, abstraction, modular design]
duplicate_of: none
source_trust_level: A
confidence_score: 0.98
verification_status: applied
tags: [oop, software-design, encapsulation, modularity, parnas, abstraction]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
  language: TypeScript / Python / Java
  applicable_to: [OOP, Module Design, API]
---

# Encapsulation and Information Hiding

## 매 한 줄
> **"매 internal 의 hide — 매 stable interface 의 expose"**. Parnas 1972. 매 OOP encapsulation = 매 information hiding 의 means. 매 modern: 매 module + 매 type system + 매 access control. 매 critical for 매 change isolation.

## 매 핵심

### 매 Parnas (1972)
- 매 module = 매 design decision 의 wrap.
- 매 secret 의 stable interface 의 hide.
- 매 change cost 의 minimize.

### 매 access modifier
- **public**: 매 anyone.
- **protected**: 매 subclass.
- **private**: 매 self only.
- **internal / package-private**: 매 module.

### 매 modern variant
- **TypeScript** `#privateField`.
- **Python** `_protected` (convention) + name mangling `__private`.
- **Rust** `pub(crate)`, `pub(super)`.
- **Java module system** (JPMS).
- **JavaScript** `class { #x }`.

### 매 응용
1. **Class**: 매 attribute hide.
2. **Module**: 매 internal export X.
3. **Microservice**: 매 DB private to service.
4. **API**: 매 implementation 의 versioned.
5. **Library**: 매 internal 의 unstable.

### 매 Law of Demeter
- 매 "talk to friends only".
- 매 a.b.c.d() = code smell.

## 💻 패턴

### 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; }
}

// 매 접근 시 SyntaxError
// account.#balance ❌
```

### 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
```

### 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 의 외부 접근 불가
    }
}
```

### Module-level (Python)
```python
# payments/__init__.py
from ._engine import charge  # 매 only public API
# 매 _engine internal 의 hide

# payments/_engine.py (underscore = internal)
def charge(amount):
    return _internal_call(amount)

def _internal_call(amount):
    # 매 hidden
    pass
```

### 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]] · [[Anaemic Domain Model]] · [[Dependency_Injection_(DI)|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 |
