Hello and happy Monday!
This week I’ll be resuming my review of Refactoring: Ruby Edition.
As we grow as programmers there will be times where we figure out easier ways to perform the same action. When this is the case, we should take time out to replace our older, more complicated code, and use our new found understanding to replace the old with our new, clearer way to accomplish the same goal.
Before we get into our brief example for today, here’s a peak at the mechanics to this refactoring pattern.
- Prepare our alternative algorithm
- Run this new algorithm against our tests, and if they pass then we’re done
- If our test results aren’t the same then we can use our old algorithm to debug our new one
I like how the book’s example illustrates this:
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 friends end
def found_friends(people) people.select do |person| %w(Don John Kent).include?(person) end end
In addition to taking time out to replace our complex algorithm with something clearer, sometimes we may want to also change our algorithm to do something slightly different than before. In these cases it’s easier on us to substitute our algorithm first into something easier for the change we want to make.
We should also ensure that we have decomposed the method as much as we can.
This pattern reminds me of some great instruction about fixing my tic-tac-toe algorithm that I received from Marek Publicewicz.
IMO this is a good example of both clarity and debugging improvements to an algorithm I was working on at the time.