In this article we are summarizing the most interesting parts of:
Martin Fowler – Refactoring (2018) Chapter 6 “A First Set of Refactorings”
Extract variable
❌
✅
const quantityDiscount = Math.max(0, order.quantity – 500) * order.itemPrice * 0.05;
const shipping = Math.min(basePrice * 0.1, 100);
return basePrice – quantityDiscount + shipping;
Changing a parameter
❌
return [“MA“, “CT“, “ME“, “VT“, “NH“, “RI“].includes(aCustomer.address.state);
}
const newEnglanders = someCustomers.filter(c => inNewEngland(c));
✅
return [“MA“, “CT“, “ME“, “VT“, “NH“, “RI“].includes(stateCode);
}
const newEnglanders = someCustomers.filter(c => inNewEngland(c.address.state));
Split Phase
❌
const productPrice = priceList[orderData[0].split(“–“)[1]]; const orderPrice = parseInt(orderData[1]) * productPrice;
✅
const orderPrice = price(orderRecord, priceList);
function parseOrder(aString) {
const values = aString.split(/s+/);
return ({
productID: values[0].split(“–“)[1],
quantity: parseInt(values[1]),
});
}
function price(order, priceList) {
return order.quantity * priceList[order.productID];
}