Dynamic Method Definition
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 […]
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…
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.
Disclaimer: The information in this blog is current as of 11 December 2012. Current policies, offerings, procedures, and programs may differ. For up-to-date information visit FlatironSchool.com.
Posted by Flatiron School / December 11, 2012
Learn to Code Python: Free Lesson for Beginners
Flatiron School Welcomes Peter Barth as CEO
“As we navigate a dynamic and complex tech talent landscape, Flatiron School’s mission – to enable the pursuit of a better life through education – is more vital than ever.”