Skip to main content

What is metaprogramming?

The word metaprogramming keeps coming up everywhere in stuff I read nowadays. Even though I sort of knew what it meant I wasn't really sure. So I decided to ask the question 'what exactly is metaprogramming' on SO.

I got some really nice answers and links to articles. I have written this blog post as an effort to summarize what I have learned and to be able to share it with others who might be interested.

According to Wikipedia

''
Metaprogramming is the writing of computer programs that write or manipulate other programs (or themselves) as their data, or that do part of the work at compile time that would otherwise be done at runtime. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually, or it gives programs greater flexibility to efficiently handle new situations without recompilation."

The compiler is the simplest example of a metaprogram. It takes as input, code in some language, and creates code for another language. An example of metaprogramming in Java, is the use of generics. Here is a blog post I wrote (although for a different reason) some time back to show a simple example of how the compiler transforms Java code which has generics.

In languages like C and C++, metaprogramming can be done by the preprocessor.

In the Groovy programming language, there are two types of metaprogramming techniques: compile time metaprogramming, and runtime metaprogramming.

In compile time metaprogramming, Groovy allows us to hook into the compilation process at various stages, and modify the Abstract Syntax Tree which the compiler works on. (If you are interested, here is an Eclipse plugin to visualize the AST of a Java program)

An example of compile time metaprogramming is the use of the @Singleton annotation in Groovy. Whenever, we implement a Singleton, we always create a private constructor and a static method which gives us an instance of the Singleton. If we have several Singleton classes in our software, we have to implement this pattern for all of them. Using the @Singleton annotation gives us pattern reuse through AST transformations.

Let's say I want to create a Singleton class called MySingleton. In Groovy I can create it as follows without having to write a single line of plumbing code.


@Singleton class MySingleton {
//implementation of the class
}


During the compilation phase, some custom code will be invoked which will add the private constructor and a static instance() method to the class. Isn't this great? I think AST transformations can take reuse to a totally new level

Runtime metaprogramming can be done by using the Groovy MetaClass or more specifically the MetaObjectProtocol. Using the MetaClass, we can:
  • Add methods to objects at runtime
  • Determine if an object responds to a message or contains a property
  • Respond to calls made on non-existent methods
  • Respond to queries made on non-existent properties
Various builders in Groovy such as the MarkupBuilder and the SwingBuilder use the MetaObjectProtocol to achieve their magic. Here is some very simple code which uses SwingBuilder to create a simple GUI.


def swing = new SwingBuilder()
def gui = swing.frame(title:'GroovyTwitterClient',
size:[600,400],
defaultCloseOperation:WindowConstants.EXIT_ON_CLOSE) {
scrollPane {
tabbedPane = widget(new JTabbedPane())
}
}


What you see in the code above is a very simple DSL to create Swing GUI's. The code creates a JFrame, set's it's title, size, and defaultCloseOperation. Then it creates a JScrollPane and puts it in the JFrame. Finally it creates a JTabbedPane and puts it in the JScrollPane. If you look at the code carefully, you will realize that we call the method 'frame' on an instance of SwingBuilder and give it certain parameters and a closure. In the closure we call a method 'scrollPane' and give it another closure, and so on. Here each method call actually results in the creation of a Swing component. The parameters of the call are the properties which will be set on that component and the closure represents the component(s) to be added to that component. However, the most interesting thins is yet to come. The SwingBuilder class does not even have methods called 'frame', 'scollPane', and 'tabbedPane'. So then how does this work? The SwingBuilder class overrides invokeMethod(...) which is invoked for every single method call. So, when the 'frame' method is invoked on SwingBuilder, it goes through the MetaObjectProtocol to invokeMethod(...) . Here the call is intercepted and a swing component is created based on the name of the method.

This was just an overview. There is much more to metaprogramming and I will write more about it in future posts.

Comments

Popular posts from this blog

Commenting your code

Comments are an integral part of any program, even though they do not contribute to the logic. Appropriate comments add to the maintainability of a software. I have heard developers complain about not remembering the logic of some code they wrote a few months back. Can you imagine how difficult it can be to understand programs written by others, when we sometimes find it hard to understand our own code. It is a nightmare to maintain programs that are not appropriately commented. Java classes should contain comments at various levels. There are two types of comments; implementation comments and documentation comments. Implementation comments usually explain design desicisions, or a particularly intricate peice of code. If you find the need to make a lot of implementation comments, then it may signal overly complex code. Documentation comments usually describe the API of a program, they are meant for developers who are going to use your classes. All classes, methods and variables ...

Inheritance vs. composition depending on how much is same and how much differs

I am reading the excellent Django book right now. In the 4th chapter on Django templates , there is an example of includes and inheritance in Django templates. Without going into details about Django templates, the include is very similar to composition where we can include the text of another template for evaluation. Inheritance in Django templates works in a way similar to object inheritance. Django templates can specify certain blocks which can be redefined in subtemplates. The subtemplates use the rest of the parent template as is. Now we have all learned that inheritance is used when we have a is-a relationship between classes, and composition is used when we have a contains-a relationship. This is absolutely right, but while reading about Django templates, I just realized another pattern in these relationships. This is really simple and perhaps many of you may have already have had this insight... We use inheritance when we want to allow reuse of the bulk of one object in other ...

Planning a User Guide - Part 3/5 - Co-ordinate the Team

Photo by  Helloquence  on  Unsplash This is the third post in a series of five posts on how to plan a user guide. In the first post , I wrote about how to conduct an audience analysis and the second post discussed how to define the overall scope of the manual. Once the overall scope of the user guide is defined, the next step is to coordinate the team that will work on creating the manual. A typical team will consist of the following roles. Many of these roles will be fulfilled by freelancers since they are one-off or intermittent work engagements. At the end of the article, I have provided a list of websites where you can find good freelancers. Creative Artist You'll need to work with a creative artist to design the cover page and any other images for the user guide. Most small to mid-sized companies don't have a dedicated creative artist on their rolls. But that's not a problem. There are several freelancing websites where you can work with great creative ...