Dynamic Method Definition

Posted by Flatiron School  /  December 11, 2012

The following is a guest post by Adam Jonas and originally appeared on his blog. Adam is currently a student a The Flatiron School. You can follow him on twitter here.

As a beginner, when I run into a problem my first instinct is to power through and simply find a way to get it done– the brute force method. This means that I am rarely going to write good code during the first attempt. Once it is working however, I of course have the opportunity to return later and make it better. As Kent Beck says,

make it work, make it right, make it fast.

Refactoring is about making it right by changing the internal structure without changing the external behavior.

Refactoring: Ruby Edition has lots of great examples and methods for refactoring code. Inspired by the book, I gave a presentation on the subject last week. My example of Dynamic Method Definition was the clear winner based on the feedback from the audience so I’ll outline it below…

One of the most prominent clues that code needs refactoring is duplication…

Blog post image: tumblr_me4fztVCbX1rtan47.png

Enter Metaprogramming…

Metaprogramming is:

A program which modifies or generates other programs.

Instead of writing out each individual method, why don’t we use the power of Dynamic Method Definition to write these three methods for us?

Blog post image: tumblr_me4g05VVlw1rtan47.png

There is a lot going on here so let’s take a closer look.

Blog post image: tumblr_me4g0k1nMH1rtan47.png

Pretty slick huh?

This use of dynamic dispatching isn’t about semantics and code clarity (although it improves the code in both areas), use of this method is about maintainability. As we expand our list of attributes, we simply need to add the new parameter to repo_params. Easy peasy.

Refactoring: Ruby Edition should be required reading for anyone to graduate from the ‘beginner’ stage. Dynamic method definition is one of about 203,234,984 things that the book will teach you. Go read it.