liveBook · Manning

Refactoring

As explained in Grokking Simplicity

The systematic restructuring of existing code without changing its externally observable behavior.

Refactoring is the systematic restructuring of existing code while keeping its externally observable behavior unchanged. It makes code easier to test, reuse, maintain, and change safely. section 4.0 section 4.9

A practical refactoring starts with a working function and separates its responsibilities. Extract a calculation, identify its inputs and outputs, make implicit data explicit, and leave actions such as global updates or DOM changes at the boundary. section 4.0 section 4.9

Useful refactoring moves include:

  • Extract a subroutine, then convert global reads into arguments and global writes into return values. section 4.9
  • Spot a code smell when a changing value appears in a function name; add that value as an explicit argument and update callers. section 10.1 section 10.3
  • Replace changing code bodies with callbacks when the surrounding before-and-after structure is shared. section 10.1
  • Rewrite loops from their behavior or from structural clues: map commonly produces one result per element, while reduce combines elements. section 13.6
  • Prefer small steps: make data, operate on whole arrays, and split callbacks when they perform more than one job. section 13.10 section 13.8

Extracting a shopping-cart calculation

A function that calculates a total, writes a global shopping_cart_total, and updates the DOM can first extract calc_total(). Then calc_total() can accumulate in a local variable, return the total, and accept shopping_cart as cart. The outer function assigns the result and continues its action work. The calculation is now easier to reuse and test without the global cart. section 4.9

How Grokking Simplicity covers it

How deep it goes
Works through extraction, explicit inputs and outputs, code smells, callbacks, loop rewrites, and small-step decomposition.
Examples
Demonstrates shopping-cart totals, duplicated field setters, nested loops, array windows, callbacks, and functional map and reduce chains.
What it assumes
Assumes familiarity with existing functions and JavaScript loops while teaching refactoring, code smells, implicit arguments, and callbacks explicitly.
What you can do after
Apply it via incremental transformations that expose data flow, remove duplication, replace loops, and reduce bug-prone mutable state.
How it connects
Connects refactoring with code smells, first-class functions, higher-order functions, functional tools, testing, and global mutable variables.

Also explained in

Compare how 22 books explain refactoring →

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.