I was curious if anyone used code generation (writing code that writes code) in their projects. I haven’t seen the technique described in the context of java game development but I have dabbled in it a bit and have liked what it gives me and may look for opportunities to do more. I want two things which seem to work against one another. I want to be able to specify things in config/data files because it is often the most convenient and least error prone way to do so. I also want what I specify to be used as if it were hard coded and to take advantage of Java’s built in type checking. For instance, if I describe my ExplosionEvent message in a data file:
+ Explosion
position mygame.util.Vector3
strength float
I want to be able to say things like:
System.out.println("BOOM " + explosion.strength);
instead of
System.out.println("BOOM " + (float)explosion.getParam("strength"));
So I have code (in a separate project) that reads in the message config file, and generates a java file for each message definition in the appropriate directory in my game project code. (I suppose i could change the build so that it automatically creates a jar that I import instead).
public class ExplosionMessage extends Message {
public final mygame.util.Vector3 position;
public final float strength;
public ExplosionMessage(Entity sender, Entity recipient, mygame.util.Vector3 position, float strength) {
super(sender,recipient);
this.position = position;
this.strength = strength;
}
}
Pros
- More efficient. Properties are fields not entries in a hashmap.
- lds not property maps. Message types are classes not a generic message type with a name parameter.
Compile time safety. If, in my game code, I misspell a property I will get a compile time error, not a run time error.
Because the fields are explicitly typed, I don’t have to do a lot of casting.
Cons
[li]Extra project/code necessary to do the conversion of config file to java classes
- An extra build step
For me, the cons are hardly a bother (if you are using external config files, you need to write some code to read it into your game engine anyhow and running the CodeGen code takes seconds). Event messages are the simplest application of this because they are simple data containers but I could see the potential for trying to do more.
Does anyone else do anything like this? What has your experience been?