During my last AirPair with Adam Cuppy. He shared with me how to DRY up my events_controller page. There were quite a few methods that contained identical commands, and thankfully he walked me through my first refactor, sharing the principles of both when and how to remove code duplication. Today I’m going to attempt to refactor my venues_controller!
Lets start by taking a look at my venues_controller code before any changes are made, how many redundancies can you spot?
I spot four lines of code that look exactly the same. Lines 20, 24, 28 and 38 all contain the line
@venue = Venue.find(params[:id]). The way the code is written right now, if you or I needed to make changes to how we locate venue id’s we would have to change each of the four lines. And thats no good! Redundancies like this elementary example, are at least part of the reason people write code in the first place.
So now that we have located some redundant code, lets extract these lines of repetitive madness out so that we only have it written once.
I’ll start by creating a method with restricted access so that outside code cannot interact with it.
Heres what that could look like:
Above, we created a method containing a conditional that wraps our line of code from the four lines from the first example. The condition is making sure that their is actually a venue object and
params([:venue_id] is a way for us to check our database for the object by its index. In other words the
:venue_id is what we’re using to locate @venue.
Now that we have this handy method created we can delete all of those lines of code that look the same, and replace them with our new
Notice that we just took the repeated line of code and wrapped it with a private method
find_venue(id). From there the refactor is simple. We just assign the method to our instance variable like so:
@event = find_venue(parames[:id])
We add the
params[:id] to represent that we are looking to find the represented object’s ID through the http params hash.
And there you have it! A first refactor, removing duplicated code.
We could do the right thing here and finish with a swift push to Github.
Remember the steps?
0. Since we’re not starting a new app theres no need for
git status – Lets us know where we are currently in Git
git add . – Adds all untracked files to the staging area for commit.
git commit -m "Refactor venues_controller" – Takes a snapshot of our code that we can refer back to.
git push origin master – Delivers our modified code to our remote repository inside of github.
Check out my AirPair with Adam!