Recently prolific Delphi writer Nick Hodges declared a war on the use of nil pointers. It is arguable whether nil pointers usage is bad or not, but the point is the “Guard Pattern” proposed is really an antipattern. Here is a simple demo:
program Project11; {$APPTYPE CONSOLE} uses SysUtils, Classes; type TMyClass = class private FList: TStringList; public constructor Create(AList: TStringList); destructor Destroy; override; end; constructor TMyClass.Create(AList: TStringList); begin if AList = nil then begin raise Exception.Create('Don''t you dare pass me a nil reference!); end; FList:= AList; FList.Add('TMyClass instance created'); end; destructor TMyClass.Destroy; begin FList.Add('TMyClass instance destroyed'); inherited Destroy; end; procedure Test; begin TMyClass.Create(nil); end; begin try Test; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
If you understand how exceptions raised in a constructor work you see that the above code raises 2 exceptions: the first is the “wanted” exception in the constructor, the second is the “unwanted” access violation in the destructor.
The moral is: if you raise an exception in a constructor be very careful when writing the destructor, cause you need to treat a case of improperly initialized instance.