I've worked with numerous Delphi developers over the years and worked with a lot of other developers code. I've found that some developers seem happy just to free an object once it is no longer required and some always use FreeAndNil.
My rule on using .Free and FreeAndNil is always use FreeAndNil except when the object is in local scope. For example the only time I use .Free is:
procedure DoSomething;
var
productList: TStringList;
begin
productList := TStringList.Create();
try
// Do something...
finally
productList.Free;
end;
end;
I consider the above to be fine, however recently I was speaking to a developer who said they always use FreeAndNil because what would happen if some other developer added to the procedure and tried to use the object, but check that is was assigned first. In the example above if someone added some code that checked for the assignment and then a block of code that used 'productList'. An error would not occur however the block of code would never be executed. The question here is what is better, the block of code never to execute or an error to occur and the bug is fixed. It is possible that the unit test would detect both early on, and apparently a code coverage tool would also detect that the block of code was never executed (can anyone suggest code coverage tools for Delphi?).
The other argument my colleague had for always using FreeAndNil was if another developer came along and changed the scope of productList and made it into a private or public variable. I consider this to be a weak argument because if a developer did this without reviewing the code then they should not be a Delphi developer.
Showing posts with label free. Show all posts
Showing posts with label free. Show all posts
Saturday, 10 December 2016
Tuesday, 9 April 2013
How to correctly free a thread
There are 2 ways to free a thread, below are both, but my favourite way is to explicitly free the thread as I may want to reference something after the thread is terminated, but before it is freed.
while not Terminated do
3) When you want to free the thread do something like:
FThread.Terminate;
FThread.Terminate;
Explicitly free the thread
1) Set the 'FreeOnTermiate' property to false, this can be done when your thread class is created.
2) In the execute procedure check for the terminate property e.g.
while not Terminated do
begin
// execute code
end;
3) When you want to free the thread do something like:
FThread.Terminate;
FThread.WaitFor;
FreeAndNil(FThread);
Easier way to free the thread
1) Set the 'FreeOnTermiate' property to true.
2) When you want to free the thread just call:
FThread.Terminate;
Subscribe to:
Posts (Atom)