Refactoring: Refactorings/Replace Temp with Query
Jump to navigation
Jump to search
Temporary value variable used to store result of an expression; chances are that expression is used elsewhere. Temps create longer methods.
See also: Split Temporary Variable, Separate Query from Modifier
Mechanics
- Extract right-hand side of assignment into a method
- Note: Mark method as private at first; easier to relax protection than swim through tons of public methods
- Ensure extrated method is free of side effects (i.e. doesn't modify any object). Use Separate Query from Modifier
- Test
- Inline Temp on the temporary variable
Example
Before
def price
base_price = @quantity * @item_price
if base_price > 1000
discount_factor * 0.95
else
discount_factor * 0.98
end
base_price * discount_factor
end
After
def price
base_price * discount_factor
end
def discount_factor
base_price > 1000 ? 0.95 : 0.98
end
def base_price
@quantity * @item_price
end