From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewParameterize Function
Key Insight
When multiple functions perform analogous logical operations but vary only by specific literal values, redundancy can be eliminated by consolidating them into a single, more generalized function. This unified function accepts parameters to handle the differing values, thereby increasing its utility and making it applicable across a wider array of contexts with diverse inputs. This refactoring enhances code reusability and maintainability by centralizing common logic.
The process involves selecting one of the similar functions and modifying its declaration to incorporate parameters for each literal value that distinguishes it from its counterparts. Subsequently, every call site that previously invoked this function must be updated to pass the appropriate literal value as an argument to the newly added parameter. After this, the body of the function is revised to utilize these new parameters instead of hardcoded literal values, with incremental testing performed after each modification to ensure correctness.
Following these steps, each remaining similar function call is replaced with a call to the newly parameterized function, with individual tests conducted after each replacement. A straightforward illustration involves `tenPercentRaise(aPerson)` and `fivePercentRaise(aPerson)`, which can be abstracted into a single `raise(aPerson, factor)` function. A more intricate scenario is seen in functions like `bottomBand`, `middleBand`, and `topBand` for calculating charges within different usage ranges. These can be refactored into a single `withinBand(usage, bottom, top)` function, allowing a `baseCharge` calculation to use expressions like `withinBand(usage, 0, 100) * 0.03`, `withinBand(usage, 100, 200) * 0.05`, and `withinBand(usage, 200, Infinity) * 0.07`.
📚 Continue Your Learning Journey — No Payment Required
Access the complete Refactoring summary with audio narration, key takeaways, and actionable insights from Martin Fowler, Kent Beck.