28

Parameterize Function


Goal

Two near-identical functions that differ only in literal values combine into one with a parameter.

Before the refactoring
function tenPercentRaise(person)  { person.salary *= 1.10; }
function fivePercentRaise(person) { person.salary *= 1.05; }
After the refactoring
function raise(person, factor) { person.salary *= 1 + factor; }
Savings

One canonical implementation; new variations are new parameter values, not new functions.

Note

If the variations are conceptually different operations, one parameterized function will accumulate flags and special cases — keep them separate then.