When writing a program, the main reason for using routines is to isolate assignments. This allows you to effectively troubleshoot problems when they arise. When using routines in a program, we saw that the order of declaring them was important. For example, you cannot call a routine that has not been declared yet. For this reason, whenever you need to call it, you should find out where it was created or whether it has been declared already. If the program is using many routines, it would become cumbersome to start looking for them. At the same time, on a large program, it is usual for many routines to use the same kind of variable. To make these routines easily manageable, you can create a source file where you would list them. Such a file is called a unit and it has the pas extension.
A unit file has the following structure: |
unit Unit1;
interface
implementation
end.
The source file starts with the unit keyword. This keyword lets the compiler know that this source file is a unit. The unit keyword must be followed by a name for the file. When you add a new unit to your project, Delphi gives it a default name. If it is the first unit, it would be called unit1, the second unit would be called unit2, etc. If you want to change the name of the unit, you must save it. This would prompt you to specify a name for the unit. When naming a unit, you must use a unique unit name in the project: two units must not have the same name in the same project. The name of the unit is followed by a semi-colon.
Under the unit line, a section with the interface keyword starts. In this section, you can declare variables, constants, enumerators, types, procedures, functions, and other objects such as classes we will study eventually. Although the routines are declared for later implementation, you do not have to type the forward keyword on their declaration. Their presence in the interface section indicates already that they will be implemented later on.
At the end of the interface section, you start a new section with the implementation keyword. In this section, you can implement the routines declared in the interface section. You can also use the variables, constants, and other objects declared in the previous section.
Here is an example of a simple unit file: |
unit Unit1;
interface
Function AddTwoNumbers : Double; forward;
function GetNumber : Double; forward;
implementation
Function AddTwoNumbers : Double;
var
Number1 : Double;
Number2 : Double;
begin
Number1 := GetNumber;
Number2 := GetNumber;
Result := Number1 + Number2;
end;
function GetNumber : Double;
var Nbr : Double;
begin
Write('Enter Number: ');
Readln(Nbr);
Result := Nbr;
end;
end.
|
|