Tuesday 29 September 2009

Refactoring Progress #5

The refactoring is almost complete:

I've just spent about five hours in total dealing with bugs I introduced into the TDungeon level generation code while refactoring, which was mainly due to doing the refactoring offline, i.e. not within an environment where the code could compile. It has been a useful exercise, as well as removing any code that I'd be ashamed of releasing (now there's just a lot of code left that I merely dislike), I've reaquainted myself with a lot of code that has been written for quite a while now and which I had forgotten the purpose of. The code also conforms a lot more to coding standards.

The only major source code left to refactor is UnitDisplay.pas which, as the name suggests, is, contains the code that interfaces with the screen and the GUI-handling code. Its about 4000 lines of code. I'm on target to finish the refactor within the week or so.

Its a messy unit, full of code like this:
Procedure TFormDisplay.ListViewMonstersCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if ListViewMonsters.Items.Count = 0 then Compare := 0
else
begin
if (StrToInt(Item1.SubItems[6])) > (StrToInt(Item1.SubItems[6])) then Compare := 1
else if (StrToInt(Item1.SubItems[6])) = (StrToInt(Item1.SubItems[6])) then Compare := 0
else Compare := -1;
end;
end;
I'm not coding C, so there's no virtue in conciseness. The refactor turns that code into this (note that some of the indenting may not display properly, but the final code is indented properly):
{ Sort Routine to sort entries in the Visible Monsters display - compares two
TListItems and returns a comparison based upon TMonster.Level }

Procedure
TFormDisplay.ListViewMonstersCompare(Sender: TObject; Item1,

Item2: TListItem; Data: Integer; var Compare: Integer);
var
FirstItemLevel: Integer;
SecondItemLevel: Integer;

begin

{ Logging }
hLog.Add('{now} {lNum} TFormDisplay.ListViewMonstersCompare()');

{ Default result which is that both items are equal}
Result := 0;

try
{ Make sure there are items to compare }
if ListViewMonsters.Items.Count > 0 then
begin
{ Get the monster levels from the Listview Items }
FirstItemLevel := StrToIntDef(Item1.SubItems[MONSTER_LEVEL], 0);
SecondItemLevel := StrToIntDef(Item2.SubItems[MONSTER_LEVEL], 0);

{ Compare the Monster Levels of each items }

{ First > Second }
if FirstItemLevel > SecondItemLevel then
Compare := 1

{ First <>
else if FirstItemLevel < style="font-weight: bold; color: rgb(0, 0, 102);">) then
Compare := -1;

end;
except
{ in case of error, log the Exception }
on
E: Exception do hLog.AddException(E);
end;
end;
After I finish that unit, I'll have to put together the instructions for downloading and installing the various 3rd party components that I use, and then technically I'll have a source code distribution ready for when I release Kharne under the MPL.

No comments: