핵심 내용

결합도는 모듈들이 서로 얼마나 강하게 의존하는지를 나타낸다. 응집도는 한 모듈 안의 요소들이 하나의 목적을 위해 얼마나 긴밀하게 협력하는지를 나타낸다.

1. 모듈이란

모듈은 프로그램을 이루는 구성 단위로, 정해진 책임을 맡아 기능을 제공한다.

프로그램의 큰 기능은 여러 하위 모듈이 각자 맡은 일을 하고 서로 협력해 완성한다. 이는 복잡한 문제를 작은 문제들로 나누어 해결한 다음, 결과를 합쳐 전체 문제를 푸는 방식과 같다.

문제를 나눌 때는 먼저 핵심 목적을 남기고 불필요한 세부 사항을 감추는 추상화를 한다.

예시
엔진을 자동차를 움직이는 동력을 제공하는 장치로 바라본다. 연료 연소나 냉각 같은 내부 세부 사항은 이 수준의 설명에서 다루지 않는다.

추상화한 문제는 다시 더 작은 문제로 나눌 수 있다. 각 문제를 맡아 해결하는 구성 단위가 모듈이다. 이 분해는 여러 단계로 이어질 수 있다. 다른 모듈을 조합해 더 큰 기능을 제공하는 모듈을 상위 모듈, 그 기능의 일부를 맡아 제공하는 모듈을 하위 모듈이라고 한다. 상위와 하위는 절대적인 구분이 아니라 바라보는 계층에 따라 달라진다.

graph TD
    Car[자동차 모듈]
    Engine[엔진 모듈]
    Transmission[변속기 모듈]
    Cooling[냉각 모듈]
    Fuel[연료 공급 모듈]
    Combustion[연소 모듈]

    Car -->|하위 모듈| Engine
    Car -->|하위 모듈| Transmission
    Engine -->|하위 모듈| Cooling
    Engine -->|하위 모듈| Fuel
    Engine -->|하위 모듈| Combustion

자동차 관점에서는 엔진이 하위 모듈이고, 엔진 내부를 살펴보면 냉각·연료 공급·연소 모듈을 아우르는 상위 모듈이 된다.

따라서 모듈은 추상화된 문제를 맡아 해결하고, 잘 정의된 인터페이스를 제공하며, 세부 구현을 캡슐화하는 소프트웨어의 구성 단위다.

2. 모듈의 범위

모듈은 잘 정의된 인터페이스를 통해 교체할 수 있어야 한다. 외부 상태를 직접 읽거나 변경하면 의존성이 인터페이스에 드러나지 않아, 구현을 독립적으로 교체하고 테스트하기 어려워진다. 부수효과가 있다는 이유만으로 모듈이 아닌 것은 아니다. 부수효과와 의존 대상을 인터페이스 뒤에 두고 관리할 수 있는지가 중요하다.

아래 두 함수는 같은 입력을 받아 같은 결과를 내는 계산 구현이다. 구현 방식은 다르지만 Product[]를 받아 number를 반환하는 인터페이스가 같으므로 서로 바꾸어 사용할 수 있다.

type Product = { id: number; price: number };

function makePayPrice(products: Product[]): number {
  return products.reduce((total, product) => total + product.price, 0);
}

function makePayPriceV2(products: Product[]): number {
  let total = 0;

  for (const product of products) {
    total += product.price;
  }

  return total;
}

반면 다음 함수는 매개변수에 없는 외부 변수 discounts를 직접 읽는다. 할인 규칙이나 데이터가 바뀌면 함수의 결과도 달라지지만, 호출부의 인터페이스에는 이 의존성이 나타나지 않는다.

type Discount = { productId: number; discountRate: number };

const discounts: Discount[] = [{ productId: 1, discountRate: 0.1 }];

function makePayPriceWithHiddenDependency(products: Product[]): number {
  return products.reduce((total, product) => {
    const discountRate = discounts
      .filter((discount) => discount.productId === product.id)
      .reduce((sum, discount) => sum + discount.discountRate, 0);

    return total + Math.max(product.price * (1 - discountRate), 0);
  }, 0);
}

discounts를 함수가 직접 참조하지 않고 생성 시점에 전달하면 의존성이 명시적이 된다. 팩토리는 할인 데이터가 반영된 계산 함수를 만들고, 반환된 함수는 앞의 예제와 같은 Product[] 입력 및 number 반환 인터페이스를 유지한다.

function createPayPriceCalculator(discounts: Discount[]) {
  return (products: Product[]): number => {
    return products.reduce((total, product) => {
      const discountRate = discounts
        .filter((discount) => discount.productId === product.id)
        .reduce((sum, discount) => sum + discount.discountRate, 0);

      return total + Math.max(product.price * (1 - discountRate), 0);
    }, 0);
  };
}

const makePayPrice = createPayPriceCalculator(discounts);
const totalPrice = makePayPrice(products);

할인 데이터가 어디서 전달되는지 생성 지점에서 확인할 수 있고, 테스트에서는 다른 목록을 주입해 결과를 제어할 수 있다. 반환된 함수의 인터페이스가 같다면 구현을 바꾸어도 사용하는 쪽은 그대로 둘 수 있다.

아래 그림에서 함수는 모듈 A와 B가 구현하는 인터페이스에 의존하지만, 동시에 모듈 A의 내부 정보도 직접 참조한다. 이 숨은 의존성 때문에 인터페이스가 같더라도 A를 B로 바꾸기 어렵다.

3. 결합도

결합도는 모듈 사이 의존성이 얼마나 강한지, 한 모듈의 변경이 다른 모듈의 수정으로 얼마나 쉽게 전파되는지를 나타낸다. 의존 관계의 개수만으로 결합도를 판단할 수는 없다. 호출부가 안정된 인터페이스에만 의존하면 구현을 교체하기 쉽지만, 내부 자료나 규칙까지 알아야 한다면 결합도가 높아진다.

graph LR
    Function[호출 함수]
    Interface[모듈 인터페이스]
    subgraph ModuleA[모듈 A]
        AImplementation[인터페이스 구현]
        AInternal[내부 정보]
    end
    ModuleB[모듈 B]

    AImplementation -->|구현| Interface
    ModuleB -->|구현| Interface
    Function -.->|의존| Interface
    Function -.->|직접 참조 · 숨은 의존성| AInternal
    Interface ~~~ AImplementation
    Interface ~~~ ModuleB

이 구조에서는 호출 함수가 인터페이스뿐 아니라 모듈 A의 내부 정보에도 의존한다. 따라서 같은 인터페이스를 구현한 모듈 B로 A를 교체하기 어렵다. 모듈 A의 인터페이스를 유지하더라도 호출 함수가 참조하는 내부 정보의 구조나 의미가 바뀌면 호출 함수도 함께 수정해야 한다.

인터페이스를 유지한 채 내부 구현을 바꿨는데도 외부 코드를 수정해야 한다면, 외부 코드가 내부 구현에 결합되어 있다는 신호다.

type Location = 'A' | 'B';
type Prescription = { activeIngredient: string };
type Medicine = { id: string; activeIngredient: string };
type Inventory = {
  findByIngredient: (ingredient: string) => Medicine[];
};

class DrugStore {
  constructor(
    private location: Location,
    private inventory: Inventory,
  ) {}

  prepareMedicine(prescription: Prescription): Medicine | undefined {
    const candidates = this.inventory.findByIngredient(prescription.activeIngredient);

    // A 지점은 같은 성분의 약 중 하나를 무작위로 선택한다.
    if (this.location === 'A') {
      const index = Math.floor(Math.random() * candidates.length);
      return candidates[index];
    }

    // B 지점은 재고 목록의 첫 번째 약을 선택한다.
    return candidates[0];
}

const drugStore = new DrugStore(location, inventory);
const medicine = drugStore.prepareMedicine(prescriptionForCold);

if (!medicine) return;
packageMedicine(medicine);

DrugStore는 지점에 따라 약을 선택하는 규칙이 다르다. 처음 예제에서는 호출부도 location을 확인해 동작을 나누므로, 지점별 규칙을 두 곳에서 알아야 한다. 호출부가 DrugStore 내부의 위치 규칙에 결합된 구조다.

위치별 규칙을 선택 함수로 분리하고 DrugStore 생성 시 주입하면, 호출부는 위치나 선택 방식을 알 필요가 없다.

type SelectMedicine = (candidates: Medicine[]) => Medicine | undefined;

const selectMedicineByLocation: Record<Location, SelectMedicine> = {
  A: (candidates) => {
    const index = Math.floor(Math.random() * candidates.length);
    return candidates[index];
  },
  B: (candidates) => candidates[0],
};

class DrugStore {
  constructor(
    private inventory: Inventory,
    private selectMedicine: SelectMedicine,
  ) {}

  prepareMedicine(prescription: Prescription): Medicine | undefined {
    const candidates = this.inventory.findByIngredient(prescription.activeIngredient);
    return this.selectMedicine(candidates);
  }
}

const drugStore = new DrugStore(inventory, selectMedicineByLocation[location]);
const medicine = drugStore.prepareMedicine(prescriptionForCold);

if (medicine) packageMedicine(medicine);

이제 지점별 선택 규칙은 조립하는 곳에서 한 번 정하고, 호출부는 prepareMedicine의 공개 인터페이스에만 의존한다. 선택 규칙을 바꿔도 호출부는 수정할 필요가 없다. 내부 세부 사항에 의존해 외부 코드를 수정해야 하는 상황이 결합도를 보여주는 신호다.

결합도를 파악할 수 있는 다른 방법으로는 인터페이스의 면적이 있다. 면적은 의존 대상이 공개하는 정보의 양을 의미한다.
만약 인터페이스 A가 B보다 더 많은 속성과 메서드를 공개한다면 인터페이스 A는 면적이 더 넓고, 결합도가 높을 가능성이 크다.
깊은 모듈은 내부 구현의 복잡도에 비해 인터페이스를 단순하게 유지하므로 제공하는 기능의 양에 비해 복잡한 인터페이스를 노출하는 얕은 모듈보다 결합도를 효과적으로 관리할 수 있다.

결합도를 파악할 수 있는 또 다른 방법은 의존하는 모듈의 개수다.

graph LR
    Order[주문 처리 모듈]
    User[사용자 모듈]
    Inventory[재고 모듈]
    Payment[결제 모듈]
    Coupon[쿠폰 모듈]

    Order -.-> User
    Order -.-> Inventory
    Order -.-> Payment
    Order -.-> Coupon

높은 결합도를 가진 모듈은 변경이 발생했을 때 영향을 받는 모듈이 많기 때문에 안정적으로 관리할 수 있도록 특히 신경써야 한다. 인터페이스를 작고 단순하게 유지함으로써 인터페이스를 변경할 가능성을 낮추고, 캡슐화를 통해 내부 구현의 변경이 외부에 영향을 주지 않게 해야한다.

4. 응집도

응집도는 모듈 안의 데이터와 동작이 하나의 목적을 위해 얼마나 긴밀하게 모여 있는지를 나타낸다. 응집도를 판단할 때는 기능의 이름만 보지 말고, 함께 바뀌는 이유가 있는지 살펴야 한다.

async function signup() {
  const id = (document.getElementById('id') as HTMLInputElement).value;
  const password = (document.getElementById('password') as HTMLInputElement).value;

  if (id === '' || id.length < 4) {
    alert('아이디를 입력해주세요.');
    return false;
  }

  if (password.length < 8) {
    alert('비밀번호는 8자 이상이어야 합니다.');
    return false;
  }

  const response = await fetch('/auth/sign-up', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ id, password }),
  });
  const result: { success: boolean } = await response.json();

  return response.ok && result.success;
}

이 함수는 회원가입이라는 기능을 완성한다는 관점에서는 한 목적을 가진다. 하지만 입력을 읽는 방법, 검증 규칙, 서버 통신은 서로 다른 이유로 바뀔 수 있다. 예를 들어 폼 구조가 바뀌거나 검증 정책이 바뀌거나 API 규약이 바뀌면 모두 이 함수를 수정해야 한다. 이 책임들을 각각의 변경 이유로 살펴보면 한 함수에 여러 관심사가 모여 있음을 알 수 있다.

각 동작을 별도 함수로 나누고 signup은 회원가입 흐름을 조합하게 만들 수 있다.

type SignupInput = { id: string; password: string };

function readSignupInput(): SignupInput {
  return {
    id: (document.getElementById('id') as HTMLInputElement).value,
    password: (document.getElementById('password') as HTMLInputElement).value,
  };
}

function isValidSignupInput({ id, password }: SignupInput): boolean {
  return id.length >= 4 && password.length >= 8;
}

async function sendSignupRequest(input: SignupInput): Promise<boolean> {
  const response = await fetch('/auth/sign-up', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(input),
  });
  const result: { success: boolean } = await response.json();

  return response.ok && result.success;
}

async function signup(): Promise<boolean> {
  const input = readSignupInput();
  if (!isValidSignupInput(input)) return false;

  return sendSignupRequest(input);
}

이제 입력 읽기, 검증, 서버 요청은 각자의 책임을 가진다. signup은 이 동작을 회원가입 흐름으로 조합한다. 응집도를 높인다고 모든 함수를 잘게 나누는 것은 아니다. 함께 바뀌는 책임은 모으고, 서로 다른 이유로 바뀌는 책임은 분리하는 것이 기준이다. 응집도가 높으면 관련 변경을 한곳에서 다루기 쉬워지지만, 실제 변경 영향은 모듈 사이 결합도에도 달려 있다.

5. 결합도와 응집도

응집도가 낮은 모듈은 서로 다른 이유로 바뀌는 책임을 한데 모아 둔다. 결합도가 높은 모듈은 다른 모듈의 세부 구현이나 숨은 상태를 알아야 동작한다. 두 문제는 함께 나타나기 쉽다.

아래 예제에서는 회원가입 페이지와 API, 라우터, 분석 모듈이 전역 상태를 공유한다. 페이지는 이 상태와 각 모듈의 세부 동작을 알고 있고, API와 라우터도 서로 다른 모듈 및 공유 상태에 기대고 있다. 폼 입력, 검증, 네트워크 요청, 이동, 분석이 여러 곳에 흩어져 있어 응집도는 낮고 결합도는 높다.

const signupState = { isSubmitting: false, userId: '' };

const tangledAnalytics = {
  track(eventName: string, userId = signupState.userId) {
    console.log(eventName, userId, tangledRouter.currentPath);
  },
};

const tangledRouter = {
  currentPath: '/',
  navigate(path: string) {
    if (!signupState.userId) return;
    this.currentPath = path;
    history.pushState({}, '', path);
  },
};

const tangledUserApi = {
  async create(input: SignupInput) {
    signupState.isSubmitting = true;
    const response = await fetch('/auth/sign-up', {
      method: 'POST',
      body: JSON.stringify(input),
    });
    const result: { success: boolean; userId?: string } = await response.json();

    if (result.success && result.userId) {
      signupState.userId = result.userId;
      tangledAnalytics.track('user_created');
    }

    signupState.isSubmitting = false;
    return result;
  },
};

async function signupPage() {
  const id = (document.getElementById('id') as HTMLInputElement).value;
  const password = (document.getElementById('password') as HTMLInputElement).value;

  if (signupState.isSubmitting || !isValidSignupInput({ id, password })) return;
  const result = await tangledUserApi.create({ id, password });
  if (!result.success) return;

  tangledRouter.navigate('/welcome');
  tangledAnalytics.track('signup_completed', signupState.userId);
}
graph LR
    SignupPage[회원가입 페이지]
    Form[DOM 폼]
    Validation[검증 규칙]
    API[사용자 API]
    Router[라우터]
    Analytics[분석 도구]
    State[공유 회원가입 상태]

    SignupPage -.-> Form
    SignupPage -.-> Validation
    SignupPage -.-> API
    SignupPage -.-> Router
    SignupPage -.-> Analytics
    SignupPage -.-> State
    API -.-> Analytics
    API -.-> State
    Router -.-> State
    Analytics -.-> Router

개선할 때는 회원가입 흐름을 조정하는 모듈과 각 책임을 분리하고, 공유 상태 대신 명시적인 반환값과 인터페이스로 결과를 전달한다. 페이지는 입력을 읽어 회원가입 흐름을 호출하고, API·라우터·분석 구현은 조립하는 곳에서 연결한다.

type SignupInput = { id: string; password: string };
type SignupResult = { success: boolean; userId?: string };

type SignupFlowDependencies = {
  validate: (input: SignupInput) => boolean;
  createUser: (input: SignupInput) => Promise<SignupResult>;
  navigate: (path: string) => void;
  track: (eventName: string, userId?: string) => void;
};

function createSignupFlow({ validate, createUser, navigate, track }: SignupFlowDependencies) {
  return async (input: SignupInput): Promise<SignupResult> => {
    if (!validate(input)) return { success: false };

    const result = await createUser(input);
    if (!result.success) return result;

    navigate('/welcome');
    track('signup_completed', result.userId);
    return result;
  };
}

const signup = createSignupFlow({
  validate: validateSignupInput,
  createUser: userRepository.create,
  navigate: appRouter.navigate,
  track: analyticsClient.track,
});

async function handleSignup(form: HTMLFormElement) {
  const data = new FormData(form);
  return signup({
    id: String(data.get('id') ?? ''),
    password: String(data.get('password') ?? ''),
  });
}
graph LR
    Page[회원가입 페이지]
    Form[폼 입력]
    Flow[회원가입 흐름]
    Validator[검증 인터페이스]
    UserService[사용자 생성 인터페이스]
    Navigator[이동 인터페이스]
    AnalyticsPort[분석 인터페이스]
    UserAPI[사용자 API 구현]
    Router[라우터 구현]
    Analytics[분석 도구 구현]

    Page -.->|읽기| Form
    Page -.->|호출| Flow
    Flow -.-> Validator
    Flow -.-> UserService
    Flow -.-> Navigator
    Flow -.-> AnalyticsPort
    UserAPI -.->|구현| UserService
    Router -.->|구현| Navigator
    Analytics -.->|구현| AnalyticsPort

개선한 구조에서는 각 모듈이 맡은 책임이 분명해져 응집도가 높아진다. 회원가입 흐름은 사용자 API·라우터·분석 도구의 내부 상태를 직접 읽지 않고, 명시된 인터페이스와 반환값을 사용한다. 구현을 교체해도 인터페이스가 유지되면 호출부의 수정이 줄어 결합도도 낮아진다.

로그처럼 여러 흐름에 공통으로 적용할 동작은 회원가입 로직마다 반복해서 넣지 않고, 함수형 데코레이터로 감쌀 수 있다. 아래 래퍼는 실행 전·성공·실패 로그를 남기며, 입력값은 기록하지 않는다.

type AsyncUseCase<Input, Output> = (input: Input) => Promise<Output>;
type Logger = {
  info: (event: string) => void;
  error: (event: string, error: unknown) => void;
};

function withLogging<Input, Output>(
  name: string,
  useCase: AsyncUseCase<Input, Output>,
  logger: Logger,
): AsyncUseCase<Input, Output> {
  return async (input) => {
    logger.info(`${name}.started`);

    try {
      const output = await useCase(input);
      logger.info(`${name}.completed`);
      return output;
    } catch (error) {
      logger.error(`${name}.failed`, error);
      throw error;
    }
  };
}

const signup = withLogging(
  'signup',
  createSignupFlow({
    validate: validateSignupInput,
    createUser: userRepository.create,
    navigate: appRouter.navigate,
    track: analyticsClient.track,
  }),
  logger,
);
graph LR
    Page[회원가입 페이지] -.-> Signup[로그가 적용된 회원가입 함수]
    Signup -.->|감싸서 실행| Logging[로그 데코레이터]
    Logging -.->|호출| Flow[회원가입 흐름]
    Logging -.-> LoggerPort[Logger 인터페이스]
    Logger[로그 구현] -.->|구현| LoggerPort

이 방식은 로그 처리를 회원가입 흐름 바깥에 두어 업무 로직의 응집도를 유지한다. 데코레이터는 로그 기록과 흐름 실행을 연결하므로, 로그 구현을 교체해도 회원가입 흐름을 수정할 필요가 없다.

6. 캡슐화, 결합도, 응집도의 관계

캡슐화는 같은 목적을 가진 상태와 행동을 하나의 단위로 묶고, 외부에는 필요한 인터페이스만 공개해 불필요한 정보는 숨기는 과정이다. 캡슐화를 잘 지키는 것이 높은 응집도와 낮은 결합도를 달성하는 가장 효과적인 방법 중 하나다.