PHpullh
학습 라이브러리/Java/불변 설계와 함수형 패턴

JAVA · 함수형/Stream

불변 설계와 함수형 패턴

불변 데이터 구조와 with 패턴으로 상태 변경을 안전하게 처리합니다.

함수형/Stream중급불변with패턴record함수형

핵심 설명

불변 데이터 구조와 with 패턴으로 상태 변경을 안전하게 처리합니다.

Java code

import java.util.*;

public class ImmutableDesign {
    // 불변 record + with 패턴
    record Account(String id, String owner, long balance) {
        Account deposit(long amount) {
            return new Account(id, owner, balance + amount);
        }
        Account withdraw(long amount) {
            if (amount > balance) {
                throw new IllegalStateException("잔액 부족");
            }
            return new Account(id, owner, balance - amount);
        }
        Account withOwner(String newOwner) {
            return new Account(id, newOwner, balance);
        }
    }

    // 불변 컬렉션 래퍼
    record ImmutableStack<T>(List<T> elements) {
        ImmutableStack() { this(List.of()); }

        ImmutableStack<T> push(T item) {
            var newList = new ArrayList<>(elements);
            newList.add(item);
            return new ImmutableStack<>(List.copyOf(newList));
        }

        T peek() { return elements.get(elements.size() - 1); }

        ImmutableStack<T> pop() {
            return new ImmutableStack<>(
                List.copyOf(elements.subList(0, elements.size() - 1)));
        }
    }

    public static void main(String[] args) {
        Account acc = new Account("A001", "홍길동", 10000);
        Account acc2 = acc.deposit(5000).withdraw(3000);
        System.out.println(acc.balance());  // 10000 (원본 불변)
        System.out.println(acc2.balance()); // 12000
    }
}

학습 팁

with 패턴은 record의 한 필드만 변경한 새 인스턴스를 반환합니다. JDK에서 공식 with 표현식이 논의 중입니다.

주의할 점

불변 컬렉션을 매번 복사하면 성능이 떨어질 수 있습니다. 대량 데이터에는 Vavr의 영속적(persistent) 자료구조를 고려하세요.

자주 묻는 질문

불변 설계와 함수형 패턴란 무엇인가요?

불변 데이터 구조와 with 패턴으로 상태 변경을 안전하게 처리합니다.

불변 설계와 함수형 패턴 학습 시 주의할 점은 무엇인가요?

불변 컬렉션을 매번 복사하면 성능이 떨어질 수 있습니다. 대량 데이터에는 Vavr의 영속적(persistent) 자료구조를 고려하세요.