Expose Legacy Units

Expose identifiers from other units through a new unit

Sometimes you need to re-export and expose identifiers from another unit within your new current unit. The end result: as long as you reference this new unit, you can directly access those identifiers.

Applicable Scenarios:

  1. Maintain compatibility with older unit versions and preserve legacy calling syntax;
  2. Encapsulate low-level internal units and hide underlying implementation files from external callers.

Implementation Method: Inside the interface section of the current unit, redefine identical-named / alias identifiers to forward types and constants from underlying units.

Modify MyUnit.pas

unit MyUnit;
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}

interface
uses Graphics;

type
  // Method 1: Create an alias, expose Graphics.TColor externally as TMyColor
  TMyColor = TColor;

  // Method 2: Expose using the original name; unit qualifier Graphics. is mandatory to avoid circular self-references
  TColor = Graphics.TColor;

const
  // Constants also support forwarding exposure
  clYellow = Graphics.clYellow;
  clBlue = Graphics.clBlue;

implementation

end.Code language: JavaScript (javascript)

Full Example

unit MyUnit;
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}

interface
uses Graphics;

type
  // 1 Graphics.TColor type alias TMyColor
  TMyColor = TColor;

  // 2 Expose original name
  // qualify with Graphics. to prevent self-loop.
  TColor = Graphics.TColor;

const
  // Constants support  too.
  clYellow = Graphics.clYellow;

implementation

end.Code language: PHP (php)

Main Program

program showcolor;
{$ifdef FPC} {$mode objfpc}{$H+}{$J-} {$endif}

uses MyUnit;
var
  C1: TMyColor;
  C2: TColor;

begin
  C1 := clYellow;
  C2 := clYellow;
end.
Code language: PHP (php)

In the main program, we use the renamed identifiers defined inside MyUnit.

Leave a Reply

Your email address will not be published. Required fields are marked *