This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Just a question about the complexity of metaprogramming.
As Metaprogramming can be an incredible way to produce a piece of code (elegant, concise...), it can also be very difficult to understand by young developpers.
We know that not every developers will read the Ruby Metaprogramming book because they don't think they need to.
So how to know where to use metaprogramming and when not ?
My question is a bit vague, I am looking for your impression on the subject.
Like any other abstraction tool, use metaprogramming when the problem you're trying to solve is one you have to solve repeatably, and the cost/benefit tradeoff is weighed in favor of "benefit". And remember that metaprogramming doesn't need to be done, or even well-understood, by people that *use* it. After all--how many people use attr_accessor without even knowing what it is, that it's a method that creates new methods, and so on?
Whoever *does* do the metaprogramming *should* understand it, how to debug it, how Ruby finds methods to run, and so on.
Joined: Mar 08, 2006
I understand your point of view. attr_accessor is a good example of metaprogramming behind the scene.
And, code should not be leveled by the worst people on the team :-)
David, you have a very good point here. I'd also add that metaprogramming is like any other technique - difficult at first, and then it becomes just another tool. Then you select your tools based on the usual questions: how obvious is this code for me and my teammates? Is a method_missing() this more elegant than just defining two similar methods here? What happens if I have to change this later? And so on.
Like most good things, metaprogramming can be overused (or abused). However, I don't think that overusing metaprogramming is worse than overusing most other coding practices. Maybe the "meta" prefix just makes it sound scary. Well-written metaprogramming code is supposed to be more readable than the equivalent "regular" code, not more obscure.
Admittedly, there are a few techniques that can bite you real bad - like reckless monkeypatching of classes. That happens when you change existing classes, for example by redefining their methods. This is a slippery path. In the book I talk at length about this and how to avoid pitfalls (in a word: testing!).
Paolo Perrotta, Europe
Author of Metaprogramming Ruby