Recent

Author Topic: [solved] Aborting construction of object  (Read 2710 times)

DimProfi

  • Full Member
  • ***
  • Posts: 126
    • http://www.dimprofi.de
[solved] Aborting construction of object
« on: April 09, 2013, 05:46:11 am »
Is there a possibility to abort object construction and return nil without using exceptions in this theoretical way:

Code: [Select]
type
  TObjectA=class
      constructor Create(filename:string);
  end;

constructor TObjectA.Create(filename:string);
begin
  if not FileExists(filename) then
  begin
     Result:=nil;
     exit;
  end;

  Result:=inherrited Create();
end;

Code: [Select]

  obj:=TObjectA.Create('C:\test.db');

  if not assigned(obj) then
  begin
     showmessage('Database could not be accessed!');
     exit;
  end;

   obj.getData();
   ...
   obj.Free;

May be I'm a bit crazy  ;)

The only alternative would be an object factory, which creates objects and returning it, if object initialization successful.


P.S.: I dont like using exceptions because they can appeare everywhere in a constructor or destructor or in a block of handling other exception.

« Last Edit: April 09, 2013, 12:27:55 pm by dimprofi »
Lazarus 1.2/FPC 2.6.4 (x86/x86_64/win32/win64/Linux) :: Be smart - use predictable {$INTERFACES CORBA}! :)

BrunoK

  • Hero Member
  • *****
  • Posts: 720
  • Retired programmer
Re: Aborting construction of object
« Reply #1 on: April 09, 2013, 10:34:11 am »
constructor TObjectA.Create(filename:string);
begin
  if not FileExists(filename) then
  begin
     FreeAndNil(Self); // Result:=nil; >>>  FreeAndNil in <uses sysutils >
     exit;
  end;

  Result:=inherited Create();
end;

Might work.

User137

  • Hero Member
  • *****
  • Posts: 1791
    • Nxpascal home
Re: Aborting construction of object
« Reply #2 on: April 09, 2013, 10:57:36 am »
This worked for me, form caption became 'Is nil'. Free would do a little unnecessary work here. Checking if it's nil at first, when it never is in constructor.
Code: [Select]
constructor TSomeObject.Create;
begin
  Destroy;
  self:=nil;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  if TSomeObject.Create=nil then caption:='Is nil';
end;

DimProfi

  • Full Member
  • ***
  • Posts: 126
    • http://www.dimprofi.de
Re: Aborting construction of object
« Reply #3 on: April 09, 2013, 12:25:02 pm »
  self:=nil;

I thought self is read-only :)
Thanx!
Lazarus 1.2/FPC 2.6.4 (x86/x86_64/win32/win64/Linux) :: Be smart - use predictable {$INTERFACES CORBA}! :)

DimProfi

  • Full Member
  • ***
  • Posts: 126
    • http://www.dimprofi.de
Re: Aborting construction of object
« Reply #4 on: April 09, 2013, 12:27:16 pm »
  FreeAndNil(Self); // Result:=nil; >>>  FreeAndNil in <uses sysutils >

Thanx!
Gonna check with Heaptrc if all good with FreeAndNil in constructor.
Lazarus 1.2/FPC 2.6.4 (x86/x86_64/win32/win64/Linux) :: Be smart - use predictable {$INTERFACES CORBA}! :)

 

TinyPortal © 2005-2018