
함수형 프로그래밍에서 액션, 계산과 같이 함수를 개발하거나 리팩토링할 때 다음과 같은 사항들을 통해서 재사용성을 높일 수 있다.
함수는 입력과 출력이 항상 존재한다.
let total = 0;
const addToTotal = (value: number) => {
console.log(value)
total += value;
return total
}
명시적 입력 : 함수의 인자 → value
명시적 출력 : 함수의 return → return total
암묵적 입력 : 직접 함수에 주입한 값이 아닌 전역 변수 → total
암묵적 출력 : 함수로 부터 직접 내보내는 값이 아닌 함수 내부에서 정보를 출력 → console.log
함수형 프로그래밍에서 함수 내부에 존재하는 암묵적 입/출력을 없애면, 계산(순수 함수)를 만들 수 있다. 암묵적 입력은 함수의 인자로 바꾸고, 암묵적 출력의 경우 함수의 return 값에 포함하도록 한다.
💡 리팩터링(refactoring) : 이전의 코드는 수정하면서 결과값을 그대로 유지하는 유지보수 방법
함수의 입출력을 조절함으로서 기존의 액션 단위로 존재하는 함수를 일부 계산(순수함수)로 리팩토링 할 수 있고, 이 과정을 통해서 함수의 재사용성과 테스트 용이성을 향상 시킬 수 있다.
function update_tax_dom() {
set_tax_dom(shopping_cart_total * 0.1);
}
Solve
// Calculate
function calculate_tax(cost) {
return cost * 0.1
}
// Action
function update_tax_dom(total_cost) {
const tax_cost = calculate_tax(total_cost);
set_tax_dom(tax_cost);
}
function update_shipping_icons() {
var buy_buttons = get_buy_buttons_dom();
for(var i = 0; i < buy_buttons.length; i++) {
var button = buy_buttons[i];
var item = button.item;
if (item.price + shopping_cart_total >= 20) {
button.show_free_shipping_icon();
} else {
button.hide_free_shipping_icon();
}
}
}
Solve
// Calculate
function is_total_cost_overload(item_price, total_cost) {
return item_price + total_cost >= 20
}
// Action
function update_shipping_icons() {
var buy_buttons = get_buy_buttons_dom();
for(var i = 0; i < buy_buttons.length; i++) {
var button = buy_buttons[i];
var item = button.item;
if (is_total_cost_overload(item.price, shopping_cart_total)) {
button.show_free_shipping_icon();
} else {
button.hide_free_shipping_icon();
}
}
}
좋은 글 감사합니다.