본문 바로가기
Java

Lazy 로 쿼리를 날리고 싶다면?

by 성건희 2023. 9. 12.
반응형

문제

aService 로직을 실행하고, 실행 환경이 release 환경이라면 bService 로직을 추가로 실행하는 코드가 있다.

public void run(Model model) {
  model.addAttribute("play1", aService.play());
  boolean isRelease = DeployUtils.isRelease();
  if (isRelease) {
    model.addAttribute("play2", bService.play());
  }
}

문제는 이 코드가 대략 10 군데 정도의 Controller 에서 사용되고 있어 중복처럼 보였다.
중복을 제거하기 위해 BaseController 를 만들고, 해당 코드를 설계했다.


BaseController

public void add(Model model, Play play1, Play play2) {
  model.addAttribute("play1", play1);
  boolean isRelease = DeployUtils.isRelease();
  if (isRelease) {
    model.addAttribute("play2", play2);
  }
}

사용 Controller

public void run(Model model) {
  add(model, aService.play(), bService.play());
}

위와 같이 하면 해결된 것 같지만, 문제는 release 환경이 아닌데도 파라미터로 넘길때 bService.play() 로직이 실행된다는 것이다.
만약 release 환경이 아니라면 불필요한 쿼리/로직이 실행되는 것이다.
해결 방법이 없을까?

해결

함수형 인터페이스 인 Supplier<T> 를 사용하면 된다.
Supplier 는 추상 메서드 get() 을 통해 Lazy Evaluation 이 가능해지기 때문이다.
위 로직을 아래처럼 수정해보자.


BaseController

public void add(Model model, Supplier<Play> play1, Supplier<Play> play2) {
  model.addAttribute("play1", play1.get());
  boolean isRelease = DeployUtils.isRelease();
  if (isRelease) {
    model.addAttribute("play2", play2.get());
  }
}

사용 Controller

public void run(Model model) {
  add(model, () -> aService.play(), () -> bService.play());
}

참고

반응형

댓글