d8a80f6272
이름만 다른(표기 변형) [[위키링크]]를 대상 문서의 canonical 제목으로 치환해 끊겼던 1,200개 링크를 연결. 제목/파일명 정규화 일치만 적용하고 별칭 매칭은 과병합 위험으로 제외(애매성 가드). 원본은 _link_reconcile_backup/ 에 백업. 도구: Datacollect/scripts/link_reconcile_apply.mjs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
6.8 KiB
6.8 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-via-access-modifie | Encapsulation via Access Modifiers | 10_Wiki/Topics | verified | self |
|
none | A | 0.95 | applied |
|
2026-05-10 | pending |
|
Encapsulation via Access Modifiers
매 한 줄
"매 internal state 의 hide + boundary 의 explicit". 1967 Simula 의 OOP 의 도입 후 매 Bertrand Meyer 의 "Design by Contract", Parnas 의 information hiding 원칙 의 codify — 2026 modern lang 는
public/private/protected의 보다, JS#private, Rust module visibility, TSreadonly, Javasealed, C#init-only 의 fine-grained capability 의 dominate.
매 핵심
매 Access modifier 의 종류 (lang 별)
- Java:
public,protected, package-private (default),private. - C#:
public,protected,internal,private,protected internal,private protected,file. - TypeScript:
public(default),protected,private,#private(true private — JS native). - Rust:
pub,pub(crate),pub(super),pub(in path), default private to module. - Python: convention only —
_underscore(protected),__double(name-mangled). - Kotlin:
public(default),internal(module),protected,private.
매 Encapsulation 의 layer
- Visibility: who can see.
- Mutability:
final,readonly,const,val. - Identity: opaque type, newtype.
- Invariant: setter validation, factory.
매 응용
- API 의 stable surface 의 maintain (semver).
- Library author 의 internal refactoring freedom.
- Test isolation (private — black-box test 의 강제).
- Security boundary (capability 의 leak 방지).
💻 패턴
TypeScript 의 #private (true private)
class BankAccount {
#balance = 0; // 매 runtime 의 private — TS `private` 의 erase 의 X
readonly id: string;
constructor(id: string) { this.id = id; }
deposit(amount: number) {
if (amount <= 0) throw new Error('positive only');
this.#balance += amount;
}
get balance() { return this.#balance; }
}
const a = new BankAccount('A1');
// a.#balance = 999; // SyntaxError 의 compile + runtime
Rust 의 module visibility
mod auth {
pub struct User {
pub name: String,
password_hash: String, // 매 module 외부 의 invisible
}
impl User {
pub fn new(name: &str, pw: &str) -> Self {
User { name: name.into(), password_hash: hash(pw) }
}
pub(crate) fn verify(&self, pw: &str) -> bool {
self.password_hash == hash(pw)
}
}
fn hash(s: &str) -> String { /* ... */ s.into() }
}
Java sealed + record
public sealed interface Shape permits Circle, Square, Triangle {}
public record Circle(double radius) implements Shape {
public Circle { // 매 compact constructor 의 invariant
if (radius < 0) throw new IllegalArgumentException();
}
}
// 매 exhaustive switch 의 enable
String describe(Shape s) {
return switch (s) {
case Circle c -> "circle r=" + c.radius();
case Square sq -> "square";
case Triangle t -> "tri";
};
}
C# init-only + required
public class Order
{
public required string Id { get; init; } // 매 set 의 only at init
public DateTime Created { get; init; } = DateTime.UtcNow;
private decimal _total;
public decimal Total
{
get => _total;
private set => _total = value >= 0 ? value :
throw new ArgumentException();
}
}
var o = new Order { Id = "ORD-1" }; // 매 valid
// o.Id = "X"; // 매 error: init-only
Python 의 convention + property
class Vault:
def __init__(self, secret):
self._secret = secret # 매 protected (convention)
self.__truly_hidden = "obfuscated" # 매 _Vault__truly_hidden
@property
def secret(self):
# 매 read-only 의 access
return f"***{self._secret[-2:]}"
v = Vault("p@ssword")
print(v.secret) # ***rd
# v.secret = "x" # AttributeError
Capability-based design (no class)
// 매 closure-based 의 information hiding
function makeCounter() {
let count = 0;
return {
inc: () => ++count,
get: () => count,
// 매 reset 의 reveal 안 하면 의 capability 의 absent
};
}
const c = makeCounter();
c.inc(); c.inc();
console.log(c.get()); // 2 — count 의 access 의 X
Friend / internal API (Kotlin)
// 매 internal 의 same module 만의 access
internal class IndexBuilder {
internal fun rebuild() { /* ... */ }
}
// 매 @PublishedApi 의 inline function 의 internal API 의 publish
@PublishedApi
internal fun secretImpl() = 42
inline fun publicWrapper() = secretImpl()
Newtype 의 opaque ID
pub struct UserId(u64); // 매 tuple struct 의 inner 의 private
impl UserId {
pub fn new(id: u64) -> Self { UserId(id) }
pub fn value(&self) -> u64 { self.0 }
}
// 매 raw u64 의 mistakenly UserId 로 의 X — type-safe boundary
fn get_user(id: UserId) { /* ... */ }
// get_user(123); // compile error
매 결정 기준
| 상황 | Approach |
|---|---|
| Library API | pub 의 minimal surface, internal 의 default |
| Domain model | private field + factory + invariant |
| DTO/value | record / data class / immutable |
| JS/TS browser code | #private (true private) 의 default |
| Cross-module refactoring | internal/pub(crate) 의 prefer |
기본값: most restrictive 의 default. 매 explicit 하 expand.
🔗 Graph
- 부모: Object-Oriented Programming (OOP) · Information Hiding
- 변형: Module System
- 응용: API Design · Library Design · Refactoring_Best_Practices
- Adjacent: Abstraction · SOLID
🤖 LLM 활용
언제: API surface review, accessor pattern 의 generate, visibility audit. 언제 X: language-specific subtle case (Kotlin internal mangling 등) 의 verify 필수.
❌ 안티패턴
- Public field: encapsulation 의 broken — invariant 의 enforce 의 X.
- Getter/setter for everything: encapsulation 의 illusion (Tell Don't Ask 위반).
- Reflection 의 private 의 bypass: test 의 implementation 의 lock.
- Java private 의 inner class: enclosing class 의 implicit access — confusion.
- TS
private의 trust: runtime 의 erase —#private사용.
🧪 검증 / 중복
- Verified (Bloch "Effective Java" Item 15, Parnas 1972 "Decomposition", JLS, ECMA-262).
- 신뢰도 A.
🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — TS/Rust/Java/C#/Kotlin/Python access patterns |