CODING TIP
When one creates objects dynamically, as needed, your code inevitably becomes quite messy. Checking to see if the object exists before creating it, eg.
if FMyVariable = nil then
FMyVariable := TMyClass.Create;
Checking to see if the object exists before destroying it, e.g
if FMyVariable <> nil then
FreeAndNil(FMyVariable)
Checking to see if the object exists before using it, e.g
if FMyVariable = nil then
begin
FMyVariable := TMyClass.Create;
FMyVariable.SomeMethod;
end;
OR
if FMyVariable <> nil then
FMyVariable.SomeMethod;
Inevitably your code becomes scattered with code like the fragments shown above making maintenance a real difficult task. If you needed to change the create you would have to hunt all over looking for the "if <> nil then create" or "if = nil then create", with 4 simple methods you can neaten up your code and give maintenance programmers a break.
The four simple methods are :
procedure CreateObject;
procedure FreeObject;
function ObjectAllocated: Boolean;
procedure ObjectNeeded;
and this is how the code for each method looks;
procedure CreateObject;
begin
FObject := TObject.Create;
end;
procedure FreeObject;
begin
if ObjectAllocated then
FreeAndNil(FObject);
end;
function ObjectAllocated: Boolean;
begin
Result := (FObject <> nil);
end;
procedure ObjectNeeded;
begin
if not ObjectAllocated then
CreateObject;
end;
And that’s it, so instead of using :
"If FObject <> nil then" you use "if ObjectAllocated then", when you need the object simply call ObjectNeeded, and to destroy the object simply call FreeObject. All the nitty-gritty if existance checking is already taken care of.
Good luck,
http://codecentral.borland.com/codecent ... g?id=17353 Alıntıdır