결합도와 응집도 추가 예제롤 살펴보자

기본형 (데이터 결합도)

class Bill {// 주차 요금 청구서
  모듈 (사용시간과 할인률을 인자로 받고 계산하여 주차요금 메소드를 호출)
    public static int getBillFee(int time, int discount) {
      double discountPercentage = discount / 100;
      // 메서드안에서 또 다른 메서드를 호출해 의존도가 있긴 하지만, 메서드에 단순 파라미터 데이터를 보내는 형태
      return Fee.calculateFee(time) * discountPercentage;
    }
}
class Fee {// 주차 요금 계산 모듈
  public static int calculateFee(int time) {
    int defaultMoney = 1000;
    return defaultMoney * time;
  }
}

public class Main {
  public static void main(String[] args) {
    Bill.getBillFee(2, 80); // 2시간 이용, 80% 할인
  }
}

스탬프 결합도

/ 이용기록 자료구조 형태
class Record {
  public int carNum;
  public int useTime
  private int fee

  Record(int carNum, int useTime) {
    this.carNum = carNum;
    this.useTime = useTime;
  }

  public void setFee(int fee) {
    this.fee += fee;
  }

  public int getFee(int fee) {
    return this.fee;
  }
}

괜찮은 것 같지만 문제는 Record 클래스를 수정할때 생기고,
Bill, Fee 두개의 클래스에서 Record를 사용하고 있는 점이다.

Record에 존재하는 userTimes을 min 단위로 수정한다면?
Bill, Fee 모두 수정해야 한다.

즉 유지보수의 공수가 더 커진다.

제어 결합도

다른 모둘이 논리적 흐름을 제아하는 경우.
캡슐화 원칙을 위배한다고 한다.

이젠 Bill 모듈에 있는 회원 정보를 넘겨주고
회원 여부로 분기를 Fee 모듈에서 판단하고 있다.

class User { ... } // 회원 정보 클래스

class Bill { // 주차 요금 청구서 모듈
  public static int getBillFee(int time) {
    double discountPercentage = discount / 100;
    User user1 = new User();
    // 인수값에 따라서 모듈 내부 로직의 처리가 달라지는 결합 형태
    return Fee.calculateFee(time, user.isJoin) * discountPercentage;
  }
}

class Fee { // 주차 요금 계산 모듈
  public static int calculateFee(int time, boolean isJoin) {
    int defaultMoney = 1000;
    // 회원 여부에 따라 주차요금을 계산하는 로직이 달라짐
    if(isJoin) {
    } else {
    // ...
    return defaultMoney * time - 400; // 회원 이면 400원 할인
    }
  }
}

이렇게 결합이 강할거면 모듈을 하나로 합치는게 낫다..
물론 응집도 문제가 발생하지만
그건 뒤에 나온다.

software-engineering 카테고리의 다른 글