liveBook · Manning

Extract function argument refactoring

As explained in Grokking Simplicity

A refactoring technique that converts information encoded implicitly in a function name or surrounding code into an explicit function argument.

Extract function argument refactoring makes an implicit argument explicit. Use it when similar functions differ because a value is hard-coded in the body and named in each function. section 10.1 section 10.4

Apply the refactoring in four direct steps:

  • Identify the value encoded in the function name. section 10.4
  • Add that value as an explicit function argument. section 10.1
  • Replace the hard-coded value in the body with the new argument. section 10.4
  • Update callers to pass the value explicitly. section 11.1

From named setters to a generic setter

Replace setPriceByName(), setQuantityByName(), setShippingByName(), and setTaxByName() with setFieldByName(cart, name, field, value). Field names such as 'price' and 'quantity' become first-class values: callers can pass, store, or collect them, while one implementation handles existing and future fields. section 10.4

function setFieldByName(cart, name, field, value) { #1 
    var item = cart[name];
    var newItem = objectSet(item, field, value);
    var newCart = objectSet(cart, name, newItem); #3
    return newCart;
}
 
cart = setFieldByName(cart, "shoe", 'price', 13);
cart = setFieldByName(cart, "shoe", 'quantity', 3);
cart = setFieldByName(cart, "shoe", 'shipping', 0);
cart = setFieldByName(cart, "shoe", 'tax', 2.34); #2

Compare the explicit field argument with the earlier family of field-specific setters. section 10.4

The same move generalizes nested updates: incrementSize(item) becomes incrementOption(item, option), then updateOption(item, option, modify). It can also expose custom worker behavior as a Queue argument, separating reusable control flow from task-specific work. section 14.10 section 16.6

How Grokking Simplicity covers it

How deep it goes
Explains the smell, four-step procedure, first-class values, nested applications, and runtime field validation.
Examples
Uses cart field setters, quantity and size incrementers, nested shirt options, reusable queues, and array operations.
What it assumes
Teaches first-class values from their definition rather than assuming prior knowledge of the concept.
What you can do after
Apply the refactoring to remove duplication, pass field names explicitly, generalize nested updates, and extract reusable callbacks.
How it connects
Connects code smells, first-class values, higher-order functions, callbacks, nested data, and functional iteration.

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.