views:

235

answers:

3

I'm about to writing an app which will be making use of the state and command patterns. The States will act as a facade to the commands.

There are 7 states and about 50 Commands which not all the states can execute, any method for which the command cannot be executed will throw an execption, otherwise It will create the command, execute it and return the result.

Since there are such a lot of classes that are going to be so similar I'm thinking of writing some code to auto generate the code. I've got a matrix mapped out in Excel of which states allow which commands to be executed, and I was planning on outputting that to csv and useing that as the basis for the code generation.

My idea is to manually write the interfaces that the various classes implement and then use that as a template for the code generator.

Is this a good idea? Does anyone have any tips on the best way to go about doing this?

I'll be codeing in Java however I think the basic principles apply to code generation in any OO language.

+1  A: 

Well, if the classes are really that similar, why not derive them from a common Command object instead of using code generation?

What you're talking about seems to be a basic rules engine -- the Rules Engine you're making is basically what runs each command.

Dave Markle
My design has room for an abstract command class however I'll still need to code up 50 classes hence the code generation.
Omar Kooheji
So you have a choice of making 50 classes and compiling or filling out 50 templates? Seems like about the same amount of work, except if you use code generation you have to write the code generator! I mean, if most of your classes are similar, your class definitions for your derived classes should be really, really simple...
Dave Markle
I was planning on using the code generator to do the tedious bit of writing the skeletons using a single template, and then filling in the balnks. But I do see your point.
Omar Kooheji
A: 

We use Excel macros to generate FSM code (in C) like this, it works really well for us. One thing I would suggest is using templates for as much of the generated code as possible so that other users can change the templates to match their preferred style.

Vicky
A: 

I'm working on a project at the moment that makes heavy use of code generation for a similar sort of scenario; after some time working with the generated code I'm finding that in the cases where generation is used to provide lots of rote code, a solution with more use of generic types (which hold what would be the repeated bits) and independent function types to hold the specific logic, would actually reduce the amount of code to maintain.

In Java, the syntax for writing a function pointer is more cumbersome than in other languages (yet another interface for a class to implement), but by the time you've analysed the problem enough to create the templates, you've done the pre-emptive refactoring required.

Steve Gilham