Thursday, April 19, 2007

Obscure Duplication

Many people have written about the evils of duplication in code. Refactoring tools have evolved to the point where they can often detect it. Eclipse's "extract method" refactoring will identify similar blocks of code and replace all instances with a call to the extracted method.

There are other forms of duplication in software development that are harder to find, but cause just as many problems. One common example is duplicating state between code and configuration files.

I just finished removing one such case. Fall of Rome uses rules files to define variable elements of the game, including emissary definitions. An example might be:
{ //Emissary Rank
1 //Rank
"King" //Description
}

Unfortunately, the code for determining the icons for representing the emissaries on screen relied upon static variables defined in a Java class:

public static final int kRank_King = 1

public String getIconFilename() {
switch( rank ) {
case( kRank_King )
iconName = "king"
...
}

The Emissary Rank concept is duplicated between the configuration files and the code. This makes it hard to change the Rank definitions, as I discovered accidentally when the Drow Queen I created looked like a Provincial Governor.

Fortunately, this particular instance was not hard to change. Most of the emissary descriptions are very close to the icon filenames, and I was able to replace the switch statement on emissary ranks with one line of code:

return emissary.getEmissaryRankInfo().description.toLowerCase();