Dynamic Method Definition

Flatiron School / 11 December 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 learn more about him here, or 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…

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?

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

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.

Here's Where to Start Flatiron School Prework Previous Post Roll Your Own OpenStruct Class Next Post