[개발자_객체지향_디자인패턴] 의존

박상준·2024년 8월 10일
0

의존성?

  • 한 객체가 다른 객체를 사용하는 관계를 말한다.
  • 자동차가 엔진을 사용하는 경우 , 자동차는 엔진에 의존한다고 말할 수 있다.

코드에서 의존성

public class FlowController {
    // fileName 필드 초기화 코드 생략
    public void process() {
        FileDataReader reader = new FileDataReader(fileName); // 객체 생성
        byte[] plainBytes = reader.read(); // 메서드 호출

        ByteEncryptor encryptor = new ByteEncryptor(); // 객체 생성
        byte[] encryptedBytes = encryptor.encrypt(plainBytes); // 메서드 호출

        FileDataWriter writer = new FileDataWriter(); // 객체 생성
        writer.write(encryptedBytes); // 메서드 호출
    }
}
  • 위 코드에서 객체생성과 메서드 호출부가 일렬로 서있다.
  • 혹시 차이점이 보이는가?
  • 바로..

의존성의 구현방법

  1. 파라미터를 통한 의존성 구현

    public void process(ByteEncryptor encryptor) {
        // 내부에서 encryptor를 사용할 가능성이 높다.
    }
    • 해당 방식은 매개변수에 아예 사용될 객체를 던져버리는 방식이다.
    • FileDataWriter 의 생성자가 변경되면 FlowController 도 변경되어야 한다.
    • 만약 FileDataWriter 의 매개변수가 변경된 경우
    public class FlowController {
        // outFileName 필드 초기화 위한 코드 추가 발생
        public void process() {
            // ... 다른 코드 생략 ...
            
            // FileDataWriter writer = new FileDataWriter(); 기존 코드
            FileDataWriter writer = new FileDataWriter(outFileName); // 변경 발생
            writer.write(encryptedBytes);
        }
    }
    • FileDataWriter 변경하나가 다른 곳까지 전파되는 경우, 이는 의존 관계 설계가 순환된어서 안좋은 케이스라고 볼 수 있다.

    • 이러한 순환을 막기위해
      • SOLID 중에 하나인 DIP 가 등장한다.
        • (Dependency Inversion Principle) 로서 의존 역전 원칙이라고 한다.

의존의 양면성

  • 의존성이 양방향으로 영향을 미칠 가능성이 있습니다
public class Authenticator {
    public boolean authenticate(String id, String password) {
        Member m = findMemberById(id);
        if (m == null) return false;
        return m.equalPassword(password);
    }
}

public class AuthenticationHandler {
    public void handleRequest(String inputId, String inputPassword) {
        Authenticator auth = new Authenticator();
        if (auth.authenticate(inputId, inputPassword)) {
            // 아이디/암호 일치할 때의 처리
        } else {
            // 아이디/암호 일치하지 않을 때의 처리
        }
    }
}
  • AuthenticationHandler 에서는 Authenticator 를 사용한다
    • 이것을 의존 한다고 표현한다.
    • AuthenticationHandler 가 제대로 동작하려면 Authenticator 가 필요하다.
  • 만약 해당 상황에서 새로운 요구사항이 들어오면..
    • 로그이 실패시 아이디가 잘못되었는지, 비밀번호가 잘못되었는지 구분해서 로그를 남겨야하는 경우
  • 코드 변경
    • 해당 요구사항을 만족시키기 위하여 코드 이렇게 변경해야함..

      public class Authenticator {
          public void authenticate(String id, String password) {
              Member m = findMemberById(id);
              if (m == null) throw new MemberNotFoundException();
              if (!m.equalPassword(password)) throw new InvalidPasswordException();
          }
      }
      
      public class AuthenticationHandler {
          public void handleRequest(String inputId, String inputPassword) {
              Authenticator auth = new Authenticator();
              try {
                  auth.authenticate(inputId, inputPassword);
                  // 아이디/암호가 일치하는 경우의 처리
              } catch(MemberNotFoundException ex) {
                  // 아이디가 잘못된 경우의 처리
              } catch(InvalidPasswordException ex) {
                  // 암호가 잘못된 경우의 처리
              }
          }
      }
    • Authenticator 클래스가 변경되었다.

      • boolean 반환대신 예외가 발생함
    • AuthenticationHandler 가 변경됨

      • 예외 처리가 추가됨.
    • 하나의 변경점으로.. 의존성이 양방향으로 영향을 미칠 수 있다는 것을 보여준다.

profile
이전 블로그 : https://oth3410.tistory.com/

0개의 댓글