DEV Community

Naomi Dennis
Naomi Dennis

Posted on

1 1

Favorite Refactoring Techniques: Combine Functions Into Transform

When multiple functions have related behavior that acts on an object together, they can combine into a single function to transform an object. Behavior is the main way to determine of multiple functions should be combined. Let's look at an example.

Say, we have the following functions that calculates the total price at a restaurant.

loyaltyPoints = 50
price = new ShopItem(100)
total = calculateDiscount(price, loyaltyPoints)
total = calculateTip(price)
total = calculateSalesTax(price)

The calculation functions all relate to determining the total. Because we would need to call calculateDiscount whenever we call calculateSalesTax or calculateTip to get an accurate total; we should consolidate these calls into a single function.

myLoyaltyPoints = 50
itemPrice = new ShopItem(100)
total = calculateTotal(itemPrice, myLoyaltyPoints)
function calculateTotal(price, loyaltyPoints) {
return calculateDiscount(price, loyaltyPoints) + calculateTip(price) + calculateSalesTax(price)
}

Another way of determining the relationship between functions, is to look at its input, output and name. All calculate functions accept a number and return a number. Based on the semantic meaning of calculating the discount, sales tax and tip, we can determine these methods will likely, only, be called together. After this, we can peek into the functions and get a better idea of its behavior. In our example, each calculation function is returning a changed price.

Thus, we create a brand new function that combines all calculations and returns a transformed price.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay