Quantcast
Channel: Delphi – The Wiert Corner – irregular stream of stuff
Viewing all articles
Browse latest Browse all 1445

Another case against FreeAndNil

$
0
0

I started this post as “A case against FreeAndNil” but soon found out about [WayBack/Archive.isA case against FreeAndNil – Community Blogs – Embarcadero Community.

Recently I was refactoring a bunch of code that was classed based to become interface based.

The old code had a lot of references to classes like this:

FMyField: TMyClass;

The compiler had detected those as compiler errors so now they were like this:

FMyField: IMyInterface;

But the compiler would still happily compile code (for instance in destructors) containing:

FreeAndNil(FMyField);

The only way that FreeAndNil can be implemented is with an untyped var parameter:

procedure FreeAndNil(var Obj);
var
  Temp: TObject;
begin
  Temp := TObject(Obj);
  Pointer(Obj) := nil;
  Temp.Free;
end;

This var construct makes it typeless: the method dutifully accepts anything even something that isn’t a TObject. And there is hardly anyw any (cheap) way to detect it’s actually a TObject (as it likekly won’t have RTTI).

What happens when you call it with an interface as parameter is that the hard cast will execute a “Free” method that might not be a method at all. Or is a method that does something totally different, expects more parameters (hello stack-underflow!) or has other harmfull side effects.

So contrary to the past – where most people would prefer FreeAndNil – I’m back to the below code in class based situations:

FMyField.Free(); FMyField := nil;

This looks like a strange but it has the visual clue that both are being executed and belong together.

Edit: the above is why I wrote a generic FreeAndNil inside a helper that limits itself to TObject references. The gist is below. This is the declaration:

class procedure FreeAndNil<T: class>(var Value: T); static;

Some future enhancements:

Blast from the past which is how I used to do it:

–jeroen


Viewing all articles
Browse latest Browse all 1445

Trending Articles