Refactoring: Refactorings/Remove Assignments to Parameters
Jump to navigation
Jump to search
When in the method body, the code modifies the parameter variables passed into it to become another object:
Suppose foo is a parameter passed into a method. Somewhere in the code we say foo = another_object
Mechanics
- Create a temporary variable for the parameter
- Replace all parameter references after the assignment to the temporary variable
- Change assignment to assign to temporary variable
- Test
Example
Before
def discount(input_val, quantity, year_to_date)
input_val -= 2 if input_val > 50
input_val -= 1 if quantity > 100
input_val -= 4 if year_to_date > 10000
input_val
After
def discount(input_val, quantity, year_to_date)
result = input_val
result -= 2 if input_val > 50
result -= 1 if quantity > 100
result -= 4 if year_to_date > 10000
result
Note: Ruby always passes parameters by value, so internal modification within method is not reflected in outer scope