DEV Community

Naomi Dennis
Naomi Dennis

Posted on

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.

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.

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.

Top comments (0)