💻 Programming

OOP

Object-Oriented Programming

Object-oriented programming. Encapsulation, inheritance, polymorphism, and abstraction are the core principles. Designs highly maintainable software through the SOLID principles.

📖 Detailed Explanation

OOP (Object-Oriented Programming) is a programming paradigm that models a program as a collection of objects. It is built on four core principles. Encapsulation bundles data and methods together and restricts external access. Inheritance lets a child class inherit the properties and methods of a parent class. Polymorphism provides various implementations through the same interface. Abstraction hides complex implementation and exposes only essential functionality.

The history of OOP goes back to the 1960s. Simula (1967), developed in Norway, was the first object-oriented language and introduced the concepts of classes and objects. Later, Smalltalk (1972), developed by Alan Kay at Xerox PARC, established the pure OOP philosophy that "everything is an object." Concepts such as message passing and dynamic typing developed in Smalltalk and influenced modern Python and Ruby. With the arrival of C++ (1983) and Java (1995), OOP became an industry standard.

The SOLID principles are five OOP design principles established by Robert C. Martin. SRP (Single Responsibility): a class should have only one responsibility. OCP (Open-Closed): open for extension, closed for modification. LSP (Liskov Substitution): a child class must be substitutable for its parent class. ISP (Interface Segregation): interfaces should be split into small, specific ones. DIP (Dependency Inversion): depend on abstractions, not on concrete implementations.

OOP vs FP (functional programming) are complementary rather than mutually exclusive. OOP is strong at modeling the real world by bundling state and behavior into objects. FP minimizes side effects through immutability and pure functions. Modern languages (Kotlin, Scala, TypeScript) mix the two paradigms. In AI/ML code, it is common to use FP for data pipelines and OOP for model architecture. Ultimately, it is important to choose the paradigm that fits the problem.

💻 Code Example

"""
OOP 핵심 개념 예제 - Python
캡슐화, 상속, 다형성, 추상화 + SOLID 원칙 적용
"""

from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import List, Protocol


# ===== 추상화 (Abstraction) =====
class PaymentProcessor(ABC):
    """결제 처리기 추상 클래스 - ISP 원칙 적용"""

    @abstractmethod
    def process_payment(self, amount: float) -> bool:
        """결제 처리 (구현 필수)"""
        pass

    @abstractmethod
    def refund(self, transaction_id: str) -> bool:
        """환불 처리"""
        pass


# ===== 캡슐화 (Encapsulation) =====
@dataclass
class Money:
    """금액을 캡슐화한 값 객체"""
    _amount: float
    _currency: str = "KRW"

    @property
    def amount(self) -> float:
        return self._amount

    def add(self, other: 'Money') -> 'Money':
        if self._currency != other._currency:
            raise ValueError("통화가 다릅니다")
        return Money(self._amount + other._amount, self._currency)

    def __str__(self) -> str:
        return f"{self._amount:,.0f} {self._currency}"


# ===== 상속 (Inheritance) + 다형성 (Polymorphism) =====
class CreditCardProcessor(PaymentProcessor):
    """신용카드 결제 - LSP 원칙 준수"""

    def __init__(self, api_key: str):
        self._api_key = api_key
        self._transactions: dict = {}

    def process_payment(self, amount: float) -> bool:
        # 실제로는 PG사 API 호출
        transaction_id = f"CC_{id(self)}"
        self._transactions[transaction_id] = amount
        print(f"[신용카드] {amount:,.0f}원 결제 완료")
        return True

    def refund(self, transaction_id: str) -> bool:
        if transaction_id in self._transactions:
            print(f"[신용카드] {transaction_id} 환불 완료")
            return True
        return False


class KakaoPayProcessor(PaymentProcessor):
    """카카오페이 결제 - 다형성 활용"""

    def process_payment(self, amount: float) -> bool:
        print(f"[카카오페이] {amount:,.0f}원 결제 완료")
        return True

    def refund(self, transaction_id: str) -> bool:
        print(f"[카카오페이] {transaction_id} 환불 완료")
        return True


# ===== DIP 원칙 - 추상화에 의존 =====
class OrderService:
    """주문 서비스 - DIP 원칙 적용 (구체 클래스가 아닌 추상화에 의존)"""

    def __init__(self, payment_processor: PaymentProcessor):
        # 구체 클래스가 아닌 추상 클래스에 의존
        self._processor = payment_processor

    def checkout(self, items: List[dict]) -> bool:
        total = sum(item['price'] * item['quantity'] for item in items)
        print(f"\n총 금액: {total:,.0f}원")
        return self._processor.process_payment(total)


# ===== SRP 원칙 - 단일 책임 =====
class OrderValidator:
    """주문 검증만 담당 - SRP 원칙"""

    @staticmethod
    def validate(items: List[dict]) -> bool:
        if not items:
            raise ValueError("주문 항목이 비어있습니다")
        for item in items:
            if item.get('quantity', 0) <= 0:
                raise ValueError("수량은 1 이상이어야 합니다")
        return True


# ===== 실행 예시 =====
if __name__ == "__main__":
    # 다형성 활용: 동일 인터페이스로 다양한 결제 수단 처리
    items = [
        {"name": "AI 강의", "price": 50000, "quantity": 1},
        {"name": "교재", "price": 30000, "quantity": 2}
    ]

    # 신용카드로 결제
    cc_processor = CreditCardProcessor(api_key="test_key")
    order_service = OrderService(cc_processor)
    order_service.checkout(items)

    # 카카오페이로 결제 (동일 코드, 다른 결제 수단)
    kakao_processor = KakaoPayProcessor()
    order_service = OrderService(kakao_processor)
    order_service.checkout(items)

🗣️ Examples of Practical Conversations

SOLID principles question in a technical interview

"The SOLID principle I consider most important is DIP. When you depend on abstractions rather than concrete classes, testing becomes easier, and even code with external dependencies, like a payment module, can be replaced with a Mock. I always receive dependencies through constructor injection and define the interface first before implementing."

Discussing design patterns in a code review

"This OrderService handles payment, sends notifications, and does logging too. That violates SRP. Split payment into PaymentProcessor and notifications into NotificationService, and OrderService only needs to coordinate them. Each class should have only one reason to change."

In an architecture design meeting

"Let's design this payment system with the Strategy pattern. We'll have a PaymentStrategy interface and create CreditCard, KakaoPay, and NaverPay implementations. When adding a new payment method, we just add a new class without modifying existing code, so it also satisfies OCP."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

⚠️
Avoid excessive inheritance (Fragile Base Class Problem)

As the inheritance hierarchy gets deeper, changing a parent class affects every child. Avoid inheritance deeper than three levels, and use inheritance only when the "is-a" relationship is certain. In most cases, composition is more flexible.

⚠️
Interface segregation (avoid Fat Interfaces)

Several small, specific interfaces are better than one huge interface. Don't make clients depend on methods they don't use. Separating a "payment" interface from a "refund" interface is the ISP principle.

⚠️
Favor Composition over Inheritance

This is a core principle of the GoF design patterns. Inheritance is fixed at compile time, but composition can be swapped at runtime. Instead of inheriting from Logger, hold a Logger as a field and delegate to it. Testing and maintenance become much easier.

🔗 Related Terms

📚 Learn More