Refactoring: Refactorings/Split Temporary Variable
Jump to navigation
Jump to search
Temporary variable is assigned, used, then reassigned for another purpose.
Mechanics
- Change name of temporary variable at its first assignment
- If later assignments are of form i = i + expression, temp variable is "collecting" (addition, concatenation, stream, add to collection)
- Change all references to the temporary variable up to its second assignment
- Test
- Repeat in stages as necessary
Example
Before
def distance_traveled(time)
acc = @primary_force / @mass # First assignment
primary_time = [time, @delay].min
result = 0.5 * acc * primary_time * primary_time
secondary_time = time - @delay
if secondary_time > 0
primary_vel = acc * delay
acc = (@primary_force + @secondary_force) / @mass # Second assignment
result += primary_vel * secondary_time + 5 * acc * secondary_time * secondary_time
end
result
end
After
def distance_traveled(time)
primary_acc = @primary_force / @mass
primary_time = [time, @delay].min
result = 0.5 * primary_acc * primary_time * primary_time
secondary_time = time - @delay
if secondary_time > 0
primary_vel = primary_acc * delay
secondary_acc = (@primary_force + @secondary_force) / @mass
result += primary_vel * secondary_time + 5 * secondary_acc * secondary_time * secondary_time
end
result
end