liveBook · Manning

Replace body with callback

As explained in Grokking Simplicity

A refactoring technique that extracts unchanged before-and-after code into a function and supplies the varying body as a callback argument.

Replace body with callback removes duplication by separating a repeated before-and-after structure from the code that varies between them. The varying behavior becomes a function argument—a callback—so the surrounding function can be reused. section 10.1 section 10.15

Apply the refactoring in three steps:

  • Identify the before, body, and after sections. The before and after remain stable; the body changes. section 10.11
  • Extract the complete before-body-after structure into a function. section 10.1
  • Extract the body into a callback parameter and invoke it between the unchanged sections. section 11.1

Reusable array copying

Repeated copy-on-write functions make a copy, modify it, and return it. Extracting the modification produces: function withArrayCopy(array, modify) { var copy = array.slice(); modify(copy); return copy; } A setter can then call withArrayCopy(array, function(copy) { copy[idx] = value; }); The same helper supports pushing, removing elements, or sorting. section 11.3

Wrapping try/catch once

When many operations share identical error handling, pass the operation as a callback: function tryCatch(f, errorHandler) { try { return f(); } catch(error) { return errorHandler(error); } } A call such as tryCatch(sendEmail, logToSnapErrors) reuses the surrounding syntax while varying the operation. section 11.3 section 10.11

function arraySet(array, idx, value) {
    return withArrayCopy(array, function(copy) {
        copy[idx] = value;
    });
}
 
function withArrayCopy(array, modify) { #1
    var copy = array.slice();
    modify(copy);
    return copy;
}

Inspect the compact JavaScript transformation from a specialized array setter to a reusable copy helper with a modify callback. section 11.3

How Grokking Simplicity covers it

How deep it goes
Provides a three-step refactoring procedure and multiple JavaScript transformations, stopping short of formal language semantics.
Examples
Uses try/catch logging, array copying, conditional execution, forEach-style iteration, and asynchronous cart-total calculation.
What it assumes
Assumes basic functions and JavaScript syntax while teaching first-class functions, callbacks, and higher-order functions through examples.
What you can do after
Build reusable higher-order functions by extracting stable surroundings and passing changing behavior as callbacks.
How it connects
Connects callbacks with first-class functions, higher-order functions, code smells, copy-on-write, functional iteration, and asynchronous programming.

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.