A better way of creating from a class parameter? - delphi

In TApplication.CreateForm (not sure if it is allowed to paste the code here. I will do so if somemone confirms) it seems a way of creating an instance of a TForm descendant by using the class of the derived form and a variable pointing to the form. Both are parameters of CreateForm;
procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
Is there a better or even simpler way (maybe with less code) of doing what is done in CreateForm if I wanted to have a method which creates a derived control with only some parameters as indicators of what class it is and the variable it will be using.
EDIT: I would like to have a method that creates a control which I use in my project. The method will also do some additional code related to the control so that is the reason for the method. I do not want to duplicate that additional work and the method will be called numerous times. I can implement the code in the same way as CreateForm but was wondering if there is a way of doing the same in less or simpler code.

I want to have a method which creates a derived control with only some parameters as indicators of what class it is and the variable it will be using.
You don't need a method for that. You can write it like this:
MyForm := TMyForm.Create(Owner);
Don't be put off by all the code in Application.CreateForm. That code performs many tasks, the principle of which is to assign the Application.MainForm variable. The IDE likes to encourage you to use Application.CreateForm but in reality you only need to call it once, and that is to create the main form.
If you are dead set on making this into a method then it would look like this:
function CreateForm(FormClass: TFormClass; Owner: TComponent): TForm;
begin
Result := FormClass.Create(Owner);
end;
When calling this function you would need to cast the value returned:
MyForm := TMyForm(CreateForm(TMyForm, Owner));
or
MyForm := CreateForm(TMyForm, Owner) as TMyForm;
As an alternative you could use a generic method:
type
TFormCreator = class
public
class function CreateForm<T: TForm>(Owner: TComponent): T; static;
end;
Implement it like this:
class function TFormCreator.CreateForm<T>(Owner: TComponent): T;
begin
Result := T(TFormClass(T).Create(Owner));
end;
Call it like this:
MyForm := TFormCreator.CreateForm<TMyForm>(Owner);
Pretty ridiculous isn't it? All you want to do is instantiate a form! So, I have a strong suspicion that you have been confused by the IDE's use of Application.CreateForm and believe that there is more to instantiating forms than there really is. My instincts tell me that you are actually looking for this:
MyForm := TMyForm.Create(Owner);

AS. You can post YOUR OWN code, but with regards to code which copyrights holds someone else - that gets a bit complicated. I believe it falls under USA "Fair Use" doctrine. For example you can post a snippet of VCL source to criticize or demonstrate something, but not to copy-paste it into another project and only as little of the VCL code - as required for that "fair use" intention.
A VCL form is a component, thus it needs an owner, who would be responsible for memory management. So you can create the form in a typical TComponent creation pattern.
MyFormVariable := TMyFormClass.Create( Application );
This also adds for type safety that untyped var Reference in CreateForm denies.
Whether that way is better or worse than using Application.CreateForm is up to your tastes. Personally I prefer uniform way so when I need to create a form or a datamodule explicitly I usually go the "component" way not the "application" way.
I guess (just guess) that back in old days TApplication.CreateForm added some extra required setup that "component way" of creating forms could not do, at least not before VCL would get started by Application.Run call. Or maybe there were types of TApplication - and AFAIR there are 5 ones for different projects - that were not derived from TComponent? But anyway I think today that limitations - if ever there where any - not apply any more.

Related

Dynamically create form by name?

Is there a way to create forms dynamically by only their names;
The concept goes like this. I have a main form, and by some user selection, a number of predefined forms must be created and docked on tabitems on a pagecontols on the main form.
I do know the names of the forms and i do know when to create each one of those, but i would like to know if a better way of creating these forms by a single procedure call, and not having all of these information in my code.
Its Delphi XE3 firemonkey, on win 7.
Thanks in advance for any help
Apparently on Firemonkey Delphi doesn't automatically register form classes to be available by name, so you'll first need to add something like this to the end of the unit that holds your form class:
unit Form10;
[ ... ]
// Right before the final "end."
initialization
RegisterFmxClasses([TForm10]);
end.
This will automatically register TForm10 so it'll be available by name. Next you can use this kind of code to create a form at Runtime by it's class name:
procedure TForm10.Button1Click(Sender: TObject);
var ObjClass: TFmxObjectClass;
NewForm: TCustomForm;
begin
ObjClass := TFmxObjectClass(GetClass(ClassName));
if ObjClass <> nil then
begin
NewForm := ObjClass.Create(Self) as TCustomForm;
if Assigned(NewForm) then
NewForm.Show;
end
end;
You can only create objects when you have a class reference for it. To get a class reference for something given its string name, call FindClass. Call the constructor on the result. You may have to type-cast the result to a different metaclass before the compiler will allow you to access the constructor you want. In the VCL, you might use TFormClass, but plain old TComponentClass will work, too, since all FireMonkey objects are descendants of TComponent; the important part is that you have access to the right constructor, and that's where the one you need is introduced.
It only works for classes that have been registered. Your form classes should be registered by Delphi automatically, but if they're not, you can call RegisterClasses manually, or RegisterFmxClasses if you need to put your classes in groups.
Delphi.About.com has a VCL demonstration.

Why is using procedures to create objects preferred over functions?

This is similar to this question. I asked "Why?" to the most popular response but I don't know that anyone would ever look at it again. At least not in any timely manner.
Anyway, my question is about best practices for delegating responsibility for creation of objects to functions or procedures, without causing memory leaks. It seems that this:
procedure FillObject(MyObject: TMyObject; SomeParam: Integer);
begin
//Database operations to fill object
end;
procedure CallUsingProcedure();
var
MyObject: TMyObject;
begin
MyObject = TMyObject.Create();
try
FillObject(MyObject, 1);
//use object
finally
MyObject.Free();
end;
end;
is preferred over this:
function CreateMyObject(DBID: Integer): TMyObject;
begin
Result := TMyObject.Create();
try
//Database operations to fill object
except on E: Exception do
begin
Result.Free();
raise;
end;
end;
end;
procedure CallUsingFunction();
var
MyObject: TMyObject;
begin
MyObject = CreateMyObject(1);
try
//use object
finally
MyObject.Free();
end;
end;
Why?
I'm relatively new to Delphi, having previously worked most with Java and PHP, as well as C++, though to a lesser extent. Intuitively, I lean toward the function method because:
It encapsulates the object creation code in the function, rather than create the object separately whenever I want to use the procedure.
I dislike methods that alter their parameters. It's often left undocumented and can make tracing bugs more difficult.
Vague, but admittedly it just "smells" bad to me.
I'm not saying I'm right. I just want to understand why the community chooses this method and if there is good reason for me to change.
Edit:
References to #E-Rock in comments are to me(Eric G). I changed my display name.
One problem is what Ken White wrote: you hand the user of the function an object he or she must free.
Another advantage of procedures is that you can pass several objects of a hierarchy, while a function that creates such an object always generates the same. E.g.
procedure PopulateStrings(Strings: TStrings);
To that procedure, you can pass any kind of TStrings, be it the Lines of a TMemo, the Items of a TListBox or TComboBox or a simple standalone TStringList. If you have a function:
function CreateStrings: TStrings;
You always get the same kind of object back (which object exactly is not known, as TStrings is abstract, so you probably get a TStringList), and must Assign() the contents to the TStrings you want to modify. The procedure is to be preferred, IMO.
Additionally, if you are the author of the function, you can't control whether the object you create is freed, or when. If you write a procedure, that problem is taken off your hands, since the user provides the object, and its lifetime is none of your concern. And you don't have to know the exact type of the object, it must just be of the class or a descendant of the parameter. IOW, it is also much better for the author of the function.
It is IMO seldom a good idea to return an object from a function, for all the reasons given. A procedure that only modifies the object has no dependency on the object and creates no dependency for the user.
FWIW, Another problem is if you do that from a DLL. The object returned uses the memory manager of the DLL, and also the VMT to which it points is in the DLL. That means that code that uses as or is in the user code does not work properly (since is and as use the VMT pointer to check for class identity). If the user must pass an object of his, to a procedure, that problem does not arise.
Update
As others commented, passing an object to a DLL is not a good idea either. Non-virtual functions will call the functions inside the DLL and use its memory manager, which can cause troubles too. And is and as will not work properly inside the DLL either. So simply don't pass objects into or out of a DLL. That goes with the maxime that DLLs should only use POD type parameters (or compound types -- arrays, records -- that only contain POD types) or COM interfaces. The COM interfaces should also only use the same kind of parameters.
Creating the object instance and passing it into another procedure makes it clear which code is responsible for freeing the instance.
In the first case (using a procedure to fill it):
MyObj := TMyObject.Create;
try
// Do whatever with MyObj
finally
MyObj.Free;
end;
This is clear that this block of code is responsible for freeing MyObj when it's finished being used.
MyObj := CreateMyObject(DBID);
What code is supposed to free it? When can you safely free it? Who is responsible for exception handling? How do you know (as a user of someone else's code)?
As a general rule, you should create, use, and free object instances where they're needed. This makes your code easier to maintain, and definitely makes it easier for someone who comes along later and has to try and figure it out. :)
I use a combination of both idioms. Pass the object as an optional parameter and if not passed, create the object. And in either case return the object as the function result.
This technique has (1) the flexibility of the creation of the object inside of the called function, and (2) the caller control of the caller passing the object as a parameter. Control in two meanings: control in the real type of the object being used, and control about the moment when to free the object.
This simple piece of code exemplifies this idiom.
function MakeList(aList:TStrings = nil):TStrings;
var s:TStrings;
begin
s:=aList;
if s=nil then
s:=TSTringList.Create;
s.Add('Adam');
s.Add('Eva');
result:=s;
end;
And here are three different ways to use it
simplest usage, for quick and dirty code
var sl1,sl2,sl3:TStrings;
sl1:=MakeList;
when programmer wants to make more explicit ownership and/or use a custom type
sl2:=MakeList(TMyStringsList.create);
when the object is previously created
sl3:=TMyStringList.Create;
....
MakeList(sl3);

Using another forms event procedure

Is there any way to allow one form to use the event procedures from another form?
E.g. I have a form called PongForm and another called ObstPongForm. There is a ticker on PongForm and another one on ObstPongForm. Is it possible to get ObstPongForm to use the code from PongForm's 'tick' event in it's own 'tick' event? Maybe by letting ObstPongForm inherit from PongForm?
You can simply assign it by code (as long as you have access to both instances):
ObstPongForm.Ticker.OnTick := PongForm.TickerTick;
Yes, forms are just classes like any other, and Delphi supports visual inheritance, so you can call inherited methods normally.
If ObstPongForm is a specialized version of PongForm then inheritance makes sense, but be careful as ObstPongForm will inherit all visual controls from the PongForm, including whatever you may add in the future.
Also since I assume you already have both forms, making one inherit from another is doable but requires some manual DFM editing, mainly changing the
Object ObstPongForm: TObstPongForm
to
Inherited ObstPongForm: TObstPongForm
If the code you want to reuse may be needed in several unrelated forms, then moving the code to a common unit used by these forms may be the best solution
It would be better style to have both of the forms call another class that implements the logic used by both. If you're writing all your program logic in your OnTimer event handler, you're heading down a bad road that many delphi programmers take years to realize was a bad idea
So one form needs to call your method, it does it like this:
procedure TForm1.DoSomething;
begin
DataModule1.LogicMethod;
end;
Elsewhere there is a timer...
procedure TForm2.Timer1Timer(Sender:TObject);
begin
DataModule1.LogicMethod;
end;
And then the method itself:
procedure TDataModule1.LogicMethod;
begin
// Everything that you used to have in Timer1Timer goes here, except the setting of
// UI properties in Form1 which is kept in Form1:
Inc(FCounter);// stupid example.
//
if Assigned(FOnResults) then
FOnResults(Self, FCounter, FDataObject1);
// Form2 is connected to FOnResults event, and stores the
// result in the UI somewhere.
end;
Event handlers are just normal procedures. If your ObstPongForm tick handler has additional code that it needs to run in addition to the PongForm's code, then you can call the PongForm's tick handler manually when needed, eg:
uses
..., PongForm;
procedure ObstPongForm.TickHandler(Sender: TObject);
begin
...
PongForm.TickHandler(Self);
...
end;

Register a New Class in runtime using Delphi

Is possible create (register) a new class in runtime using delphi.
I have a Class called TMyForm, is possible create a new form derived from TMyForm but with new class type.
i want something like this
var
Myform : TMyForm;
MyFormClassBase : TFormClass;
begin
MyFormClassBase := TFormClass(RegisterMyNewClass('TMyNewClass'));//obviously RegisterMyNewClass does not exist
Myform := MyFormClassBase.Create(Application);
Myform.Show;
end;
i am using delphi 7
UPDATE 1
I dont look create a new instance of the same base class, i need create an new class type in runtime derived from another class.
UPDATE 2
Thank you very much for your interest. but the purpose is a bit complex to explain (because my bad english). I have a form that allows you to edit multiple master data tables, all these tables have the same fields code (an integer primary key) and description (a varchar field), they serve to define currencies, countries, projects, groups, etc.
as logic is the same for all these tables, so only need this form by passing as parameters the title of the table name , to manage these tables. something like this
FormCurrency:= TMyForm.Create( 'Define currencys', 'CURRENCYTABLE')
if ValidateAccess(FormCurrency) then
FormCurrency.Show
else
FormCurrency.Close;
FormGroups:= TMyForm.Create( 'Define Groups', 'GROUPSTABLE')
if ValidateAccess(FormGroups) then
FormGroups.Show
else
FormGroups.Close;
on the other hand I have a validation method (called ValidateAccess) that validates the users access to the forms using the form's class . because of this if you use the same kind of form is restricted access to all the options like "define groups","define currencys", "define countrys" (which I do not want that to happen), because that i need to pass to the ValidateAccess method a diferent class.
I cannot rewrite the ValidateAccess method because exist many diferents forms already registered in the system.
I dont want create a new form type and a new unit over and over just changing the title and the table to use.
Thanks in Advance.
I don't know if I get you right, but what I understand can be achieved in this way:
type
TCurrencyForm = class(TMyForm);
TGroupsForm = class(TMyForm);
FormCurrency:= TCurrencyForm.Create( 'Define currencys', 'CURRENCYTABLE')
if ValidateAccess(FormCurrency) then
FormCurrency.Show
else
FormCurrency.Close;
FormGroups:= TGroupsForm.Create( 'Define Groups', 'GROUPSTABLE')
if ValidateAccess(FormGroups) then
FormGroups.Show
else
FormGroups.Close;
In your ValidateAccess method (assuming the parameter is named Form) you can check something like:
if Form is TCurrencyForm then
else if Form is TGroupsForm then
If you don't have access to the new form class declarations you can use Form.ClassName instead.
It looks like Uwe managed to solve your problem. I should just state for the record that it is possible to add new class types at runtime. Classes are defined by their class reference, which is a pointer to a VMT (Virtual Method Table), and if you know how VMTs are laid out you can create one of your own. I did a session on it at CodeRage last year. Unfortunately, the audio quality sucked. :(
Of course, this isn't much use to you unless you have to create classes whose definition is not available at compile time, for example if you're using a scripting engine. When all the information you need is available at compile time, go with something like what Uwe described.
Why do you need to create a new subclass of the form? You cannot change anything about that new class to make it different from the existing class at runtime. i.e. you cannot add new methods or properties.
I suspect that you have made the mistake of thinking that one form class can have only one instance. But this is not the case. You can create as many instances of a form as you wish:
var
formA : TMyForm;
formB : TMyForm;
begin
formA := TMyForm.Create(Application);
formB := TMyForm.Create(Application);
formA.Show;
formB.Show;
end;
If this isn't what you require, you will need to provide more information about just what exactly it is you are trying to achieve.
IIUC, you can have something like this:
TmyForm = class... //your normal form
...
public
property Title: string read FTitle write SetTitle;
property FormKind: TFormKind read FFormKind write SetFormKind;
function ValidateAccess: boolean;
...
end;
Where TFormKind = (fkCurrency, fkCountry, ...);
And in your SetTitle will also set the form's caption, in your SetFormKind you will do your coressponding initialization(s) if necessary whereas in ValidateAccess you will handle (most probably in a case) the different situations according to the value of FFormKind.
And to use it:
myForm:=TmyForm.Create(Application); //since we'll free it the owner can be also 'nil'
myForm.Title:='Boo!';
myForm.Kind:=fkCurrency;
if myForm.ValidateAccess then
myForm.ShowModal; //btw your 'if' structure is a little bit 'odd' to say at least. You don't need to call Close on a form which isn't showing
myForm.Free; //get rid of it. - of course this applies if we created it. Not applicable if you use 'Show' only, of course.
However perhaps you'll find better to separate the layers and have a different class to handle the validation, according to the form's properties etc.
Delphi is a 'static' language, so you cannot create a new type (or class) at run time. You can do this in some 'dynamic' languages, like Python.
If you are trying to create a new form, populated with different controls, you can do this, but you need to create each individual control, make the form it's parent (and owner) and set it's position and caption etc.
procedure TForm1.Button1Click(ASender: TObject);
var
LForm: TForm;
LLabel: TLabel;
begin
LForm := TForm.Create(nil);
try
LForm.Width := 100;
LForm.Height := 100;
LLabel := TLabel.Create(LForm);
LLabel.Parent := LForm;
LLabel.Caption := 'Hello World!';
LForm.ShowModal;
finally
FreeAndNil(LForm);
end;
end;
I have similar problem, and find some runtime solution.
Only request is that MyForm already created in runtime.
var vOldForm,vNewForm:TObject;
begin
vOldForm:=Application.FindComponent('MyForm');
If vOldForm<>nil then
vNewForm:=TFormClass(vOldForm.ClassType).Create(Application);
If vNewForm is vOldForm.ClassType then (vNewForm as TForm).Show;
end;

Does Delphi call inherited on overridden procedures if there is no explicit call

Does Delphi call inherited on overridden procedures if there is no explicit call in the code ie (inherited;), I have the following structure (from super to sub class)
TForm >> TBaseForm >> TAnyOtherForm
All the forms in the project will be derived from TBaseForm, as this will have all the standard set-up and destructive parts that are used for every form (security, validation ect).
TBaseForm has onCreate and onDestroy procedures with the code to do this, but if someone (ie me) forgot to add inherited to the onCreate on TAnyOtherForm would Delphi call it for me? I have found references on the web that say it is not required, but nowhere says if it gets called if it is omitted from the code.
Also if it does call inherited for me, when will it call it?
No, if you leave the call to inherited away, it will not be called. Otherwise it would not be possible to override a method and totally ommit the parent version of it.
It is worth mentioning that not calling inherited in Destroy of any object can cause memory leaks. There are tools available to check for this in your source code.
The inherited call has to be made explicitly. In general no language automatically calls the inherited function in equivalent situations (class constructors not included).
It is easy to forget to make the inherited call in a class constructor. In such a situation if a base class needs to initialize any data you have an access violation waiting to happen.
Perhaps you could override DoCreate and DoDestory in your TBaseForm class so you could ensure some code is executed regardless of the implementation of child classes.
// interface
TBaseForm = Class(TForm)
...
Protected
Procedure DoCreate(Sender : TObject); Override;
End
// implementation
Procedure TBaseForm.DoCreate(Sender : TObject);
Begin
// do work here
// let parent call the OnCreate property
Inherited DoCreate(Sender);
End;
Inherited must be explicitly called in descendant objects as well as in visual form inheritance. If you use class completion then it adds inherited automatically if you flagged the definition as override (but not for reintroduce). If you are using visual form inheritance then when you add a new event hander through the form editor then it will add inherited as well.
The inherited code is not called implicitly, as the others have indicated. You must call it explicitly. This gives you some useful flexibility. For instance, you might want to do some preprocessing code prior to the inherited code, then do some post processing code afterwards. This might look like:
procedure TMyCalcObject.SolveForX;
begin
ResetCalcState;
inherited SolveForX;
PostProcessSolveForX;
end;
You must call it explicitly. This allows a lot of flexibility, since you can choose at which point in code to call the inherited method. But it's also a big source of bugs. It's easy to forget to call the inherited function and compiler has no way to tell if you did it deliberately or you just forgot.
There should be some kind of directive "skip_inherited" to tell compiler that you don't want to call the inherited method.
Compiler would then easily report error if it didn't find either "inherited" or "skip_inherited". That would mean you forgot. But unfortunately nobody in CodeGear thought of that.
No. That's the whole point of overriding.

Resources