6-11. 단계 쪼개기
적용 시점
서로 다른 두 대상을 한꺼번에 다루는 코드를 발견하는 경우
입력이 처리 로직에 적합하지 않은 경우
덩치가 큰 소프트웨어인 경우
여러 단계로 분리하면 좋을 코드를 찾은 경우
절차
두 번째 단계에 해당하는 코드를 독립 함수로 추출
테스트
중간 데이터 구조를 만들어서 앞에서 추출한 함수의 인수로 추가
테스트
추출한 두 번째 단계 함수의 매개변수를 하나씩 검토함. 그중 첫 번째 단계에서 사용되는 것은 중간 데이터 구조로 옮김
첫 번째 단계 코드를 함수로 추출하면서 중간 데이터 구조를 반환하도록 만듬
예시
❌Before
const priceOrder = (product, quantity, shippingMethod) => {
const basePrice = product.basePrice * quantity;
const discount = Math.max(quantity - product.discountThreshold, 0
* product.basePrice * product.discountRate;
const shppingPerCost = (basePrice > shippingMethod.discountThreshold)
? shippingMethod.discountedFee : shippingMethod.feePerCase;
const price = basePrice - discount + shippingCost;
return price;
}
⭕After
const applyShipping = (priceData, shippingMethod) => {
const shippingPerCase = priceData.basePrice > shippingMethod.discountThreshold ?
shippingMethod.discountFee : shippingMethod.feePerCase;
const shippingCost = priceData.quantity * shippingPerCase;
return priceData.basePrice - priceData.discount + shippingcost;
}
const calculatePricingData = (product, quantity) => {
const baseprice = product.basePrice * quantity;
const discount = Math.max(quantity - product.discountThreshold, 0 )
* product.basePrice * product.discountRate;
return { basePrice, discount, quantity };
}
const priceOrder = (product, quantity, shippingMethod) => {
const priceData = calculatePricingData(product, quantity);
return applyShipping(priceData, ShippingMethod);
}
Last updated