Refactoring: Refactorings/Introduce Explaining Variable
Jump to navigation
Jump to search
Use a variable name to explain a complicated expression
Mechanics
- Assign a temporary variable to the result of part of the complex expression
- Replace the result part of the expression with the value of the temp
- Note: If the result part of the expression is repeated, you can replace the repeats one at a time
- Test
- Repeat for other parts of the expression
Example
Before
def price
# price is base price - quantity discount + shipping
return @quantity * @item_price - [0, @quantity - 500].max * @item_price * 0.05 + [@quantity * @item_price * 0.1, 100.0].min
end
After
Note: Could also use Extract Method to turn base_price, quantity_discount, and shipping into function calls
def price
base_price = @quantity * @item_price
quantity_discount = [0, @quantity - 500].max * @item_price * 0.05
shipping = [base_price * 0.1, 100.0].min
return base_price - quantity_discount + shipping
end
Using Move Method Instead
(This is Fowler's preferred solution)
def price
base_price - quantity_discount + shipping
end
def base_price
@quantity * @item_price
end
def quantity_discount
[0, @quantity - 500].max * @item_price * 0.05
end
def shipping
[base_price * 0.1, 100.0].min
end