Files
2nd/10_Wiki/Topics/Programming & Language/객체 지향 프로그래밍 (Object-Oriented Programming).md
T
2026-05-10 22:08:15 +09:00

196 lines
6.1 KiB
Markdown

---
id: wiki-2026-0508-객체-지향-프로그래밍-object-oriented-prog
title: 객체 지향 프로그래밍 (Object-Oriented Programming)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [OOP, Object-Oriented Programming, 객체지향]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [oop, encapsulation, polymorphism, paradigm]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: Java/TS/Python
framework: agnostic
---
# 객체 지향 프로그래밍 (Object-Oriented Programming)
## 매 한 줄
> **"매 state + behavior 를 object 로 묶어 message passing 으로 협력시키는 패러다임"**. Smalltalk (1972) → C++/Java → 매 modern composition-over-inheritance + interface-driven 으로 진화. 매 2026 의 OOP 는 functional core + OO shell 의 hybrid 가 dominant.
## 매 핵심
### 매 4 기둥
- **Encapsulation**: state 의 hide + 매 invariant 의 보호.
- **Abstraction**: 매 interface 만 노출 — implementation hide.
- **Inheritance**: 매 sub-class 의 reuse — 매 fragile base class 위험.
- **Polymorphism**: subtype / parametric / ad-hoc — 매 substitutability.
### 매 modern OOP 의 best practice
- **Composition > Inheritance**: 매 has-a >> is-a.
- **Program to interface**: 매 concrete type 의 dependency X.
- **SOLID**: SRP / OCP / LSP / ISP / DIP.
- **Immutable by default**: record / data class / value object.
### 매 응용
1. UI framework (React class — but hooks shifted toward functional).
2. Game engine (Unity GameObject / Component).
3. ORM entity (JPA / SQLAlchemy / Active Record).
4. GUI (Swing, Qt, AppKit).
## 💻 패턴
### Encapsulation + invariant
```java
public class Account {
private long balanceCents; // private = hidden
public void deposit(long cents) {
if (cents <= 0) throw new IllegalArgumentException();
this.balanceCents += cents;
}
public long getBalanceCents() { return balanceCents; }
// 매 setter 없음 — invariant 보호
}
```
### Polymorphism (interface)
```typescript
interface PaymentMethod {
charge(amountCents: number): Promise<TxResult>;
}
class StripeCard implements PaymentMethod {
async charge(c: number) { /* stripe sdk */ return { ok: true }; }
}
class Paypal implements PaymentMethod {
async charge(c: number) { /* paypal sdk */ return { ok: true }; }
}
async function checkout(pm: PaymentMethod, total: number) {
return pm.charge(total); // 매 same call, different impl
}
```
### Composition over Inheritance
```typescript
// ❌ Inheritance hell
// class FlyingFish extends Fish, Bird {} — multiple inheritance 문제
// ✅ Composition
interface Swim { swim(): void }
interface Fly { fly(): void }
class Fish implements Swim { swim() { console.log("swim"); } }
class Bird implements Fly { fly() { console.log("fly"); } }
class FlyingFish implements Swim, Fly {
private swimmer = new Fish();
private flyer = new Bird();
swim() { this.swimmer.swim(); }
fly() { this.flyer.fly(); }
}
```
### Strategy Pattern
```python
from typing import Protocol
class SortStrategy(Protocol):
def sort(self, data: list[int]) -> list[int]: ...
class QuickSort:
def sort(self, data): return sorted(data)
class BubbleSort:
def sort(self, data):
d = data[:]
for i in range(len(d)):
for j in range(len(d)-i-1):
if d[j] > d[j+1]: d[j], d[j+1] = d[j+1], d[j]
return d
class Sorter:
def __init__(self, strategy: SortStrategy):
self.strategy = strategy
def run(self, data):
return self.strategy.sort(data)
```
### Dependency Injection
```java
@Service
class OrderService {
private final OrderRepo repo;
private final PaymentGateway gateway;
public OrderService(OrderRepo r, PaymentGateway g) { // constructor inject
this.repo = r; this.gateway = g;
}
}
```
### Immutable Value Object (Java record)
```java
public record Money(long cents, String currency) {
public Money {
if (cents < 0) throw new IllegalArgumentException();
}
public Money add(Money other) {
if (!currency.equals(other.currency)) throw new IllegalArgumentException();
return new Money(cents + other.cents, currency);
}
}
```
### Sealed Hierarchy (Java 17+, Kotlin, Scala)
```java
public sealed interface Shape permits Circle, Square, Triangle {}
public record Circle(double r) implements Shape {}
public record Square(double s) implements Shape {}
public record Triangle(double a, double b, double c) implements Shape {}
double area(Shape s) {
return switch (s) { // exhaustive
case Circle c -> Math.PI * c.r() * c.r();
case Square q -> q.s() * q.s();
case Triangle t -> { /* heron */ yield 0; }
};
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 stateful entity (User, Order) | OOP class + invariant |
| 매 stateless transformation | functional / pure function |
| 매 plugin / extensibility | interface + DI |
| 매 data-only | record / dataclass |
| 매 algorithm dispatch | strategy / sealed + switch |
**기본값**: 매 immutable record + composition + interface + constructor DI. 매 deep inheritance 의 X.
## 🔗 Graph
- 부모: [[Programming Paradigms]]
- 변형: [[Functional Programming]] · [[Procedural Programming]] · [[Actor Model]]
- 응용: [[Design Patterns]] · [[SOLID]]
- Adjacent: [[Domain-Driven Design]] · [[Type Systems]] · [[Encapsulation]]
## 🤖 LLM 활용
**언제**: class design review, SOLID 위반 발견, refactor toward composition.
**언제 X**: 매 simple data transformation script — function 으로 충분.
## ❌ 안티패턴
- **God Object**: 1000+ method 의 single class.
- **Yo-yo Inheritance**: 매 6 단 deep — 매 행위 추적 불가.
- **Anemic Object**: getter/setter 만, behavior 누락.
- **Setter explosion**: 매 invariant 의 무력화.
- **Tight coupling to concrete class**: 매 testability X.
## 🧪 검증 / 중복
- Verified (Gamma et al. *GoF Design Patterns* 1994, Martin *Clean Architecture* 2017).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 4 기둥 + composition + sealed hierarchy + DI |