1
votes

I am using Delphi XE3. Currently there are too many functions in my unit, and one of them is very long. So I want to put that long function to another unit. Is that possible?

I try as follows:

Unit1:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Test;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
...

Unit2:

unit Unit2;

interface

implementation

uses Unit1;

procedure TForm1.Test;
begin
end;

end.

But compile fails, said "[dcc32 Error] Unit1.pas(16): E2065 Unsatisfied forward or external declaration: 'TForm1.Test'"

2
No, this is not possible. Needing to do so is probably an indication that you're putting too much functionality into the UI code rather than separating it out properly. You may want to consider a redesign and then refactoring.Ken White

2 Answers

2
votes

You cannot move a class method's implementation to another unit. However, you can refactor its inner code into its own function in another unit, and then call that function from your class method, eg:

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    procedure Test;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  Unit2;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Test;
end;

procedure TForm1.Test;
begin
  Unit2.DoTest;
end;

end.
unit Unit2;

interface

procedure DoTest;

implementation

procedure DoTest;
begin
  ...
end;

end.
1
votes
  1. Functions belonging to the same class must be in one unit (your error reason)
  2. your declaration and implementation must be in the same unit
  3. if you want to split it up, you need to make them be in different classes