JavaScript에서의 함수 조인트: AOP 기반 실행 훅 구현

함수형 프로그래밍 환경에서 코드의 관심사 분리(SoC)는 유지보수성과 재사용성을 높이는 핵심 원칙이다. Java의 Spring AOP처럼 엄격한 프레임워크 없이도, JavaScript는 고차 함수와 프로토타입 기반 확장을 통해 유연한 실행 시점 훅(hook)을 구현할 수 있다. 이 방식은 로깅, 성능 측정, 권한 검사, 에러 복구 등 반복적 부가 로직을 기존 함수에 ‘삽입’하지 않고, 외부에서 조합해 적용할 수 있게 한다.

핵심 아이디어: 조인트 포인트와 어드바이스

  • 조인트 포인트(Joint Point): 함수 호출 자체 — 특정 메서드나 콜백이 실행되는 순간.
  • 어드바이스(Advice): 그 시점에 주입할 동작 — before, after, around 형태로 분류 가능.
  • 비침투성: 원본 함수의 본문은 전혀 수정되지 않으며, 런타임에 동적으로 조합된다.

기본 구현: 체인 가능한 훅 메서드

다음은 Function.prototype에 확장된 두 가지 훅 메서드를 정의한 예시다. 각각은 새로운 함수를 반환하며, 원본 함수를 감싸는 클로저 형태로 동작한다.

Function.prototype.enhanceBefore = function (preAction) {
  const original = this;
  return function (...args) {
    preAction.apply(this, args);
    return original.apply(this, args);
  };
};

Function.prototype.enhanceAfter = function (postAction) {
  const original = this;
  return function (...args) {
    const result = original.apply(this, args);
    postAction.apply(this, args);
    return result;
  };
};

사용 예시: 성능 측정 및 상태 로깅

아래는 간단한 계산 함수에 훅을 연결해 실행 전후 동작을 추가하는 방법이다.

const compute = () => {
  console.log('계산 중...');
  return Math.random() * 100;
};

const loggedCompute = compute
  .enhanceBefore(() => console.time('실행 시간'))
  .enhanceAfter(() => console.timeEnd('실행 시간'));

loggedCompute(); // → "계산 중...", 콘솔에 타이머 결과 출력

고급 기능: 조건부 실행 차단

어드바이스가 false를 반환하면 연쇄 실행을 중단하도록 개선할 수 있다. 이를 통해 인증 체크나 입력 유효성 검사 같은 사전 조건을 자연스럽게 삽입할 수 있다.

Function.prototype.enhanceGuard = function (guard) {
  const original = this;
  return function (...args) {
    if (guard.apply(this, args) === false) {
      console.warn('실행 차단됨 — 가드 조건 실패');
      return;
    }
    return original.apply(this, args);
  };
};

const securedAction = () => console.log('보안 작업 실행');

securedAction
  .enhanceGuard(() => {
    const token = localStorage.getItem('authToken');
    return !!token; // 토큰 존재 여부에 따라 허용/차단
  })
  .enhanceAfter(() => console.log('작업 완료'));

주의사항

  • this 바인딩을 보존하려면 화살표 함수 대신 일반 함수를 사용해야 하며, apply 또는 call로 명시적으로 전달해야 한다.
  • 여러 훅을 체인할 경우, before → original → after 순서는 보장되지만, before().after()와 after().before()는 동일한 최종 결과를 낸다 — 단, 반환 값이나 부작용 발생 시점은 다를 수 있다.
  • 프로덕션에서는 Function.prototype 확장을 피하고, 독립된 유틸리티 함수(wrapWithBefore, wrapWithAfter)로 대체하는 것이 더 안전하다.

태그: JavaScript AOP higher-order-functions function-composition web-performance

10월 28일 09:16에 게시됨