Files
2nd/10_Wiki/Topics/AI_and_ML/Encapsulation-and-Information-Hiding.md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +09:00

6.7 KiB

id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
id title category status canonical_id aliases duplicate_of source_trust_level confidence_score verification_status tags raw_sources last_reinforced github_commit tech_stack
wiki-2026-0508-encapsulation-and-information-hi Encapsulation and Information Hiding 10_Wiki/Topics verified self
encapsulation
information hiding
Parnas
abstraction
modular design
none A 0.98 applied
oop
software-design
encapsulation
modularity
parnas
abstraction
2026-05-10 pending
language applicable_to
TypeScript / Python / Java
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

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)

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

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)

# 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

// 매 ❌ 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

// 매 ❌ 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)

// 매 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

// 매 ❌
order.customer.address.street;

// 매 ✅
order.shippingStreet();  // 매 method 의 ask, 매 reach 의 X

Java module (JPMS)

// module-info.java
module com.acme.payments {
  exports com.acme.payments.api;
  // 매 com.acme.payments.internal 매 not exported
}

Encapsulation check (lint rule)

// 매 ESLint 의 internal package 의 cross-module import 의 forbid
{
  rules: {
    'import/no-internal-modules': ['error', { forbid: ['*/internal/**'] }],
  },
}

Encapsulate state (React)

// 매 ❌ prop drilling internal
<Inner config={config.internal.deep.path} />

// 매 ✅ hide
function useFeatureConfig() {
  return useContext(ConfigContext);
}

Test through interface only

// 매 ❌ 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

🤖 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