Since I discovered Haml for my HTML templates in Rails, I stopped using ERB. Haml is more intuitive and readable to me.

I am rediscovering ERB though for something else completely – Java code generation.

There is a lot of boilerplate code in most Java projects. A good IDE can help you alleviate some of it but most (if not all) applications will have additional boilerplate very specific to your application. Using ERB, you can easily create cut down on mindless typing.

For example, let’s suppose you are writing many Java listeners. Just create a script that will do it for you. I’ll make an exemple with a ContactListener class that is notified when a user is added, removed or blacklisted from your contact list.

require 'rubygems'  require 'erb'     # setup - could be initialized from script arguments  classname = "Contact"  listener_methods = ["added", "removed", "blackListed"]     # create file based on 'listener.java.erb'  content = File.read('listener.java.erb')  template = ERB.new(content)  File.open("#{classname}Listener.java", 'w') { |f| f.puts(template.result) }

If I run this using listener.java.erb:

public interface <%= classname %>Listener {    <% listener_methods.each do |method|  %>    void <%= method %>(<%= classname %>Event event);    <% end %>  }

Then I generate this file:

public interface ContactListener {    void added(ContactEvent event);    void removed(ContactEvent event);    void blackListed(ContactEvent event);  }

That was easy – and it’s not that useful I admit. I’m sure you can create your own listeners just as fast in your own IDE. Probably even faster.

However here comes the fun part – the same script can be used to create lots of other classes:

  • The ContactAdapter class
  • The ContactEvent class
  • The ContactController
  • The Contact model
  • The ContactRepository (maybe even with a few methods to add/remove/retrieve a contact by id)
  • The ContactView through which users will be able to trigger ContactEvents (maybe with a simple UI – even buttons to trigger each events on the ContactHandler)
  • Registration of the ContactHandler and the ContactView by your favorite IOC framework
  • Registration of the ContactView so it is accessible from your application’s menu
  • Test classes for all of the above (including failing test cases that you’re going to have to write)

And probably other bits here and there to glue everything together.

Your mileage may vary, but code generation might be a great way to make your path shorter.

Can your IDE do that?

gabriel bélanger

Previous post

An interesting way to fund projects (en)

Next post

Start doing sprint reviews not demos (en)