Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Units and Object Pascal

Interface and Implementation Sections

Learn how a Pascal unit hides its details, why private state belongs in the implementation section, and how to break circular unit dependencies safely.

The most important idea in a Pascal unit is the split between what it promises (the interface section) and how it keeps the promise (the implementation section). Callers see only the promise. You can rewrite the how as often as you like, as long as the promise holds.

This is encapsulation at the module level, and it is available long before you write your first class. A well-made unit works like a sealed box: a few labeled buttons on the outside, all the wiring hidden inside.

What goes where

The interface section may contain:

  • routine headings (without bodies),
  • types, constants, resource strings and variables,
  • its own uses clause.

The implementation section contains:

  • the bodies of every routine declared in the interface,
  • extra helper routines, types, constants and variables that are private to the unit,
  • its own uses clause.

Here is a stack of integers. Callers can push, pop and check emptiness, but they cannot reach the array or the counter:

PASCAL
unit IntStack;

interface

procedure Push(Value: Integer);
function Pop: Integer;
function IsEmpty: Boolean;

implementation

const
  MaxItems = 100;

var
  Items: array[1..MaxItems] of Integer;
  Count: Integer = 0;

procedure Push(Value: Integer);
begin
  if Count = MaxItems then
    raise Exception.Create('Stack is full');
  Inc(Count);
  Items[Count] := Value;
end;

function Pop: Integer;
begin
  if Count = 0 then
    raise Exception.Create('Stack is empty');
  Result := Items[Count];
  Dec(Count);
end;

function IsEmpty: Boolean;
begin
  Result := Count = 0;
end;

end.

A program that uses IntStack cannot write Count := 5 or touch Items: the compiler reports an undeclared identifier. That protects the invariant "Count equals the number of stored items". If you later replace the array with a dynamic list, nothing outside the unit changes.

Compare with C: the interface section plays the role of a header file (.h), and implementation plays the role of the .c file. The difference is that Pascal keeps both in one file and the compiler checks that they agree, so you never have a header that has drifted from its source.

Headings must match

For each routine in the interface, the implementation must repeat the heading with the same parameter types and result type. Delphi lets you omit the parameter list in the implementation if it is exactly the same, but writing it in full is clearer and is what most style guides ask for. A routine declared in the interface and never implemented is an error: "Unsatisfied forward or external declaration".

Routines declared only in the implementation must come before their first use, or be introduced with forward;. They are invisible to outsiders.

A stand-in: the opaque type

C cannot hide a variable inside a block the way a unit does, but it can get close with static. The runnable program below behaves like IntStack. The part above the comment line is the "interface"; the part below is the "implementation". Because the array and counter are static, no other file could reach them.

C Stand-in: IntStack with a hidden array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Pascal raises an Exception in the same spots; here we print and exit so the program stays short.

Uses in the interface vs the implementation

Both sections may have their own uses clause. The rule of thumb: put a unit in the interface uses only if the interface itself needs it, for example a procedure heading that mentions a type from that unit. Everything else goes in the implementation uses.

PASCAL
unit Invoices;

interface

uses
  Customers;               // needed: TCustomer appears below

procedure Print(const Who: TCustomer);

implementation

uses
  System.SysUtils, Logger; // only the bodies use these

procedure Print(const Who: TCustomer);
begin
  Log(Format('Printing invoice for %s', [Who.Name]));
end;

end.

This keeps the dependency graph small, which speeds up compiles: when Logger changes, only the implementation of Invoices is affected, not the units that use Invoices.

Breaking circular references

Pascal does not allow two units to name each other in their interface uses clauses: the compiler would need each one finished before the other can start. It is allowed in the implementation sections, because by then each unit's interface is already known.

flowchart LR
  A["Orders<br/>(interface)"] -- "interface uses" --> B["Customers<br/>(interface)"]
  B -. "implementation uses: allowed" .-> A
  B -- "interface uses: circular error" --x A

Moving one uses from the interface to the implementation resolves most circular errors.

If both interfaces really need each other's types, you have found a design problem. Typical fixes are to move the shared type into a third unit that both use, or to program against an interface type (see interfaces and exceptions).

Global state is allowed, but be careful

The var in IntStack is a unit-level (global) variable. Because only the unit's routines touch it, the damage is contained, but it also means there is exactly one stack in the whole program. When you need several, you want a type: a record or a class (see classes and objects). Unit-level variables are best for true singletons such as a log file or a configuration cache.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A variable is declared only in the implementation section. Who can use it?

    Implementation-only declarations are private to the unit, which is how a unit protects its internal state.
  2. 2. Two units both list each other in their INTERFACE uses clauses. What happens?

    Interface sections must be complete before another unit can use them, so interface-level cycles are rejected. Implementation-level uses may be circular.
  3. 3. Where should you put a unit in uses if only a routine body needs it?

    Keeping it in the implementation uses clause reduces recompiles and avoids circular-reference problems.
  4. 4. Which C construct is closest to an implementation-only variable?

    A file-scope static has internal linkage: only that source file can see it.

Summary

  • interface is the public promise; implementation holds bodies and private helpers.
  • Hiding state behind routines lets you change the internals without breaking callers.
  • Put units in the implementation uses unless the interface itself needs them.
  • Interface-level circular references are errors; implementation-level ones are allowed.
  • Use a type (record or class) when you need more than one instance of some state.

Next: Initialization and Finalization