InstanceClass.NewInstance vs InstanceClass.Create
delphi, oop, vcl
Solution
I would always use `InstanceClass.Create` if it is appropriate – and invariably it is.
There are plenty of reasons. A very good one is that the single line version is more concise. Another is that the single line version is the standard, commonly used approach.
Yet another reason is the handling of exceptions in the constructor which your method 1 does not manage correctly. In case of an exception, the new instance will be destroyed, but the instance variable has still been assigned to. That's an important difference from method 2 and goes against all the lifetime management conventions of Delphi.
You mention `TApplication.CreateForm`. Let's take a look at it:
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;
try
Instance.Create(Self);
except
TComponent(Reference) := nil;
raise;
end;
Remember that `Reference` is the form variable that you pass as a `var` parameter. The point about this is this code assigns that form variable before calling the constructor. Normally that assignment is only made after the constructor completes.
Presumably this is so that code which references the form variable (often a global variable) can work even if it is invoked from inside that form's constructor. This is a very special case and is overwhelmingly the exception rather than the rule. Don't let this special case drive your mainstream coding style.
Problem
what different between InstanceClass.NewInstance+Instance.Create and InstanceClass.Create; Method1: ``` Instance := TComponent(InstanceClass.NewInstance); Instance.Create(Self); ``` Method2: ``` Instance := InstanceClass.Create(Self); ``` Which is better?