Refactoring code involves altering the structure of code to make it more understandable and maintainable without changing its observable behavior. One such strategy of refactoring is known as “Replace Temp with Query”.
What is Replace Temp with Query?
Replace Temp with Query is a refactoring technique that suggests the replacement of a local variable (temporary variable or temp) that holds the result of an expression with a method (query) that returns the result of the same expression. The essence of this refactoring is to remove the local variable and extract its creation logic into a separate method.
When To Use Replace Temp With Query?
Consider using Replace Temp with Query in the following scenarios:
- Complex calculation in a method: If a method contains complex calculations and the results are stored in temporary variables, it might be helpful to use this refactoring technique.
- Multiple references to a temporary variable: When the value of a temporary variable is referenced multiple times in a method, but not changed after its initial assignment,
Replace Temp with Querycan make the code more readable.
- Reduce side effects: Temporary variables can be a source of bugs, especially if their values are modified in the course of a method. By using a query method, you can reduce the potential for these sorts of side effects.
Examples of Replace Temp with Query
Let’s consider the following Java code:
Here, the temporary variables
discount can be replaced with queries:
Let’s see a Python example:
We can refactor this Python code by replacing temp variables with query methods:
Replace Temp with Query refactoring allows you to make your code clearer and easier to understand, as well as more robust against potential bugs. It replaces temporary variables with query methods,