Mirror

Improving your Object classes reliability (Views: 708)


Problem/Question/Abstract:

One of the worst things you can do is not call a destructor for an object. I found this the hard way with my article on Compound Volumes. The destructor call ensured that any new additions to the file were properly recorded. So forgetting it caused corruption if new files were added.

Answer:

So what we want is a way to call the destructor automatically if you forget to do it. Now I could be accused of encouraging lazy programming. So what you should do is put a ShowMessage call saying something like “*Oi dipstick, you haven’t called a destructor”. That way you avoid corrupting data and your mistakes are found a bit easier.

Heres the main code to be added after the implementation section:
Note that calling TObject(Pointer).Free works for all objects. (Unless you know better...)

var
  cvList: Tlist;

const
  InTidy: boolean = false;

procedure Remove(V: TCompoundVolume);
var
  Index: integer;
begin
  if InTidy then
    exit;
  for Index := cvlist.count - 1 downto 0 do
    if cvlist[Index] = v then
      cvlist.Delete(Index);
end;

procedure Tidylist;
var
  Index: integer;
begin
  if InTidy then
    exit;
  InTidy := true;
  for Index := cvlist.count - 1 downto 0 do
    if assigned(Cvlist[Index]) then
    begin
      TObject(Cvlist[index]).Free;
      cvlist.Delete(Index);
    end;
  InTidy := false;
end;

In the class creator add this line

cvList.Add(Self);

and in the destructor add this

Remove(Self);

And in your unit, add the lines or modify the Initialization/finalization sections

initialization
  cvlist := tlist.Create;

finalization
  TidyList;
  cvlist.free;

If your destructor is called by you, the call to Remove will remove it from the list. This needs a recursion check in case you forgot to call it and it tries to call Remove while the destructor is called from TidyList. That is what the flag InTidy guards against.

*Dipstick is a mild English term of abuse, about the same as tosspot or tosser, but not as bad as say wanker.

<< Back to main page