Draw the window, write the logic
Ask a Delphi or Lazarus developer what drew them to Object Pascal and many will describe the same experience. You open a new project and an empty window appears. You drop an edit box, a button and a label onto it, set the button's caption in a list of properties, and double-click the button. The IDE writes an empty procedure for you, you type three lines into it, press F9, and a native program with a real window is running a second later. This way of working, rapid application development, was what made Delphi famous in 1995, and it is still why companies maintain large Delphi and Lazarus applications for accounting, laboratories, factories, hospitals and engineering.
The code you write in those handlers is the Object Pascal of the last three lessons: classes and properties, events as method pointers, exceptions and generics. This final lesson shows how the pieces fit into a GUI application, which the course describes rather than runs, since the programs here are checked as console programs without a screen. It then surveys the tools professionals use, builds a complete small project in the style experienced developers recommend, with its logic separate from any user interface, and ends with where to go next.
Forms, components and the event loop
Definition— Component
A class descended from TComponent (in the Classes unit). Every component has a Name, an Owner that frees it when the owner is freed, and published properties that the IDE shows in its property editor and saves in form files. Buttons, edit boxes, timers and database connections are all components.
Definition— Form file
A text file, .lfm in Lazarus and .dfm in Delphi's VCL, that records every component on a form with the values of its published properties and the names of its event handlers. The IDE writes it as you design; at run time the application reads it and rebuilds the form.
A Lazarus application has three kinds of source file. The project file (.lpr; Delphi's is a .dpr) is the program itself, and the IDE writes it for you:
program Converter;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}cthreads,{$ENDIF}
Interfaces, { the LCL widgetset: Windows, GTK, Qt or Cocoa }
Forms, MainForm;
{$R *.res}
begin
RequireDerivedFormResource := True;
Application.Scaled := True;
Application.Initialize;
Application.CreateForm(TFormMain, FormMain);
Application.Run; { the event loop: runs until the main form closes }
end.Each form is a unit whose class descends from TForm. The IDE declares a field for every component you drop and an empty method for every event you double-click; you write the bodies:
unit MainForm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, StdCtrls;
type
TFormMain = class(TForm)
EditKm: TEdit;
ButtonConvert: TButton;
LabelResult: TLabel;
procedure ButtonConvertClick(Sender: TObject);
end;
var
FormMain: TFormMain;
implementation
{$R *.lfm}
procedure TFormMain.ButtonConvertClick(Sender: TObject);
var
Km: Double;
begin
if TryStrToFloat(EditKm.Text, Km) then
LabelResult.Caption := Format('%.2f miles', [Km / 1.609344])
else
LabelResult.Caption := 'Please type a number';
end;
end.and its form file, mainform.lfm, describes the design:
object FormMain: TFormMain
Caption = 'Distance converter'
Height = 140
Width = 320
object EditKm: TEdit
Left = 16
Top = 16
Width = 120
end
object ButtonConvert: TButton
Left = 152
Top = 16
Caption = 'Convert'
OnClick = ButtonConvertClick
end
object LabelResult: TLabel
Left = 16
Top = 64
Caption = ''
end
endThe fields and the handler sit in the first, unlabelled section of TFormMain, which for components is published, so the form loader can find them by name. {$R *.lfm} links the form file into the executable. When Application.CreateForm runs, it creates the form, reads the form file, creates each component with the form as its owner, sets its properties, and connects OnClick = ButtonConvertClick to the method of that name. Then Application.Run waits for the operating system to report mouse clicks, key presses and repaints, and turns each into a call to the right handler. Nothing in your code calls ButtonConvertClick; the event loop does.
The component libraries differ by tool. Lazarus's LCL draws native controls through a widgetset: the Windows API on Windows, GTK or Qt on Linux, and Cocoa on macOS, so one source compiles to a native application on each. Delphi has two: the VCL, a thin and fast layer over Windows's own controls, used by most long-lived Delphi applications, and FireMonkey (FMX), which draws its own controls and targets Windows, macOS, iOS and Android as well. The LCL was designed to resemble the VCL closely, and Lazarus can convert many Delphi VCL projects, but the two are not identical.
What the designer and the event loop do
None of the GUI libraries can run where this course's programs are checked, but the machinery underneath is ordinary Object Pascal from the Classes and TypInfo units. This program builds a miniature widget set and form, connects the button's event by name, exactly as a form file does, and then plays a short sequence of user actions through a simple event loop:
program MiniForms;
{$mode objfpc}{$H+}
uses
SysUtils, Classes, TypInfo;
type
{ A miniature widget set, just enough to show how the LCL and VCL work. }
TEdit = class(TComponent)
public
Text: string;
end;
TLabel = class(TComponent)
public
Caption: string;
end;
TButton = class(TComponent)
private
FOnClick: TNotifyEvent;
public
procedure Click;
published
property OnClick: TNotifyEvent read FOnClick write FOnClick;
end;
{ The form you would design in Lazarus: three controls and one handler. }
TFormMain = class(TComponent)
published
EditKm: TEdit;
ButtonConvert: TButton;
LabelResult: TLabel;
procedure ButtonConvertClick(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
end;
procedure TButton.Click;
begin
if Assigned(FOnClick) then
FOnClick(Self); { call whatever handler was assigned }
end;
constructor TFormMain.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
{ The form owns its controls, so freeing the form frees them. }
EditKm := TEdit.Create(Self);
EditKm.Name := 'EditKm';
ButtonConvert := TButton.Create(Self);
ButtonConvert.Name := 'ButtonConvert';
LabelResult := TLabel.Create(Self);
LabelResult.Name := 'LabelResult';
end;
procedure TFormMain.ButtonConvertClick(Sender: TObject);
var
Km: Double;
begin
if TryStrToFloat(EditKm.Text, Km) then
LabelResult.Caption := Format('%.2f miles', [Km / 1.609344])
else
LabelResult.Caption := 'Please type a number';
WriteLn(' ', (Sender as TComponent).Name, ' clicked; label shows "', LabelResult.Caption, '"');
end;
{ What loading a form file does for "OnClick = ButtonConvertClick":
find the component and the published method by name, then set the event. }
procedure WireEvent(Form: TComponent; const Control, Event, Handler: string);
var
M: TMethod;
begin
M.Code := Form.MethodAddress(Handler);
M.Data := Form;
if M.Code = nil then
raise Exception.CreateFmt('no published method "%s"', [Handler]);
SetMethodProp(Form.FindComponent(Control), Event, M);
end;
const
{ The user's actions, as an event loop would receive them. }
Events: array[1..4] of string =
('type EditKm 42.195', 'click ButtonConvert', 'type EditKm ten', 'click ButtonConvert');
var
Form: TFormMain;
E: string;
Parts: TStringArray;
begin
Form := TFormMain.Create(nil);
try
WireEvent(Form, 'ButtonConvert', 'OnClick', 'ButtonConvertClick');
WriteLn('Form owns ', Form.ComponentCount, ' components');
for E in Events do { the event loop }
begin
Parts := E.Split([' ']);
if Parts[0] = 'type' then
(Form.FindComponent(Parts[1]) as TEdit).Text := Parts[2]
else if Parts[0] = 'click' then
(Form.FindComponent(Parts[1]) as TButton).Click;
end;
finally
Form.Free; { frees the edit, button and label too }
end;
end.It prints:
Form owns 3 components
ButtonConvert clicked; label shows "26.22 miles"
ButtonConvert clicked; label shows "Please type a number"Three mechanisms from real GUI libraries are at work here.
- Ownership. Each control is created with
Create(Self), making the form its owner.TComponentkeeps a list of what it owns (henceComponentCountis 3) and frees all of it in its own destructor, so the singleForm.Freecleans up everything. In Lazarus and Delphi, the application owns the forms and the forms own their controls, which is why GUI code contains so few calls toFree. - Wiring by name.
WireEventdoes what readingOnClick = ButtonConvertClickfrom a form file does:MethodAddressfinds a published method by its name,FindComponentfinds the button by itsName, andSetMethodProp, fromTypInfo, sets the button's publishedOnClickproperty through run-time type information. This is why the IDE puts handlers in the published section, and why renaming a handler by hand without updating the form file breaks the connection. - The event loop. The
forloop stands in forApplication.Run: it takes each event and dispatches it. The handler runs to completion before the next event is processed, which is why a slow handler freezes a real application's window. Long work belongs in a background thread (TThread), which hands results back to the user interface withTThread.SynchronizeorTThread.Queue.
The professional toolchain
Most Object Pascal is written in one of two IDEs, and each has a set of companion tools. The table pairs them up:
| Task | Lazarus and Free Pascal | Delphi |
|---|---|---|
| Edit, design, debug | the Lazarus IDE, with its own debugger (FpDebug) or GDB | the RAD Studio IDE |
| Build from the command line | fpc for programs, lazbuild project.lpi for Lazarus projects | MSBuild with the .dproj file |
| Add libraries | Lazarus packages (.lpk) and the Online Package Manager | the GetIt package manager |
| Unit tests | FPCUnit, with console and GUI test runners | DUnitX |
| Formatting | JEDI Code Format, built into the IDE | the IDE's built-in formatter |
| Memory leaks | heaptrc (-gh, with -gl for line numbers) | FastMM in its full debug mode |
A Lazarus project's settings live in an XML file, project.lpi, which also defines build modes: a Debug mode with range and overflow checks, assertions, debug information and heaptrc, and a Release mode with optimisation (-O2) and smart linking (-CX -XX) to drop unused code. Continuous-integration servers run lazbuild --build-mode=Release project.lpi and the test program on every commit, often in containers with Free Pascal and Lazarus installed. Because .lfm and .dfm files are plain text, Git shows form changes as readable diffs. And because Free Pascal can cross-compile, one Linux build server can produce Windows and Linux executables of the same program.
Two more habits are worth copying. Professionals compile with all warnings and hints visible and keep their own code free of them; with every message switched on, Free Pascal 3.2.2 also reports a handful of warnings and notes from inside Generics.Collections itself, which come from the library and can be ignored. And they treat the compiler version as part of the project, recording it in the README or pinning it in the build image, since Free Pascal, Lazarus and Delphi each release on their own schedules. Community tools such as fpcupdeluxe install any combination of Free Pascal and Lazarus versions side by side for exactly this reason.
Project: a library loans service
Here is a complete small application: the lending desk of a community library. Books have codes and titles; some are reference only and never leave the building, and new arrivals go out for 7 days instead of 21. A member may hold at most three books. Late returns cost 0.20 a day, up to 5.00. The desk's commands arrive as lines of text, each starting with the date.
The program is written the way experienced developers structure a Lazarus or Delphi application. The core (the library, books, rules and errors) knows nothing about consoles or windows and would live in its own unit, loans.pas. The console front end turns lines of text into calls to the core and prints the results; a Lazarus form would be a second front end over the same core. And tests check the rules automatically. Because each checked program in this course is one file, the three parts appear here in one program, marked by comments:
program LibraryLoans;
{$mode objfpc}{$H+}
uses
SysUtils, DateUtils, Math, Generics.Collections;
{ ===== The core. In a real project: unit Loans (loans.pas), with no user interface. ===== }
type
ELibraryError = class(Exception);
ENotFound = class(ELibraryError);
ENotAvailable = class(ELibraryError);
ELimitReached = class(ELibraryError);
TBookFlag = (bfReferenceOnly, bfNewArrival);
TBookFlags = set of TBookFlag;
TBook = class
private
FCode, FTitle, FBorrower: string;
FFlags: TBookFlags;
FDue: TDate;
public
constructor Create(const ACode, ATitle: string; AFlags: TBookFlags = []);
function OnLoan: Boolean;
property Code: string read FCode;
property Title: string read FTitle;
property Flags: TBookFlags read FFlags;
property Borrower: string read FBorrower;
property Due: TDate read FDue;
end;
TLogEvent = procedure(const Msg: string) of object;
TBookList = specialize TObjectList<TBook>;
TBookIndex = specialize TDictionary<string, TBook>;
TLoanCounts = specialize TDictionary<string, Integer>;
TLibrary = class
public const
MaxLoans = 3;
StandardDays = 21;
NewArrivalDays = 7;
FinePerDay: Currency = 0.20;
MaxFine: Currency = 5.00;
private
FBooks: TBookList; { owns the books and keeps them in order }
FByCode: TBookIndex; { finds a book by its code }
FLoans: TLoanCounts; { books on loan, per member }
FFines: Currency;
FOnLog: TLogEvent;
function Find(const Code: string): TBook;
procedure Log(const Fmt: string; const Args: array of const);
public
constructor Create;
destructor Destroy; override;
procedure AddBook(ABook: TBook);
procedure Lend(const Code, Member: string; Today: TDate);
function Return(const Code: string; Today: TDate): Currency;
function LoansOf(const Member: string): Integer;
property Books: TBookList read FBooks;
property FinesCollected: Currency read FFines;
property OnLog: TLogEvent read FOnLog write FOnLog;
end;
function DateText(D: TDate): string;
begin
Result := FormatDateTime('yyyy-mm-dd', D);
end;
constructor TBook.Create(const ACode, ATitle: string; AFlags: TBookFlags);
begin
inherited Create;
FCode := ACode;
FTitle := ATitle;
FFlags := AFlags;
end;
function TBook.OnLoan: Boolean;
begin
Result := FBorrower <> '';
end;
constructor TLibrary.Create;
begin
inherited Create;
FBooks := TBookList.Create(True);
FByCode := TBookIndex.Create;
FLoans := TLoanCounts.Create;
end;
destructor TLibrary.Destroy;
begin
FLoans.Free;
FByCode.Free;
FBooks.Free; { frees every book }
inherited Destroy;
end;
procedure TLibrary.Log(const Fmt: string; const Args: array of const);
begin
if Assigned(FOnLog) then
FOnLog(Format(Fmt, Args));
end;
function TLibrary.Find(const Code: string): TBook;
begin
if not FByCode.TryGetValue(Code, Result) then
raise ENotFound.CreateFmt('no book with code %s', [Code]);
end;
procedure TLibrary.AddBook(ABook: TBook);
begin
FBooks.Add(ABook);
FByCode.Add(ABook.Code, ABook); { raises if the code is already taken }
end;
function TLibrary.LoansOf(const Member: string): Integer;
begin
if not FLoans.TryGetValue(Member, Result) then
Result := 0;
end;
procedure TLibrary.Lend(const Code, Member: string; Today: TDate);
var
Book: TBook;
begin
Book := Find(Code);
if bfReferenceOnly in Book.Flags then
raise ENotAvailable.CreateFmt('%s is for reference only', [Book.Title]);
if Book.OnLoan then
raise ENotAvailable.CreateFmt('%s is on loan until %s', [Book.Title, DateText(Book.Due)]);
if LoansOf(Member) >= MaxLoans then
raise ELimitReached.CreateFmt('%s already has %d books', [Member, MaxLoans]);
Book.FBorrower := Member;
if bfNewArrival in Book.Flags then
Book.FDue := Today + NewArrivalDays
else
Book.FDue := Today + StandardDays;
FLoans.AddOrSetValue(Member, LoansOf(Member) + 1);
Log('%s borrows %s, due %s', [Member, Book.Title, DateText(Book.Due)]);
end;
function TLibrary.Return(const Code: string; Today: TDate): Currency;
var
Book: TBook;
DaysLate: Integer;
begin
Book := Find(Code);
if not Book.OnLoan then
raise ENotAvailable.CreateFmt('%s is not on loan', [Book.Title]);
DaysLate := Trunc(Today) - Trunc(Book.Due);
Result := 0;
if DaysLate > 0 then
Result := DaysLate * FinePerDay;
if Result > MaxFine then
Result := MaxFine;
FFines := FFines + Result;
FLoans[Book.Borrower] := LoansOf(Book.Borrower) - 1;
Log('%s returns %s, %d day(s) late, fine %s',
[Book.Borrower, Book.Title, Max(DaysLate, 0), CurrToStrF(Result, ffFixed, 2)]);
Book.FBorrower := '';
end;
{ ===== The console front end. A Lazarus form would be another front end. ===== }
type
ECommandError = class(Exception);
TConsoleFrontEnd = class
private
FLibrary: TLibrary;
procedure ShowMessage(const Msg: string);
procedure ListOverdue(Today: TDate);
public
constructor Create(ALibrary: TLibrary);
procedure Execute(const Line: string);
procedure Report;
end;
constructor TConsoleFrontEnd.Create(ALibrary: TLibrary);
begin
inherited Create;
FLibrary := ALibrary;
FLibrary.OnLog := @ShowMessage; { the core reports through an event }
end;
procedure TConsoleFrontEnd.ShowMessage(const Msg: string);
begin
WriteLn(' ', Msg);
end;
procedure TConsoleFrontEnd.ListOverdue(Today: TDate);
var
Book: TBook;
begin
for Book in FLibrary.Books do
if Book.OnLoan and (Book.Due < Today) then
WriteLn(' overdue: ', Book.Title, ' (', Book.Borrower, ', due ', DateText(Book.Due), ')');
end;
{ Each line is "<date> <command> <arguments>". }
procedure TConsoleFrontEnd.Execute(const Line: string);
var
Words: TStringArray;
Today: TDate;
begin
WriteLn(Line);
try
Words := Line.Split([' ']);
if Length(Words) < 2 then
raise ECommandError.Create('expected a date and a command');
Today := ScanDateTime('yyyy-mm-dd', Words[0]);
if (Words[1] = 'lend') and (Length(Words) = 4) then
FLibrary.Lend(Words[2], Words[3], Today)
else if (Words[1] = 'return') and (Length(Words) = 3) then
FLibrary.Return(Words[2], Today)
else if (Words[1] = 'overdue') and (Length(Words) = 2) then
ListOverdue(Today)
else
raise ECommandError.CreateFmt('unknown command "%s"', [Words[1]]);
except
on E: ELibraryError do
WriteLn(' refused: ', E.Message);
on E: ECommandError do
WriteLn(' error: ', E.Message);
on E: EConvertError do
WriteLn(' error: ', E.Message);
end;
end;
procedure TConsoleFrontEnd.Report;
var
Book: TBook;
Status: string;
begin
WriteLn;
WriteLn(Format('%-4s %-30s %s', ['Code', 'Title', 'Status']));
for Book in FLibrary.Books do
begin
if bfReferenceOnly in Book.Flags then
Status := 'reference only'
else if Book.OnLoan then
Status := Format('with %s until %s', [Book.Borrower, DateText(Book.Due)])
else
Status := 'on the shelf';
WriteLn(Format('%-4s %-30s %s', [Book.Code, Book.Title, Status]));
end;
WriteLn('Fines collected: ', CurrToStrF(FLibrary.FinesCollected, ffFixed, 2));
end;
{ ===== Tests. In a real project: a separate test program using FPCUnit. ===== }
var
TestsRun: Integer = 0;
TestsFailed: Integer = 0;
procedure Check(const Name: string; Passed: Boolean);
begin
Inc(TestsRun);
if not Passed then
begin
Inc(TestsFailed);
WriteLn('FAIL: ', Name);
end;
end;
function Day(N: Integer): TDate; { day N of a fixed calendar }
begin
Result := EncodeDate(2026, 1, 1) + N;
end;
function LendRaises(Lib: TLibrary; const Code, Member: string; Expected: ExceptClass): Boolean;
begin
try
Lib.Lend(Code, Member, Day(0));
Result := False;
except
on E: Exception do
Result := E.ClassType = Expected;
end;
end;
procedure RunTests;
var
Lib: TLibrary;
begin
Lib := TLibrary.Create;
try
Lib.AddBook(TBook.Create('B1', 'Book one'));
Lib.AddBook(TBook.Create('B2', 'Book two', [bfNewArrival]));
Lib.AddBook(TBook.Create('B3', 'Book three', [bfReferenceOnly]));
Lib.AddBook(TBook.Create('B4', 'Book four'));
Lib.AddBook(TBook.Create('B5', 'Book five'));
Lib.Lend('B1', 'Sione', Day(0));
Check('standard loans last 21 days', Lib.Books[0].Due = Day(21));
Check('returning on the due date is free', Lib.Return('B1', Day(21)) = 0);
Lib.Lend('B1', 'Sione', Day(0));
Check('each late day costs 0.20', Lib.Return('B1', Day(25)) = 0.80);
Lib.Lend('B1', 'Sione', Day(0));
Check('fines stop at 5.00', Lib.Return('B1', Day(200)) = 5.00);
Lib.Lend('B2', 'Sione', Day(0));
Check('new arrivals are due in 7 days', Lib.Books[1].Due = Day(7));
Check('reference books are refused', LendRaises(Lib, 'B3', 'Ilse', ENotAvailable));
Check('a book on loan is refused', LendRaises(Lib, 'B2', 'Ilse', ENotAvailable));
Check('unknown codes are refused', LendRaises(Lib, 'Z9', 'Ilse', ENotFound));
Lib.Lend('B4', 'Sione', Day(0));
Lib.Lend('B5', 'Sione', Day(0));
Check('a fourth loan is refused', LendRaises(Lib, 'B1', 'Sione', ELimitReached));
Lib.Return('B4', Day(3));
Check('a return frees a place', Lib.LoansOf('Sione') = 2);
finally
Lib.Free;
end;
WriteLn(TestsRun - TestsFailed, ' of ', TestsRun, ' tests passed');
if TestsFailed > 0 then
ExitCode := 1; { so that a build script notices }
end;
const
Commands: array[1..13] of string = (
'2026-11-02 lend A1 Amina',
'2026-11-02 lend A2 Amina',
'2026-11-03 lend A3 Kenji',
'2026-11-03 lend A1 Kenji',
'2026-11-04 lend A4 Amina',
'2026-11-05 lend A5 Amina',
'2026-11-12 return A2',
'2026-11-12 lend A5 Amina',
'2026-11-20 lend X9 Kenji',
'2026-11-21 renew A4 Amina',
'2026-11-31 return A4',
'2026-12-01 overdue',
'2027-01-10 return A1');
var
Lib: TLibrary;
UI: TConsoleFrontEnd;
Line: string;
begin
Lib := TLibrary.Create;
UI := nil;
try
Lib.AddBook(TBook.Create('A1', 'Things Fall Apart'));
Lib.AddBook(TBook.Create('A2', 'Half of a Yellow Sun', [bfNewArrival]));
Lib.AddBook(TBook.Create('A3', 'Atlas of World History', [bfReferenceOnly]));
Lib.AddBook(TBook.Create('A4', 'The Tale of Genji'));
Lib.AddBook(TBook.Create('A5', 'Don Quixote'));
UI := TConsoleFrontEnd.Create(Lib);
for Line in Commands do
UI.Execute(Line);
UI.Report;
finally
UI.Free;
Lib.Free;
end;
WriteLn;
RunTests;
end.It prints:
2026-11-02 lend A1 Amina
Amina borrows Things Fall Apart, due 2026-11-23
2026-11-02 lend A2 Amina
Amina borrows Half of a Yellow Sun, due 2026-11-09
2026-11-03 lend A3 Kenji
refused: Atlas of World History is for reference only
2026-11-03 lend A1 Kenji
refused: Things Fall Apart is on loan until 2026-11-23
2026-11-04 lend A4 Amina
Amina borrows The Tale of Genji, due 2026-11-25
2026-11-05 lend A5 Amina
refused: Amina already has 3 books
2026-11-12 return A2
Amina returns Half of a Yellow Sun, 3 day(s) late, fine 0.60
2026-11-12 lend A5 Amina
Amina borrows Don Quixote, due 2026-12-03
2026-11-20 lend X9 Kenji
refused: no book with code X9
2026-11-21 renew A4 Amina
error: unknown command "renew"
2026-11-31 return A4
error: 2026-11-31 is not a valid date specification
2026-12-01 overdue
overdue: Things Fall Apart (Amina, due 2026-11-23)
overdue: The Tale of Genji (Amina, due 2026-11-25)
2027-01-10 return A1
Amina returns Things Fall Apart, 48 day(s) late, fine 5.00
Code Title Status
A1 Things Fall Apart on the shelf
A2 Half of a Yellow Sun on the shelf
A3 Atlas of World History reference only
A4 The Tale of Genji with Amina until 2026-11-25
A5 Don Quixote with Amina until 2026-12-03
Fines collected: 5.60
10 of 10 tests passedRead it as a review of the course, part by part.
- Types that say what they mean.
TBookFlagsis a set of an enumeration, sobfReferenceOnly in Book.Flagsreads like the rule it checks. The loan limits are class constants ofTLibrary, and money isCurrency, so 3 days at 0.20 is exactly 0.60. - Ownership is explicit.
FBooksis aTObjectListthat owns the books and keeps them in order for reports;FByCodeis aTDictionarythat only indexes them for fast lookup, and does not own them. Freeing the list frees every book exactly once. The main block creates two objects and frees them in onefinally, withUIset tonilfirst so thatFreeis safe even if the firstAddBookwere to fail. - Errors are classes. Every rule the desk enforces raises a descendant of
ELibraryError, with a message a librarian can read. The front end catches library errors, command errors and theEConvertErrorthatScanDateTimeraises for 31 November, and reports each on one line; anything else would be a bug and is allowed to stop the program. - The core talks through an event.
TLibraryreports what it did by callingOnLog, aprocedure … of object, if one is assigned. The console front end assigns a method that writes a line. A Lazarus form would assign one that adds a line to a memo, and its button handlers would call the same core:
procedure TFormLoans.ButtonLendClick(Sender: TObject);
begin
try
FLibrary.Lend(EditCode.Text, EditMember.Text, Date);
except
on E: ELibraryError do
MessageDlg(E.Message, mtWarning, [mbOK], 0);
end;
end;- Time comes in as a parameter.
LendandReturntake the date rather than reading the clock (Date, in the form above), so the demonstration and the tests can use fixed dates and always print the same thing. - Unit-level privacy, used on purpose.
TLibrarysetsBook.FBorrowerandBook.FDuedirectly. That works because plainprivateis visible throughout a unit (Lesson 6), and the two classes are meant to live in the same unit, where the library is the only code allowed to change a book's loan. Outside the unit, the fields are read-only properties.
The tests at the end use a ten-line stand-in for a framework, so that the program needs nothing beyond the run-time library. In the project itself they would be an FPCUnit test case, run by lazbuild and the FPCUnit console runner on every commit, with SetUp giving each test a fresh library:
type
TLoanTests = class(TTestCase)
private
FLib: TLibrary;
protected
procedure SetUp; override;
procedure TearDown; override;
published
procedure LateReturnCostsTwentyCentsADay;
end;
procedure TLoanTests.LateReturnCostsTwentyCentsADay;
begin
FLib.Lend('B1', 'Sione', Day(0));
AssertEquals(0.80, Double(FLib.Return('B1', Day(25))), 0.001);
end;Setting ExitCode := 1 when a test fails is what lets a build script or CI server notice: a test program that always exits with 0 checks nothing. When the fine was changed to 0.25 a day as an experiment, the program printed FAIL: each late day costs 0.20 and 9 of 10 tests passed, and exited with status 1; restoring it brought back 10 of 10 tests passed.
One source, several platforms
Lazarus's promise is "write once, compile anywhere", and Free Pascal keeps it with conditional compilation: the compiler defines symbols for the target operating system and processor, and {$IFDEF} or {$IF DEFINED(…)} choose which code is compiled at all. Build modes add symbols of their own with -d.
program Platforms;
{$mode objfpc}{$H+}
uses
SysUtils;
begin
{ Compile-time facts, written into the program by the compiler. }
WriteLn('Compiler: Free Pascal ', {$I %FPCVERSION%});
WriteLn('Target: ', {$I %FPCTARGETCPU%}, '-', {$I %FPCTARGETOS%});
WriteLn('Pointers: ', SizeOf(Pointer) * 8, ' bits');
{ Code for one platform only: the other branches are not even compiled. }
{$IF DEFINED(WINDOWS)}
WriteLn('Settings: ', GetEnvironmentVariable('APPDATA'));
{$ELSEIF DEFINED(DARWIN)}
WriteLn('Settings: ~/Library/Application Support');
{$ELSEIF DEFINED(UNIX)}
WriteLn('Settings: ~/.config, as the XDG convention says');
{$ENDIF}
{ Build modes set symbols with -d: fpc -dDEBUG main.pas }
{$IFDEF DEBUG}
WriteLn('Build: debug, with extra checks');
{$ELSE}
WriteLn('Build: release');
{$ENDIF}
{ Constants that differ by platform, so code need not guess. }
WriteLn('Line ends: ', Length(LineEnding), ' byte(s); paths use ''', PathDelim, '''');
end.It prints, on the Linux machine that checks this course:
Compiler: Free Pascal 3.2.2
Target: x86_64-Linux
Pointers: 64 bits
Settings: ~/.config, as the XDG convention says
Build: release
Line ends: 1 byte(s); paths use '/'Compiled for Windows, the same source would report x86_64-Win64 and the APPDATA folder, and compiled with fpc -dDEBUG it reported Build: debug, with extra checks. The {$I %…%} directives insert compile-time information as string constants; LineEnding and PathDelim are constants whose values depend on the target. Experienced developers keep platform-specific code small and gather it in a few routines or units, so that most of the program never needs an {$IFDEF}.
Common misunderstandings
Misconception
"The logic belongs in the button's OnClick handler." It is the quickest thing to write, and the hardest to test, reuse or move to another front end. Keep handlers to a few lines that read the controls, call the core and show the result, as ButtonLendClick does.
Misconception
"A long calculation inside an event handler is fine." While a handler runs, the event loop cannot repaint the window or respond to clicks, so the application appears frozen. Run long work in a TThread, and update controls only from the main thread, through Synchronize or Queue.
Misconception
"Lazarus opens Delphi projects as they are." The LCL resembles the VCL closely, and Lazarus has tools to convert Delphi projects and form files, but some components, units and language features differ. A shared code base is tested with both compilers, and usually keeps its core in units that use neither library.
Misconception
"Users need a runtime installed to run the program." Free Pascal and Delphi produce native executables with the run-time library linked in. A Lazarus application on Linux does use the system's GTK or Qt libraries, which desktop distributions already provide.
Where to go next
You have travelled from Wirth's teaching language to the Object Pascal of working developers: types, routines, data structures, units and memory, classes, interfaces, exceptions and generics, and now applications and their tools. Some good next steps:
- Build a real GUI application. Install Lazarus, follow the Lazarus Tutorial, and put a form in front of this lesson's library core: a grid of books, two edit boxes and two buttons.
- Read the references. The Free Pascal documentation covers the language, the compiler and the libraries in full, and Embarcadero's DocWiki does the same for Delphi, the VCL and FireMonkey. Michalis Kamburelis's free Modern Object Pascal Introduction for Programmers is a compact tour of everything this course covered and more.
- Explore what people build. The Castle Game Engine makes 2D and 3D games in Object Pascal; mORMot is a widely used framework for servers and databases; Free Pascal's own pas2js compiles Object Pascal to JavaScript for the browser; and Free Pascal targets embedded boards as well as desktops.
- Join the community. The Lazarus and Free Pascal forum and the wiki are friendly and active, and both projects welcome bug reports and contributions.
- See Pascal's descendants. Wirth's line continued through Modula-2 and Oberon, and its ideas reached many languages on this site: Ada shares Pascal's strong typing and readable syntax, Go borrowed from Oberon, and C# was designed by Delphi's own chief architect, Anders Hejlsberg.
Optional Christian reflection · Faithful in small things
A reflection from the Christian tradition that inspires Lumenary Academy. It is not part of the mathematics and you are welcome to skip it.
In 1995 Niklaus Wirth published A Plea for Lean Software, arguing that programs grow bloated because their makers stop caring about what each part costs and why it is there. His own languages and compilers were famously small and clear. There is something worth admiring in that discipline, and it echoes an old teaching: whoever is faithful in very little is faithful also in much. The habits this course ends with (freeing what you create, naming the owner of every object, handling errors where they can be handled, testing the rules you depend on) are small faithfulnesses, and the people who rely on our programs are served by them every day, usually without ever knowing.
Exercises
All outputs below were checked by compiling and running the code with Free Pascal 3.2.2.
1. GUI applications, professional tools and a complete project
Warm-upHumanIn the miniature forms program, the main block calls only Form.Free. Why are the edit box, the button and the label freed as well?
2. GUI applications, professional tools and a complete project
StretchComputationalThe form's constructor in the miniature forms program gains two more lines, LabelHint := TLabel.Create(nil); and LabelHint.Name := 'LabelHint'; (with a published field LabelHint: TLabel). What number does the line Form owns … components now print?
3. GUI applications, professional tools and a complete project
CoreComputationalIn the library project, the command '2026-11-30 return A4' is added after '2026-12-01 overdue'. What line does the desk print for it, below the command itself? Write it without the two leading spaces.
4. GUI applications, professional tools and a complete project
Warm-upComputationalAfter A2 has been returned, the command '2026-12-28 lend A2 Kenji' is run. What due date does the desk print? Write it as the program does, in the form yyyy-mm-dd.
5. GUI applications, professional tools and a complete project
CoreHumanA Lazarus front end is added to the library project. Where should the rule "reference books may not be lent" be enforced?
6. GUI applications, professional tools and a complete project
CoreComputationalThe platform program is compiled with fpc -dDEBUG main.pas on Linux and run. What does its Build: line print? Write the line with single spaces.
7. GUI applications, professional tools and a complete project
CoreHumanWhich of these does the lesson's toolchain table list on the Lazarus and Free Pascal side? List their letters.
- A:
lazbuild - B: FPCUnit
- C:
heaptrc - D: GetIt
- E: DUnitX
- F: JEDI Code Format
Further reading and resources
- LazarusDownloads, news and documentation for the free, cross-platform IDE and its component library, the LCL.
- Lazarus TutorialThe community wiki's walk through the IDE, forms and a first GUI application.
- Free Pascal documentationThe language reference, the programmer's and user's guides, and the RTL and FCL references.
- Embarcadero DocWikiThe documentation for Delphi and RAD Studio, including the VCL and FireMonkey libraries.
- fpcunitFree Pascal's unit-testing framework and how to run its tests from Lazarus or the command line.
- DUnitXThe unit-testing framework most Delphi projects use.
- Modern Object Pascal Introduction for Programmers · Michalis KamburelisA free, concise tour of modern Object Pascal for programmers who know another language.