It is almost always preferable to consider the object that creates the object, also to be its owner (i.e. responsible for its destruction).
To understand why I say this, consider an alternative. Suppose object A creates object B. At some point, it passes B to object C, which becomes the owner.
Between the creation of B and its transfer to C, A is responsible for destroying in case of exceptions, or possibly for choosing a branch that bypasses C. On the other hand, once it passes B, A should not try to destroy C.
All this can be handled with sufficient care. One approach is to use VCL with TComponent.Owner .
However, if you can find a way to stick to two standard ownership patterns, do it.
What are the two standard templates?
- Create in the constructor and assign a field; destroy in the appropriate destructor.
- Create and destroy within one method, with the protection provided by
try / finally .
I highly recommend that you try building your code so that all resource acquisitions use one of these two options.
How can you do this in your example? The option that appears to me is to use factory to create your FileSystem object. This allows TFileLister to control the lifetime of the FileSystem object, but gives you the flexibility to introduce different behaviors into TFileLister .
source share