Files
2nd/10_Wiki/Topic_Programming/DevOps_and_Security/Encapsulation-via-Access-Modifiers.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

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
Access Modifiers
Visibility Modifiers
Encapsulation
none A 0.95 applied
oop
encapsulation
access-modifier
language-design
2026-05-10 pending
language framework
TypeScript General

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, TS readonly, Java sealed, 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.

매 응용

  1. API 의 stable surface 의 maintain (semver).
  2. Library author 의 internal refactoring freedom.
  3. Test isolation (private — black-box test 의 강제).
  4. 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

🤖 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