From "Refactoring"
🎧 Listen to Summary
Free 10-min PreviewStrategies for Managing Temporary Variables
Key Insight
Temporary variables often contribute to long, complex routines by creating numerous locally scoped names that complicate code extraction and overall comprehension. Consequently, a key refactoring strategy involves minimizing or eliminating them. One approach is 'Replace Temp with Query,' where the right-hand side of a variable assignment is extracted into its own function (e.g., `playFor(aPerformance)`), allowing the original variable to be inlined where it's used.
This means direct calls to the new function replace references to the temporary variable throughout the code. Subsequently, the now-redundant parameter for the temporary variable can be removed from functions like `amountFor` using 'Change Function Declaration,' as the necessary value can be computed on demand within the function. This simplification reduces the number of arguments passed around, making the code cleaner.
Similarly, accumulator variables, like `totalAmount` or `volumeCredits`, which are built up over loop iterations, can be managed. This typically involves using 'Split Loop' to separate their accumulation logic, then 'Slide Statements' to move their declarations closer to their respective loops. Finally, 'Extract Function' is applied to the accumulation logic to create a dedicated function (e.g., `totalVolumeCredits()`), followed by 'Inline Variable' to replace the temporary accumulator variable with direct calls to this new function, further streamlining the main routine.
📚 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.