DEV Community

Mashcuy Lab
Mashcuy Lab

Posted on

Refactoring #1

In this article we are summarizing the most interesting parts of:

  • Martin Fowler - Refactoring (2018) Chapter 6 "A First Set of Refactorings"

Extract variable


return order.quantity * order.itemPrice - Math.max(0, order.quantity - 500) * order.itemPrice * 0.05 + Math.min(order.quantity * order.itemPrice * 0.1, 100)
Enter fullscreen mode Exit fullscreen mode


const basePrice = order.quantity * order.itemPrice;
const quantityDiscount = Math.max(0, order.quantity - 500) * order.itemPrice * 0.05; 
const shipping = Math.min(basePrice * 0.1, 100);
return basePrice - quantityDiscount + shipping;
Enter fullscreen mode Exit fullscreen mode

Changing a parameter


function inNewEngland(aCustomer) {
   return ["MA", "CT", "ME", "VT", "NH", "RI"].includes(aCustomer.address.state);
}

const newEnglanders = someCustomers.filter(c => inNewEngland(c));
Enter fullscreen mode Exit fullscreen mode


function inNewEngland(stateCode) {
   return ["MA", "CT", "ME", "VT", "NH", "RI"].includes(stateCode);
}

const newEnglanders = someCustomers.filter(c => inNewEngland(c.address.state));
Enter fullscreen mode Exit fullscreen mode

Split Phase


const orderData = orderString.split(/\s+/);
const productPrice = priceList[orderData[0].split("-")[1]]; const orderPrice = parseInt(orderData[1]) * productPrice;
Enter fullscreen mode Exit fullscreen mode


const orderRecord = parseOrder(order);
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]; 
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)