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
Inspect the completed extraction: calc_total(cart) receives the cart explicitly and returns the computed total. section 4.9
