Delphi – How to avoid to call Application.CreateForm twice

delphidelphi-2007

I stumbled on this page Why shouldn’t I call Application.CreateForm.
Now I have some code like this:

SplashForm := TSplashForm.Create(Application);
SplashForm.Show;
SplashForm.Update; // force update
Application.Initialize;
Application.CreateForm(TClientData, ClientData);
SplashForm.Update; // force update
Application.CreateForm(TClientMainForm, ClientMainForm);
Application.ShowHint := True;

Application.Run;
ClientMainForm.ServerConnected := false;
FreeAndNil(ClientMainForm);
FreeAndNil(ClientData);

First a splashform is created, then a datamodule and last the main form. The page says that Application.CreateForm should not be called twice. Should the code above be changed?

Best Solution

There is nothing wrong with using Application.CreateForm multiple times. But this introduces global variables for each form which can be a code smell. Unfortunately the IDE creates one for each form. Although you can remove them if you like.

A better way is to create a form when you need it and release it when you are ready with it. So you only use Application.CreateForm for the main form.

A main datamodule can be created by the main form. But it can be global too, just a matter of taste.

So to answer the question, you can avoid Application.CreateForm by creating and releasing the forms locally.

The article mentions the side effect of Application.CreateForm (the first completed form is the main form). So there can be unexpected side effects if the main form creates other forms using Application.CreateForm.

So just to avoid any nastyness, you should limit yoursef to a single call. Which is done using only one global form.

Related Question