Templating for deferred binding / code generation

63 views
Skip to first unread message

Harald Pehl

unread,
Mar 2, 2011, 3:42:26 AM3/2/11
to google-we...@googlegroups.com
In my current project I'm using deferred binding to generate code. The code generation is heavily based on writer.write(String), writer.indent() and writer.outdent(): 

writer.write("%s = new %s<%s>();", var1, collectionImplementation, paramType);
writer.write("for (Element %s : %s) {"elementVariableelementsVariable);
writer.indent();
writer.write("if (%s != null) {", valueVariable);
writer.indent();
writer.write("%s.add(%s);", valueVariable, valueVariable);
writer.outdent();
writer.write("}");
writer.outdent();
writer.write("}");

The whole process became very complex and error-prone. I'm thinking about to use velocity templates. Has anyone already used velocity templates for code generation? Is this a good idea? What do you think?

- Harald 

Colin Alworth

unread,
Mar 3, 2011, 2:02:38 PM3/3/11
to google-we...@googlegroups.com
My generators tend to be very heavily commented, and I try to keep blocks of printed code as small as possible in my code. I like to work up most of the boilerplate stuff in an existing abstract class or classes, and extend those when making my generated class. Small methods help too - your Element and the collection of elements can be probably named by the generator, or perhaps the whole method written as something in an abstract impl class.

The folks at Rocket-GWT have some other ideas, though the project seems to have died (or at least fallen asleep). Their approach seems to include templating, but also better tools to programmaticly write code. Perhaps someone else can pick up their mantle, but at least check out their thoughts: http://code.google.com/p/rocket-gwt/wiki/Generator.

-Colin

Philippe Beaudoin

unread,
Mar 3, 2011, 2:06:33 PM3/3/11
to google-we...@googlegroups.com
I've never tried that but am very interested in how it works out for you if you ever decide to go this route. Please keep us posted! :)

Harald Pehl

unread,
Mar 3, 2011, 3:07:55 PM3/3/11
to google-we...@googlegroups.com
Thanks for your input. I will give velocity templates a try and will let you know what I found out. 

- Harald

Harald Pehl

unread,
Jan 24, 2012, 4:54:39 PM1/24/12
to google-we...@googlegroups.com
Finally I found the time to refactor the complete code generation process in Piriti from PrintWriter.write() to a Velocity based solution. The big advantage is that the generated code is much more readable. For more details please take a look at my blog post: http://haraldpehl.blogspot.com/2012/01/how-to-use-velocity-to-generate-code-in.html

- Harald 
Reply all
Reply to author
Forward
0 new messages