views:

117

answers:

3

So Meta Programming -- the idea that you can modify classes/objects at runtime, injecting new methods and properties. I know its good for framework development; been working with Grails, and that framework adds a bunch of methods to your classes at runtime. You have a name property on a User object, and bamm, you get a findByName method injected at runtime.

  1. Has my description completely described the concept?
  2. What else is it good for (specific examples) other than framework development?
+1  A: 

Meta programming is not only adding methods at runtime, it can also be automatically creating code at compile time. I.e. code generating code.

  • Web services (i.e. the methods are defined in the WSDL, and you want to use them as if they were real methods on an object)
  • Avoiding boilerplate code. For example, in Java you should use getters and setters, but these can be made automatically for most properties.
Sjoerd
i thought metaprogramming was specifically a runtime thing. Interesting. Good point about boiler plate code (Grails does this too). Anything else?
hvgotcodes
@hvgotcodes: Metaprogramming is mostly about compile-time; runtime uses are actually pretty rare in comparision to run-time usages. See f.e. C++ templates (which is kind of metaprogramming, even though not many people like to admit that): all programs that use STL... there are lots of them.
liori
+2  A: 

To me, meta-programming is "a program that writes programs".

Meta-programming is especially good for reuse, because it supports generalization: you can define a family of concepts that belong to a particular pattern. Then, through variability you can apply that concept in similar, but different scenarios.

The simplest example is Java's getters and setters as mentioned by @Sjoerd:

Both getter and setter follow a well-defined pattern: A getter returns a class member, and a setter sets a class member's value. Usually you build what it's called a template to allow application and reuse of that particular pattern. How a template works depends on the meta-programming/code generation approach being used.

If you want a getter or setter to behave in a slightly different way, you may add some parameters to your template. This is variability. For instance, if you want to add additional processing code when getting/setting, you may add a block of code as a variability parameter. Mixing custom code and generated code can be tricky. ABSE is currently the only MDSD approach that I know that natively supports custom code directly as a template parameter.

Rui Curado
A: 

Meta programming is not only use to add stuff to your codebase. It can also be used to describe the current code you're dealing with, without coupling your codebases. It can be quite useful in applications of "many to many relationships" such as the mediator pattern.

Alexandre Deschamps