liveBook · Manning

Extract subroutine

As explained in Grokking Simplicity

A refactoring technique that moves a block of code into a separately named callable function and replaces the original block with a call to that function.

Extract subroutine is a refactoring technique: move a code block into a separately named function, then replace the original block with a call. The operation keeps behavior working while giving the extracted operation a clear name. section 4.9

Apply the technique incrementally:

  • Choose a coherent block, create and name a function, paste the block into its body, and call it from the original location. section 4.10
  • Identify implicit inputs and outputs: global reads are inputs, while global assignments or mutable-array changes are outputs. section 4.9 section 4.10
  • Convert implicit inputs into arguments and outputs into return values, assigning the returned result where the original global value was updated. section 4.9

From cart action to calculation

A cart-total loop can move from calc_cart_total() into calc_total(). Replacing the global update with a local total and return value, then passing shopping_cart as an argument, separates calculation from the surrounding action. section 4.9

function calc_cart_total() {

    shopping_cart_total = calc_total(shopping_cart); #1

    set_cart_total_dom();

    update_shipping_icons();

    update_tax_dom();
}
     
function calc_total(cart) {
    var total = 0;
    for(var i = 0; i < cart.length; i++) { #2
        var item = cart[i];
        total += item.price;
    }
    return total;
}

Inspect the completed extraction: calc_total(cart) receives the cart explicitly and returns the computed total. section 4.9

How Grokking Simplicity covers it

How deep it goes
Explains extraction step by step, then descends into implicit inputs, outputs, arguments, return values, and mutable data.
Examples
Uses shopping-cart totals, item insertion, tax calculation, and free-shipping eligibility as extraction examples.
What it assumes
Assumes basic functions and global variables, while defining implicit inputs and outputs through concrete JavaScript examples.
What you can do after
Apply it to expose code responsibilities and make data flow explicit through named functions, arguments, and return values.
How it connects
Connects refactoring with actions, calculations, global state, implicit inputs and outputs, arguments, return values, and immutability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Simplicity. The section links point to the parts of the book it draws on.