Watch, Follow, &
Connect with Us

For forums, blogs and more please visit our
Developer Tools Community.


ID: 17353, Coding Tip...

by Derrick Nel Email: Anonymous


dynamic object creation technique..
Download Details
FTP  download also available
CDN Login Required to Download. (You will be redirected to the login page if you click on the Download Link)
To download this, you must have registered:
A free membership

For Delphi, Version 1.0  to 6.0 1851 downloads
Copyright: No significant restrictions


Size: 6,339 bytes
Updated on Mon, 14 Jan 2002 05:40:33 GMT
Originally uploaded on Mon, 14 Jan 2002 05:44:03 GMT
SHA1 Hash: C7150C37F7951F340E853DD91B2E59A2C2C5C72C
MD5 Hash: 2C59260DF2433710CB89E6ED61CE5BFA

    Explore the files in this upload

Description
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,
Derrick….(dnel@oldmutual.com)

"programming in VB is like kicking a dead whale down the beach""..

   Latest Comments  View All Add New

Move mouse over comment to see the full text

Could not retrieve comments. Please try again later.

Server Response from: ETNACDC04