Replace Temp with Query
What You'll Learn
You'll learn how to eliminate temporary variables by extracting their calculations into methods, making your code more testable and reusable.
The Core Idea
A temporary variable often stores the result of a calculation you use just once or twice within a method. While this seems convenient, it creates unnecessary clutter and hides reusable logic. Replace Temp with Query means taking that calculation, moving it into its own method (a "query"), and calling that method instead of using the temp variable.
Think of it like this: instead of writing down a phone number on a sticky note every time you need it, you save it in your contacts and retrieve it whenever necessary. The contacts app is your query method—always available, never cluttering your desk.
Why This Matters
Temporary variables are local to one method. If other methods need the same calculation, you'll duplicate code. By extracting the logic into a method:
- Other methods can reuse it without duplication
- You can test the calculation independently
- The original method becomes clearer, with less variable noise
- The calculation has a meaningful name that explains its purpose
When to Apply It
Use this refactoring when:
- A temporary variable holds a calculation that could be useful elsewhere
- The calculation is complex enough to deserve its own name
- The temp variable is making your method longer or harder to read
Avoid it when the calculation is extremely expensive and you genuinely need caching within a method (though even then, consider caching strategies at a higher level).
Key Takeaway: Replace temporary variables with query methods to make calculations reusable, testable, and self-documenting—reducing clutter and exposing hidden abstractions.