Algorithms
and Lazarus
Structural
Elements: MODULARITY
Modules
in Lazarus are code segments that are re-usable. In a visual system every
event-handler is a module (either a procedure or a function).
Procedures are encapsulated
actions, Functions are similar but are designed to return with an answer
as well. In a visual system there are two DIFFERENT types of modules -
this that are aware of form components and those that aren't. When making
modules it is important to determine (first) whether the module is going
to need to play with/use a form component - if it does, it needs to be
written a special way.
Parameters in a module
are ways to communicate with it while it is running. Many standard event
handlers come equipped with a sender parameter. This parameter
corresponds to the object (a button or other visual component) that triggered
the module. Smart event handlers know what triggers them and does
things relative to the initiator of the action.
Typically there are
2 types of modules - those that are FORM AWARE and those that
are not. They differ markedly in what they can do with visual projects.
Form Aware Modules.
Modules (procedures
or functions that are DECLARED in the FORM CLASS DEFINITION) and then
DEFINED in the body of a UNIT are form aware. Such modules can
act directly on form components because they are part of the form's parentage.
Some have a sender, some do not but all are introduced (or declared)
in for CLASS definition at the top of the unit (see procedure initialise
in the code below:)
type Tform1 = class(TForm) Label1: TLabel; Label2: TLabel; procedure initialise; procedure FormCreate(Sender: TObject); procedure newClick(Sender: TObject); private { Private declarations } public { Public declarations } end;
The module is defined
later as:
Procedure TForm1.initialise;
begin
{instructions go here}
end;
Form-aware modules
are very useful for encapsulating tasks that need to be done more than
once - code recycling is a good thing, code repetition (ie. typing the
same code more than once) is generally not.
|