The creator of TDataModule is "created" without. Create, but no problem?

I suddenly noticed the TDataModuleTestExchange(nil) 'constructor in our code base:

 procedure TDialoogConfigExchange.ButtonTestClick(Sender: TObject); var lDataModuleTestExchange: TDataModuleTestExchange; lResult : Boolean; begin inherited; [snip] begin lDataModuleTestExchange := TDataModuleTestExchange(nil); // *** HERE *** try lResult := lDataModuleTestExchange.GetCalendarFolder(EditHost.Text,EditGebruiker.Text,EditWachtwoord.Text); if lResult then ToonMelding(sExchangeTestGelukt, mtInformation, [mbOk]) else ToonMelding(Meldingen.Text, mtError, [mbOK]); finally lDataModuleTestExchange.Free; end; end; end; 

So instead of TDataModuleTestExchange.**Create**(nil) this works fine!

 unit dmTestExchange; interface uses System.SysUtils, System.Classes, Xml.XMLDoc, Xml.XMLIntf, Xml.XMLDOM, TimeTellDM; type TDataModuleTestExchange = class(TTimeTellDataModule) // TDataModule descendant private public function GetCalendarFolder(const AExchangeServerURL,AExchangeLoginName,AExchangePass: String): Boolean; end; 

There is no compiler error, no runtime problems. Why?

+7
constructor delphi delphi-xe2 datamodule
source share
1 answer

First of all, it is worth noting that casting is false and serves no purpose but to confuse. The code is equivalent to:

 lDataModuleTestExchange := nil; 

TDataModuleTestExchange.GetCalendarFolder is an instance method, and you call it using the nil link. This will result in a run-time error if the method tries to access any fields of the instance or call virtual methods or, indeed, everything that depends on the instance. Thus, it seems likely that the implementation of TDataModuleTestExchange.GetCalendarFolder is instance-independent. Although you seem to be shying away from this here, this is clearly a very bad form for writing code like this.

The class should probably be rewritten to declare a static class as follows:

 type TDataModuleTestExchange = class(TTimeTellDataModule) public class function GetCalendarFolder(const AExchangeServerURL, AExchangeLoginName, AExchangePass: string): Boolean; static; end; 

Then it is called like this:

 lResult := TDataModuleTestExchange.GetCalendarFolder(EditHost.Text, EditGebruiker.Text, EditWachtwoord.Text); if lResult then ToonMelding(sExchangeTestGelukt, mtInformation, [mbOk]) else ToonMelding(Meldingen.Text, mtError, [mbOK]); 
+5
source share

All Articles