8-1. 함수 옮기기
적용 시점
함수의 위치가 잘못된 경우
객체 A에서 호출되는 함수가 객체 B의 영향을 많이 받는 경우
다른 곳에서도 함수를 이용해야 하는 경우
절차
선택한 함수가 현재 컨텍스트에서 사용 중인 모든 프로그램 요소를 살펴본다. 이 요소들 중에도 함게 옮겨야 할 게 있는지 고민한다.
선택한 함수가 다형 메서드인지 확인한다.
선택한 함수를 타깃 컨텍스트로 복사한다. 타깃 함수가 타깃 객체로 잘 옮겨지도록 다듬는다.
정적 분석을 수행한다.
소스 컨텍스트에서 타깃 함수를 참조할 방법을 찾아 반영한다.
테스트한다.
소스 함수를 인라인할지 고민해본다.
예시
❌Before
const calculateTotalPrice = ({ productPrice, uidUser }) => {
const getDistanceFee = async () => {
const address = await userService.getAddress(uidUser);
// 거리 계산해서 요금 반환하는 로직
return distancefee;
}
const calculateRemoteFee = async () => {
const address = await userService.getAddress(uidUser);
// 격오지인지 확인하는 로직
return remoteFee;
}
const distanceFee = getDistance(uidUser);
const remoteFee = calculateRemoteFee(uidUser);
return distanceFee + remoteFee;
}
⭕After
const getDistanceFee = async (uidUser) => {
const address = await userService.getAddress(uidUser);
// 거리 계산해서 요금 반환하는 로직
return distancefee;
}
const calculateRemoteFee = async (uidUser) => {
const address = await userService.getAddress(uidUser);
// 격오지인지 확인하는 로직
return remoteFee;
}
const calculateTotalPrice = ({ productPrice, uidUser }) => {
const distanceFee = getDistance();
const remoteFee = calculateRemoteFee();
return distanceFee + remoteFee;
}
Last updated