Refactoring: Refactorings/Substitute Algorithm
Jump to navigation
Jump to search
Replace a confusing algorithm with one that is clearer and easier to understand
Mechanics
- Prepare alternative algorithm
- Run new algorithm against tests
- Compare results against existing algorithm
- Replace old algorithm body with new
Example
Before
def found_friends(people)
friends = []
people.each do |person|
if person == "Don"
friends << "Don"
end
if person == "John"
friends << "John"
end
if person == "Kent"
friends << "Kent"
end
end
return friends
end
After
def found_friends(people)
people.select do |person|
%w(Don John Kent).include? person
end
end