Introduction
In my previous article, I showed how to auto-generate a decorator over one or several classes. In this article, I’ll show a more difficult generation technique: auto-generation of a Visitor pattern via creation of a visitor class and injection of visit methods into existing classes.
To try out the add-in, download the Zip with the binaries and extract them into your Addins folder.
Some Theory
If I wanted to translate several different types of objects into C#, I would typically give each of them a method similar to the following:
class MyEntity {
public something State { get; set; }
public void ToCode(StringBuilder sb)
{
sb.Append("static class " + State + " {}");
}
}
The above would take the State
property of the object being traversed (or visited), and will output valid C#. It looks simple enough, and you can litter your code with these types of statements. The only problem is when you want to output some other language, e.g., Nemerle. In this case, you need to refactor the ToCode()
method to take a second parameter – the language to generate. This results in the following:
public void ToCode(StringBuilder sb, Language language)
{
switch (language) {
case Language.CSharp:
sb.Append("static class " + State + " {}");
break;
case Language.Nemerle:
sb.Append("module " + State + " {}");
break;
}
}
Making this change in lots of classes is unrealistic. In a typical hierarchy, you might have dozens, or even hundreds of locations where you’d need to change this code, and it’s very inconvenient. So, what do you do? Well, one way of doing it is, instead of using a StringBuilder
, use an inheritable class (a decorator over StringBuilder
). But then, statements for emitting the code cannot be done in the visited classes because, after all, a visited class no longer knows (or cares) whether C# or Nemerle code is required. Here’s what I mean:
public void ToCode(CodeBuilder cb)
{
cb.VisitMyEntity(this);
}
Instead of doing anything in the visited method, we do an inversion of control, and code assembly happens in the builder’s method. This way, a C# builder would append the line in its own way, and the Nemerle builder otherwise. Congratulations – you’ve just seen an example of a full-fledged Visitor pattern.
An Example
So, what’s the problem? Well, the problem is that hierarchies are sometimes quite large, and making all this code by hand (especially if you never planned classes to be visitable) is unrealistic. For a hierarchy of 20 classes, you would require to create a visitor with 20 VisitXXX
methods, and add 20 methods to each of the visited classes. By hand. Not an easy proposition.
My tool does it for you. Here’s how. First, right-click the project and choose Add|Visitor:
Then, give the visitor a name and select all the classes you want to visit:
Now, open the Method tab to customize your visit method. Here you can define:
- Your method name
- Any additional parameters for the method
- Code that will get written immediately before calling the Visitor-owned method
- Code that will get written immediately after calling the Visitor-owned method
After you press OK, two things happen. First, you get a generated visitor class similar to the following:
class MySpecialVisitor
{
public void VisitMyEntity(MyEntity target)
{
}
public void VisitOtherEntity(OtherEntity target)
{
}
}
See how the class accepts every type of object you selected as a parameter? It’s up to you to write actual handling code here. Now, in addition to this, every class you have selected had another method added. The method looks as follows:
void SpecialVisit(MySpecialVisitor visitor, int somethingHere)
{
visitor.VisitMyEntity(this);
}
There you go – the add-in generated all the necessary plumbing for the Visitor pattern. Simple, isn’t it?
Final Thoughts
This article continues the theme of the previous one, i.e., code generation. The CodeBuilder
decorator is subclassed by builders such as CSharpBuilder
(which were discussed in the previous article), and the whole thing is propagated through model hierarchies via the Visitor pattern. This makes it a very neat and tidy system to use.
The way this add-in was written is similar to the previous one: a C# parser looks at the source code and finds all the classes. Then, we generate the Visitor class from the user’s selections. Adding methods is a bit trickier: since there is no proper API to add code into a class declaration, I use some good old-fashioned hackery to get the job done. I even reformat code after adding it – something that is tricky to do because if you save a file behind the scenes and reformat it in Visual Studio, you get a really weird dialog box asking you whether you prefer the behind-the-scenes file or the one in memory. Luckily, the API is flexible enough to allow us to close open files, write to them, open them again, reformat, and then close the ones that were initially closed. All for the sake of convenience.
That’s all I have to say! If you liked the article, please vote for it! Oh, and as you may have guessed, another pattern-related article is forthcoming. Stay tuned!