Search

 Case 1: 기본 분리 패턴

생성일
2025/09/07 11:23
태그

Pattern: 계산 추출

문제: 액션 함수 안에 비즈니스 로직이 섞여 있음
해결: 순수 계산 로직을 별도 함수로 추출
// ❌ Before: 액션과 계산이 섞임 async function processOrder(orderId) { const order = await fetchOrder(orderId) // 액션 // 계산 로직이 액션 안에 섞임 let total = 0 for (const item of order.items) { total += item.price * item.quantity } if (total > 100) { total = total * 0.9 // 10% 할인 } await updateOrder(orderId, { total }) // 액션 }
JavaScript
복사
// ✅ After function processOrder(orderId) { const order = await fetchOrder(orderId) const totalPrice = getTotalPrice(order) const discounts = getDiscounts(totalPrice, [ threshold10Off, // coupon3000원 (룰 추가) ]) updateOrder(orderId, { total: totalPrice - discounts }) } const getTotalPrice = (orders) => { return sumBy(orders, order => order.price * order.quantity) } export const getDiscounts = (subtotal, rules) => { const total = sumBy(rules, rule => rule(subtotal)) // 총액보다 할인액이 커지지 않도록 안전 장치 clamp(number, lower, upper) return clamp(total 0, subtotal); }; const threshold10Off = (subtotal) => { if (subtotal > 100) { return Math.floor(subtotal * 0.10); } return 0; };
TypeScript
복사