Archive for January, 2014

An Interface You Can Count On

Wednesday, January 15th, 2014

Using refcounted interfaces can be difficult, especially when introducing them into legacy code.  Unfortunately, interfacing is key to breaking dependencies and making code more testable.

There are only two approaches I have seen to debugging refcount issues:

1) Create a descendant of TInterfacedObject and override the _AddRef/_Release to log class information and the current refcount.  You could also use copy/paste inheritance (although I do not recommend making a habit of it), and change the implementations.

2) Create your own Interface like I did that exposes the RefCount and ClassName properties and make it the root ancestor for all interfaces used in your project instead of IInterface.  Then you can see the implementing class, and it’s refcount in the debugger, and log it as well if you see fit.  I wonder why TInterfacedObject doesn’t have such properties to begin with…

Here is an interface you can count on ;-) :


/// Interface that should be used as the ancestor
/// for all interfaces so we can see the refcount
/// when debugging without potentially altering it
/// by calling _AddRef/_Release.

IRefCountInterface = interface(IInterface)
['{95A446C2-A9E4-4355-8DDD-5B6854EBDBD0}']
function GetRefCount :Integer;
function GetClassName: string;
property RefCount :integer read GetRefCount;
property ClassName :string read GetClassName;
end;