Delphi coding hints and tips.

Unit friendly variables

If two classes are defined in the same unit they many access each others private variables without having to use a public property declaration. All classes declared in the same unit are considered to be 'friendly' so can 'see inside' each other. Or put another way all fields and methods of class in a unit are public within the same unit.

Below is an example of this. One class TPrivateVars has some private variables and procedure. Then within the second class TAccessPrivate it creates and instance of the TPrivateVars class and then accesses it private parts.

unit Unit2;

interface 

type
  TPrivateVars=class(TObject) 
    private 
      FStr:string; 
      FInt:Integer; 
      procedure Priv; 
    protected 
    public 
    end; 

  TAccessPrivate=class(TObject) 
    private 
      FPrivateVars:TPrivateVars; 
    protected 
    public 
      constructor Create; 
      destructor Destroy; override; 

    end; 

implementation 

procedure TPrivateVars.Priv; 
begin 
end; 

constructor TAccessPrivate.Create; 
begin 
{create instance of TPrivateVars} 
FPrivateVars:=TPrivateVars.Create; 
{now write directly to its private vars} 
FPrivateVars.FStr:=''; 
FPrivateVars.FInt:=0; 
{now call private method} 
FPrivateVars.Priv; 
end; 

destructor TAccessPrivate.Destroy; 
begin 
FPrivateVars.Free; 
inherited Destroy; 
end; 

end.

If you now split these two classes up into separate units you would get compiler errors - undeclared identifier for the lines access the private vars and proc.

If you hack your way into the VCL source you will find its uses 'unit friendly variables' quite a lot.