Don't mix objects and interfaces

Mixing objects and interfaces in classic (non-ARC) Delphi is a huge no-no. That part is clear. What that actually means is more of a blur. After all there is a object instance lying behind every interface reference.

So what is wrong with mixing objects and interfaces?
  1. object references are weak, interface references are strong
  2. reference counted object instances need at least one strong reference to keep them alive therefore you can't use object reference as primary owning reference
  3. reference counted object instances can be safely accessed through temporary, short-lived (weak) object references, as long as there are strong reference(s) keeping the object alive


The real issue behind the mixing of objects and interfaces is not the mixing itself, but the lack of initial strong (interface) reference to object instance, or accessing the reference counted object instance through weak (object) reference after the last strong (interface) reference has gone out of scope and the object has already been destroyed.

Note: Term weak in this post is used to denote references that don't participate in reference counting mechanism and are not strong references. More precisely, object references in classic Delphi compiler act as [unsafe], since they are not niled after the object they point to is no longer valid.

Popular posts from this blog

What is thread safety anyway?

Optimizing ARC the hard way

Git the Princess the Delphi Way