Thursday 13 August 2009

Refactoring Progress #1

Here's the current progress in the great Refactor/Tidyup/Open Source project. Red lines represent Units/Forms that have been completed.

(yes, that is the View->Project Manager dialog for the main Kharne executable)

Here's an example of an unrefactored procedure in all its hideousness (including, you'll note, no comments, the shame):

function TMonster.GetSinglePrefix: string;
begin
if (Length(Trim(UniqueName)) <> 0) then Result := ' ' else
begin
if (MonsterName[1] in ['A', 'E', 'I', 'O', 'U', 'a',
'i', 'e', 'o', 'u']) then

Result := 'an '
else
Result := 'a ';
end;
end;

And here is the refactored version:

{ Return the singular form of the prefix }
function TMonster.GetSinglePrefix: string;
begin
{ Logging }
hLog.Add('{now} {lNum} TMonster.GetSinglePrefix()');

{ Default result }
Result := '';

try
{ Again, Uniques do not have prefixes }
if (FUnique) then
Result := ' '
else
begin
{ Deal with vowels }
if (Vowel(FName)) then
Result := 'an '
else
Result := 'a ';
end;
except
{ in case of error, log the Exception }
on E: Exception do hLog.AddException(E);
end;
end;

Its still not perfect, there are still many optimisations that could be done (e.g. raising exceptions properly, dealing with those spaces that keep appearing in many of my punctuation routines), but the second excerpt I'd be happy to see released into the world with my name on it.

2 comments:

George said...

As a hobby programmer I have always wondered, what is the point of comments where you explain a line of code in natural english, like,

{ in case of error, log the Exception }
on E: Exception do hLog.AddException(E);


Are there some documentation utilities that take advantage of this? It seems redundant.

Dave said...

That's correct - normally, such comments wouldn't be of much use, however, I'm intending to enhance the exception handling soon and the comments are there mainly as a placeholder.