Dependency Injection is certainly one of the most important concepts when trying to write testable code. But while Java and C# have garbage collection, Delphi has not and normally, object disposal is managed using the ownership-principle (the one who creates the object destroys it). This is nicely supported by the try..finally
construct
Obj := TObject.Create;
try
...
finally
Obj.Free;
end;
Now what if one uses dependency injection:
constructor TFileLister.Create(FileSystem: TFileSystem);
Who should now be responsible for destroying the FileSystem
object? Does the ownership-principle still work here?
I know that interfaces are a solution to this problem (thanks to the fact that they are reference-counted). But what if there are no interfaces (say in some legacy code)? What other approaches or best practices are there to handle memory management when using dependency injection?
You have to come up with an owner for the FileSystem object. This can be either the entity that creates the TFileLister instances, or you could pass ownership to the file lister, documenting that it will free the file system that was passed to the constructor.
The right approach depends on course on your particular application. For example, if other objects would also use the same file system object, it shouldn't be owned by one of these such as the file lister, but by the object that ties it all together. You could even make the file system object global if it only makes sense to have one of it.
In short, you'll have to do a little more thinking than in Java but that's not necessarily a bad thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With