Sunday, October 30, 2011

Refactoring Ruby Code

Since I've been working on this MadLibs generator, I've been through a couple of refactorings. Friday night, I got the code hammered out but I ended up with this:

MadLib Generator, first version

It works, sure, but it's ugly. A ton of gets.chomp()'s, and there's obviously a better way to do it. Still, my plan was to hack it out as best I knew how, identify problems with it, and then rework the code.

So here's my second attempt:

MadLib generator, first refactoring

Not bad! I've gotten rid of all the gets.chomp() commands in favor of loops that will collect the correct number of nouns, verbs, adjectives and so forth. I also got rid of the prompt method - it's a hold over from the dungeon games I've been working on and I felt it was unnecessary. I was pretty proud of this, but my friend Eli thought it could be refined further, suggesting I try to Objectify the code. I'm a bit puzzled by this. What does this mean?

At any rate, I took another look and here's what I've got now:

MadLib generator, second refactoring

In this iteration, I cleaned up what's being collected a bit, and took out the definitions for popping words out of the arrays. I realized I could just call the .pop method directly by defining the array as an instance variable. This way, I was able to shorten the code by several lines by adding a character to each variable. Pretty good trade off, if you ask me!

I also redefined each array after calling a .reverse method on it. Since I'm using .pop to pull words out of the array to place in the Mad Lib, this will keep the words in the same order the user entered them.

Things are going pretty well. I feel proud that I'm anticipating problems and finding solutions for them now. Also, I should've been using Gists for a long time now.