home   Java Script   MS Access   Perl   HTML   Delphi   C ++   Visual Basic   Java   CGIPerl   MS Excel   Front Page 98   Windows 98   Ms Word   Builder   PHP   Assembler     Link to us   Links    



Teach Yourself Borland Delphi 4 in 21 Days

Previous chapter Contents


- 1 -

Getting Started with Delphi


Congratulations--you've chosen one of today's hottest programming tools! Before you get started using all that Delphi has to offer, though, you first need to learn a little about the Delphi IDE and about Object Pascal. In this chapter you will find

What Is Delphi?

By now you know that Delphi is Borland's best-selling rapid application development (RAD) product for writing Windows applications. With Delphi, you can write Windows programs more quickly and more easily than was ever possible before. You can create Win32 console applications or Win32 graphical user interface (GUI) programs. When creating Win32 GUI applications with Delphi, you have all the power of a true compiled programming language (Object Pascal) wrapped up in a RAD environment. What this means is that you can create the user interface to a program (the user interface means the menus, dialog boxes, main window, and so on) using drag-and-drop techniques for true rapid application development. You can also drop ActiveX controls on forms to create specialized programs such as Web browsers in a matter of minutes. Delphi gives you all this, and at virtually no cost: You don't sacrifice program execution speed because Delphi generates fast compiled code.

I can hear you saying, "This is going to be so cool!" And guess what? You're right! But before you get too excited, I need to point out that you still have to go to work and learn about Pascal programming. I don't want you to think that you can buy a program like Delphi and be a master Windows programmer overnight. It takes a great deal of work to be a good Windows programmer. Delphi does a good job of hiding some of the low-level details that make up the guts of a Windows program, but it cannot write programs for you. In the end, you must still be a programmer, and that means you have to learn programming. That can be a long, uphill journey some days. The good news is that Delphi can make your trek fairly painless and even fun. Yes, you can work and have fun doing it!

So roll up your sleeves and put on your hiking shoes. Delphi is a great product, so have fun.

A Quick Look at the Delphi IDE

This section contains a quick look at the Delphi integrated development environment (IDE). I'll give the IDE a once-over now and examine it in more detail on Day 4, "The Delphi IDE Explored." Because you are tackling Windows programming, I'll assume you are advanced enough to have figured out how to start Delphi. When you first start the program, you are presented with both a blank form and the IDE, as shown in Figure 1.1.

FIGURE 1.1.The Delphi IDE and the initial blank form.

The Delphi IDE is divided into three parts. The top window can be considered the main window. It contains the toolbars and the Component palette. The Delphi toolbars give you one-click access to tasks such as opening, saving, and compiling projects. The Component palette contains a wide array of components that you can drop onto your forms. (Components are text labels, edit controls, list boxes, buttons, and the like.) For convenience, the components are divided into groups. Did you notice the tabs along the top of the Component palette? Go ahead and click on the tabs to explore the different components available to you. To place a component on your form, you simply click the component's button in the Component palette and then click on your form where you want the component to appear. Don't worry about the fact that you don't yet know how to use components. You'll get to that in due time. When you are done exploring, click on the tab labeled Standard, because you'll need it in a moment.

New Term: A component is a self-contained binary piece of software that performs some specific predefined function, such as a text label, an edit control, or a list box.

The Object Inspector

Below the main window and on the left side of the screen is the Object Inspector. It is through the Object Inspector that you modify a component's properties and events. You will use the Object Inspector constantly as you work with Delphi. The Object Inspector has two tabs: the Properties tab and the Events tab. A component's properties control how the component operates. For example, changing the Color property of a component changes the background color of that component. The list of properties available varies from component to component, although components usually have several common elements (Width and Height properties, for instance).

New Term: A property determines the operation of a component.

The Events tab contains a list of events for a component. Events occur as the user interacts with a component. For example, when a component is clicked, an event is generated that tells you that the component was clicked. You can write code that responds to these events, performing specific actions when an event occurs. As with properties, the events that you can respond to vary from component to component.

New Term: An event is something that occurs as a result of a component's interaction with the user or with Windows.

New Term: An event handler is a section of code that is invoked in your application in response to an event.

The Delphi Workspace

The main part of the Delphi IDE is the workspace. The workspace initially displays the Form Designer. It should come as no surprise that the Form Designer enables you to create forms. In Delphi, a form represents a window in your program. The form might be the program's main window, a dialog box, or any other type of window. You use the Form Designer to place, move, and size components as part of the form creation process.

Hiding behind the Form Designer is the Code Editor. The Code Editor is where you type code when writing your programs. The Object Inspector, Form Designer, Code Editor, and Component palette work interactively as you build applications.

Now that you've had a look at what makes up the Delphi IDE, let's actually do something.

Your First Program: Hello World

It's tradition. Almost all programming books start you off by having you create a program that displays Hello World on the screen. I'm tempted to do something else, but tradition is not a force to be reckoned with, so Hello World it is. You've got some work ahead of you in the next few chapters, so I thought I'd give you a taste of Delphi's goodies before putting you to work learning the seemingly less glamorous basics of the Pascal language. You'll have a little fun first. Delphi (and its cousin, C++Builder) gives you possibly the quickest route to Hello World of any Windows programming environment to date.

Creating the Program

Right now you should have Delphi running, and you should be looking at a blank form. By default, the form is named Form1. (The form name is significant in Delphi, but I'll address that a little later.) To the left of the form, the Object Inspector shows the properties for the form. Click on the title bar of the Object Inspector. The Caption property is highlighted, and the cursor is sitting there waiting for you to do something. (If the Caption property is not in view, you might have to scroll the Object Inspector window to locate it. Properties are listed in alphabetical order.) Type Hello World! to change the form's caption.


NOTE: As you modify properties, Delphi immediately displays the results of the property change when appropriate. As you type the new caption, notice that the window caption of the form is changing to reflect the text you are typing.

Now click the Run button on the toolbar (the one with the green arrow). (You can also press F9 or choose Run | Run from the main menu.) Before you even know what has happened, Delphi has built the program. The form is displayed, and the caption shows Hello World!. In this case, the running program looks almost identical to the blank form. You might scarcely have noticed when the program was displayed because it is displayed in the exact location of the form in the Form Designer. (There is a difference in appearance, though, because the Form Designer displays an alignment grid and the running program does not.) Congratulations--you've just written your first Windows program with Delphi. Wow, that was easy!

"But what is it?" you ask. It's not a lot, I agree, but it is a true Windows program. Try it out and see. The program's main window can be moved by dragging the title bar, it can be sized, it can be minimized, it can be maximized, and it can be closed by clicking the Close button. You can even locate the program in Windows Explorer (it will probably be in your \Delphi40\Bin directory as Project1.exe) and double-click on it to run it.

Modifying the Program

Okay, so maybe displaying Hello World! in the caption was cheating a little. Let's spruce it up a bit. If you still have the Hello World program running, close it by clicking the Close button in the upper-right corner of the window. The Form Designer is displayed again, and you are ready to modify the form (and, as a result, the program).

To make the program more viable, you're going to add text to the center of the window itself. To do this, you'll add a text label to the form:

1. First, click on the Standard tab of the Component palette. The third component button on the palette has an A on it. If you put your mouse cursor over that button, the tooltip (a small pop-up window) will display Label.

2. Click the label button and then click anywhere on the form. A label component is placed on the form with a default caption of Label1.

3. Now turn your attention to the Object Inspector. It now displays the properties for Label1 (remember that previously it was showing the properties for Form1). Again the Caption property is highlighted.

4. Click on the title bar of the Object Inspector or on the Caption property and type Hello World!. Now the label on the form shows Hello World!.

5. As long as you're at it, you can change the size of the label's text as well. Double-click on the Font property. The property will expand to show the additional font attributes below it.

6. Locate the Size property under Font and change the font size to 24 (it is currently set to 8). As soon as you press Enter or click on the form, the label instantly changes to the new size.

Because the label is probably not centered on the form, you might want to move it. To move a component, simply click on it and drag it to the position you want it to occupy. When you have the label where you want it, you're ready to recompile and run the program. Click the Run button again and, after a split second, the program runs. Now you see Hello World! displayed in the center of the form as well as in the caption. Figure 1.2 shows the Hello World! program running.

FIGURE 1.2. Your Hello World! program running.

Closing the Program

With this little taste of Delphi, you can see that writing Windows programs with Delphi is going to be a great deal more interesting than it was in the good ol' days. To prepare for what you are going to do next, you need to close the current project in the Delphi IDE. Choose File | Close All from the main menu. Click on No when prompted to save changes to Project1, or save the project if you are fond of your new creation.

Your Second Program: Hello World, Part II

Before you can move on to learning the Pascal language you need a little more information about how Delphi works. You'll need this information to test the various Pascal language features as you work through the next couple of days. This section will contain just a glimpse into the power of Delphi. On Days 4, 5, and 6, you get a more detailed look into how Delphi works.

Creating the Hello World II Program

The goal of this exercise is to have the words Hello World, Part II appear on the screen when a button is pressed. This exercise will also give you a pattern you can follow when you test various code snippets as you work through the next couple of days. Perform the following steps:

1. Choose File | New Application from the main menu to start a new application (click No if you're prompted to save the current project).

2. Click the Standard tab on the Component palette and click the icon that has an OK button on it (the Button component).

3. Place your cursor anywhere on the form and click. A button appears on the form.

4. Choose a Label component and place it near the center of the form.

At this point your form should look similar to Figure 1.3. Notice that the label component has a default caption of Label1 and the button has a default caption of Button1.

Modifying the Hello World II Program

In the first version of Hello World, you used the Object Inspector to change the Caption property of a label. That change was applied at design time and as such was seen as soon as the program ran. In this exercise, you are going to change the caption of the label through code.

FIGURE 1.3.The new form after placing the button and label components.



NOTE: When you change a component's properties through the Object Inspector and Form Designer, you are said to make a design-time change. When you modify a property through code that executes when the program runs, you are said to make a runtime change.

To change the Caption property at runtime, follow these steps:

1. Double-click on the button on your form. As soon as you do, Delphi generates an event handler for the button's OnClick event. The generated code looks like this:
procedure TForm1.Button1Click(Sender: TObject);
begin
end;


2. Right now you don't need to be concerned with everything you see here. You only need to understand that the OnClick event handler is a section of code that will be executed every time the button is clicked (as long as the program is running, that is). The editing cursor is placed between the begin and end statements and is waiting for you to type code. Enter this code at the cursor:

Label1.Caption := `Hello World, Part II';


I always indent two spaces (considered by many programmers to be proper coding practice) so my completed event handler now looks like this:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption := `Hello World, Part II';
end;


This code is pretty simple. It simply assigns the value Hello World, Part II to the Caption property of the label (the Caption property is used to set the text that the label displays).

3. Now click on the Run button on the toolbar to run the program. When you run the program, notice that the label still has the caption Label1. Click the form's button and the label's caption changes to Hello World, Part II. Hey, how about that! Magic? No, just Delphi at work!

You'll be doing many such exercises in the next few days so you'll get plenty of practice placing labels, buttons, and other components on the form. I realize that I didn't fully explain what is going on behind the scenes here, but I don't want to get ahead of myself so I'll save that explanation for a later time.

Object Pascal Language Overview

Before you can learn about the RAD features of Delphi, you need to learn the basics of the Object Pascal language. This part of the book will probably not be the most exciting for you, but you need a basic understanding of Object Pascal before you move on.

It would be nice if presenting the Object Pascal language could be handled sequentially. That's not the case, though, because all the features you will learn about are intertwined. I'll take the individual puzzle pieces one at a time and start fitting them together.

By the end of Day 3, you'll have a fairly complete picture of the Object Pascal language. Don't be concerned if you don't instantly grasp every concept that is presented. Some of what is required to fully understand Object Pascal can only come with real-world experience.

During the next few days, you will see short code snippets that illustrate a particular feature of the Object Pascal language. You will also do some exercises that enable you to test your newfound knowledge. In the first few days, you will only see your Delphi applications in small sections. I don't want to get ahead of myself and go too far into the Delphi IDE or the Visual Component Library (VCL) at this early stage. You will have to settle for bits and pieces until later in the book when you start to get the complete picture. The code that you can download from the book's site contains complete programs for some of the exercises that you will perform over the next several days. (Go to http://www.mcp.com/info and type 0-672-31286-7.)

In the Beginning...

Back in 1994 or so, Borland began working on a RAD tool that it code-named Delphi. When it was decided that the component model architecture was the best way to implement RAD, it was then necessary to settle on the programming language that would be the heart of the system.

At that time, Borland was the only compiler vendor mass marketing a Pascal compiler. Borland was known as the company that produced the best Pascal tools. If you were a Pascal programmer, you probably used Borland's TurboPascal in one flavor or another. Borland more or less "owned" Pascal. Although Borland didn't own the Pascal language in a legal sense, it no doubt felt that because of its position in the Pascal world, it could take considerable liberties in implementing new language features and enhancements. In addition, there was no Pascal standards committee, nor even a written standard defining the Pascal language. So Borland created Delphi using Pascal as the base language (the Borland internal code name stuck and became the official product name).

Before Delphi came into being, Borland had already modified the Pascal language in positive ways. For example, Borland had already extended Pascal by creating a new language called Object Pascal. It can be said that Object Pascal is to Pascal what C++ is to C. Object Pascal added classes to Pascal, thereby hurling Pascal into the world of object-oriented programming (OOP) languages. As Delphi was being developed, new language behavior and keywords were added to deal with the component model. Keywords such as published and property were added, as were others. This enabled Borland to fully implement the power of the component model. By modifying the Pascal language to suit the component model, Borland was able to implement RAD the right way. In essence, the Object Pascal language was modified as needed when design issues came up during the development of the then-unknown product called Delphi. The result is a language that works seamlessly with the component model.

Although modifying the Pascal language could be considered a bold step for Borland, it was not without precedent. Previously, Microsoft had taken the BASIC language and modified it to produce a new language called Visual Basic. This new language was nearly unrecognizable when compared to the original BASIC language that served as its base.

Borland took a risk in modifying Pascal. After all, it had a loyal base of customers that might not take kindly to enhancements to the language they had come to know and love. Still, Borland was in a solid position in the Pascal market and went ahead with its plans. The result was a smash hit, of course.

Make no mistake about it, Object Pascal is a powerful programming language, and I don't make that statement lightly. I have a C/C++ background and, like other C/C++ programmers, I viewed Delphi with a bit of skepticism at first. I found out quickly, though, that the Object Pascal language is very capable. In fact, in the hands of the average programmer there is almost no difference in the two languages in terms of power. Object Pascal is unique in that it is both powerful and relatively easy to learn. I don't in any way want to leave the impression that Object Pascal is a not a full-featured programming language. Pascal has often been knocked as a less-than-serious programming language. That has never been true, and is even less true with today's Object Pascal.


NOTE: Several different terms have been adopted by Delphi programmers to describe what they do. The base language of Delphi is, of course, Object Pascal, and some folks call it exactly that. Others might say, "I program in Pascal," or even just, "I'm a Delphi programmer." In the end it's up to you to decide what terminology you will use. I'll use the terms Object Pascal and Pascal interchangeably throughout this book and will typically reserve use of the word Delphi to refer to the Delphi IDE or its tools.

Object Pascal enables you to take advantage of object-oriented programming to its fullest. OOP is not just a buzzword. It has real benefits because it enables you to create objects that can be used in your current program and reused in future programs.

New Term: An object, like components described earlier, is a binary piece of software that performs a specific programming task. (Components are objects, but not all objects are components. I'll explain that later.)

An object reveals to the user (the programmer using the object) only as much of itself as needed; therefore, using the object is simplified. All internal mechanisms that the user doesn't need to know about are hidden from sight. All this is included in the concept of object-oriented programming. OOP enables you to take a modular approach to programming, thus keeping you from constantly re-inventing the wheel. Delphi programs are very OOP-centric because of Delphi's heavy use of components. After a component is created (either one of your own or one of the built-in components), it can be reused in any Delphi program. A component can also be extended by inheritance to create a new component with additional features. Best of all, components hide their internal details and let the programmer concentrate on getting the most out of the component. Objects and classes are discussed in detail on Day 3, "Classes and Object-Oriented Programming."

Pascal Units

Programming is more than just typing code. Ultimately, it is the combination of conceptualizing a programming task and then typing code to carry out that task. The code you type simply goes into a text file. The compiler takes that text file and compiles it into machine code that the computer can understand. The text file that Delphi compiles into machine code is called a unit.

New Term: A unit is a text file that can be compiled into a module of code.

Types of Units

A Delphi GUI application will contain at least two units. The project source unit contains the project source code. Project source code units have an extension of DPR. You can view the project source unit by choosing Project | View Source from the main menu. It is not normally necessary to modify the project source unit. In fact, you shouldn't modify the project source unit unless you know exactly what you are doing. If you accidentally modify the project source unit in undesirable ways, you might find that your application won't compile anymore. (Certain advanced programming techniques require modification of the project source code, but that's not something you need to be concerned with at this time.)

The second type of unit that a Delphi GUI application always has is the main form's unit. A form unit, as its name implies, is a source code unit with an associated form. This type of unit has a filename extension of PAS. This is the type of unit you will use most often in your Delphi programs. A Delphi GUI application will always have one form unit (for the main form), but it can have one or more additional form units as well. For example, an application that displays an About box will have the main form unit and a unit for the About box.


NOTE: You might have noticed that I keep saying "Delphi GUI application." This is because I want to distinguish a GUI application from a console mode application. A console mode application is a 32-bit Windows application that runs in a console window (DOS box). A console application has no main form and may or may not contain other forms. A console application does, however, have one or more units.

There is a third type of unit you can use in Delphi applications. This type of unit is a unit that contains only source code. A code-only unit contains code that is called from other units in the project. I won't go into any more detail than that right now, but you'll learn more about this type of unit in later chapters.

Anatomy of a Delphi Unit

Delphi units must follow a predefined format. This shouldn't come as a surprise to you. The unit has to be in a predefined format so that the compiler can read the unit and compile the unit's code.

A Delphi project unit contains the program keyword followed by the name of the unit and a code block marked by the begin and end keywords. You can see how a basic unit looks by choosing View | Project Source from the Delphi main menu. The project source unit for a default Delphi project looks like Listing 1.1.


NOTE: The line numbers in Listing 1.1 are not part of the unit itself. I have put them there for reference only. Some of the listings you see in this book will have line numbers for reference and others will not. In either case, be sure to understand that the Pascal language does not use line numbers as some other languages do (most notably, BASIC).

LISTING 1.1. THE PROJECT SOURCE FOR A DEFAULT DELPHI PROJECT.

01: program Project1;
02: 
03: uses
04:   Forms,
05:   Unit1 in `Unit1.pas' {Form1};
06:
07: {$R *.RES}
08:
09: begin
10:   Application.Initialize;
11:   Application.CreateForm(TForm1, Form1);
12:   Application.Run;
13: end.

On line 1, the program keyword identifies this unit as a program's main source unit. You can see that the unit name, Project1, follows the program keyword (Delphi gives the project a default name until you save the project with a more meaningful name). Beginning on line 3, you see a section identified by the uses keyword. Any unit names following the uses keyword, up to the semicolon, are other units that this unit requires in order to compile. The uses keyword is described in more detail a little later in the section, "The uses List."

On line 7 you see a compiler directive that tells Delphi to include this project's resource file. Resource files are discussed in more detail on Day 8, "Creating Applications in Delphi."

Line 9 contains the begin keyword, and line 13 contains the end keyword. Notice that the final end keyword in the unit is followed by a period. (A unit can have many code blocks marked with begin and end, but only one final end statement.) The code on lines 10, 11, and 12 is code that initializes the application, creates the application's main form, and starts the application running. You don't need to be concerned about the details of this code to write Delphi programs.


NOTE: The begin and end keywords mark a code block. A code block can contain just a few lines of code, or it can contain several hundred lines of code (or even thousands of lines). You will see the begin and end keywords used throughout the book. As you work through the book, you will get a better handle on how and when the begin and end keywords are used.

Let's take a look at another basic Pascal unit. Choose File | New from the main menu. When the New Items dialog comes up, locate the icon labeled Unit and double-click it. Delphi will create a new unit and display it in the Code Editor. Listing 1.2 shows the code generated for this unit.

LISTING 1.2. A BLANK PASCAL UNIT.

01: unit Unit2;
02:
03: interface
04:
05: implementation
06:
07: end.
There isn't much here, is there? This unit has two things in common with the unit shown in Listing 1.1. First, the unit starts with the unit keyword followed by the unit name Unit2 (again, a default name created by Delphi). I realize the code in 
Listing 1.1 starts with the program keyword and this code starts with the unit keyword, but there are a few common elements: A Pascal unit starts with one of these two keywords followed by the unit name, and the end keyword appears at the end of both 
listings. Here again, the end keyword is followed by a period to mark the end of the unit.

The code in Listing 1.2 differs from that of Listing 1.1 in that it has sections marked interface and implementation. A unit that is not the program's main source unit must contain an interface section and an implementation section. These two keywords will be described in more detail in the sections entitled, "The interface Section" and "The implementation Section," respectively. Listing 1.2 also differs from Listing 1.1 in that there is no begin statement. A program's main unit must have both begin and end statements, but a source unit only has to contain a final end statement.

The following sections describe keywords that are used within a Pascal unit.

The uses List

New Term: The uses list is a list of external units that this unit references.

Refer to Listing 1.1. Notice the uses keyword on line 3. The uses keyword designates the start of a section that will contain a list of other units that this unit is dependent on. For example, line 11 of Listing 1.1 looks like this:

Application.CreateForm(TForm1, Form1);

This line of code contains information that is located in other units and cannot be found in this unit. The procedure identified by Application.CreateForm is located in a Delphi unit called Forms.pas, and the identifiers TForm1 and Form1 are located in the project's main form unit, which is called Unit1.pas. Do you see the connection? The uses list tells Delphi where to look for additional information that it will need to compile this unit. Here's another look at the uses list:

uses
  Forms,
  Unit1 in `Unit1.pas' {Form1};

Notice that the uses list contains two unit names, Forms and Unit1. In some ways this is not a good example of a uses list because the second unit listed contains additional text not usually found in a uses list (Unit1 in `Unit1.pas' {Form1}).

This text is used to specify a form that is contained in a unit and is only used by the project's main source unit. (The text between the curly braces is a comment used for reference and has no bearing on the rest of the code. Comments are discussed later in the section "Comments in Code.")

There are two rules you need to be aware of when constructing the uses list:

Naturally the list must contain valid unit names. The uses list, then, is designated by the uses keyword and ends with a semicolon. Other than that, it doesn't matter how the uses list is organized. For example, the following two uses lists are identical as far as the compiler is concerned:

uses
  Windows, Messages, SysUtils, Classes, Graphics, 
  Controls, Forms, Dialogs, StdCtrls;
uses
  Windows, 
  Messages, 
  SysUtils, 
  Classes, 
  Graphics, 
  Controls, 
  Forms, 
  Dialogs,
  StdCtrls;

A unit can have any number of uses lists. It is not required that all units needed by this unit be in a single uses list.


NOTE: In some cases, Delphi will add units to your uses list for you. This is done via the File | Use Unit menu item. This feature will be discussed in more detail on Day 4.


The interface Section

Take another look at Listing 1.2. Notice that this listing has a section marked by the interface keyword. This keyword marks the start of the interface section for the unit.

The interface section is the section of a unit in which identifiers exported from this unit are declared. An exported identifier is one that can be accessed by other units in the project.

Most units will contain code that other units use. The code might be implemented as a class, a procedure, a function, or a data variable. Any objects that are available to other units from this unit must be declared in the interface section. You could say that the interface section contains a list of items in this unit that other units can use. The interface section starts with the interface keyword and ends at the implementation keyword.

The implementation Section

New Term: The implementation section of a unit is the section that contains the actual code for the unit.

The implementation section starts with the implementation keyword and ends with the next unit keyword. The next unit keyword is usually the unit's final end keyword, but could be the initialization keyword in units that have an initialization section. It's difficult to say more than that right now, because there are other aspects of Pascal that I need to discuss before tying all of this together. However, let me give you an example that will illustrate the use of the interface and implementation sections.

Let's say that you create a unit that has a procedure called DoSomething. Let's further say you want DoSomething to be available to other units in your project. In that case, you would declare the DoSomething procedure in the interface section and then define the procedure in the implementation section. The entire unit would look like Listing 1.3.

LISTING 1.3. A UNIT WITH A PUBLIC FUNCTION.

unit Unit2;
interface
  procedure DoSomething;
implementation
  procedure DoSomething;
  begin
    { Code for DoSomething goes here. }
  end;
end.

Notice that the DoSomething procedure is declared in the interface section and defined later in the implementation section. I realize I'm getting a little ahead of myself here. Functions and procedures will be discussed more tomorrow, and I'll go over declarations and definitions in detail at that time.

The initialization and finalization Sections

The initialization and finalization sections can be used to perform any startup and cleanup code that a unit requires. Any code in the initialization section will be executed when the unit is loaded into memory. Conversely, any code in the finalization section will be executed just before the unit is unloaded from memory. You can have just an initialization section, but you cannot have a finalization section without an initialization section. The initialization and finalization sections are optional.

Additional Keywords Used in Units

A Pascal unit can contain other, optional keywords that mark sections set aside for a particular purpose. Some of these keywords have multiple uses. The following sections describe those keywords only as they pertain to units.

The const Keyword

A unit can optionally have one or more const sections. The const section is designated with the const keyword. The const section describes a list of variables that are known as constants.

A constant is an identifier that cannot change. For example, let's say you have certain values that your program uses over and over. You can set up constant variables for those values. To illustrate, let's add a const section to the program in Listing 1.3. You'll add one const section for constants that are public (available to other units) and another const section for constants that are available only to this unit. Listing 1.4 shows the unit with the two const sections added.

LISTING 1.4. THE UNIT WITH const SECTIONS ADDED.

unit Unit2;
interface
const
  AppCaption = `My Cool Program 1.0';
  procedure DoSomething;
implementation
const
  BaseX = 20;
  BaseY = 200;
  procedure DoSomething;
  begin
    { Code for DoSomething goes here. }
  end;
end.

Because the AppCaption constant is declared in the interface section, it can be used anywhere in the unit and in any unit that has this unit in its uses list. The BaseX and BaseY constants, however, are only available within this unit because they are declared in the implementation section.

The const keyword has other uses besides the one described here. I'll discuss one of those uses tomorrow in the section, "Value, Constant, and Variable Parameters."

The type Keyword

New Term: The type keyword is used to declare new types that your program will use.

Declaring a new type is an esoteric programming technique that is difficult to explain at this stage of the game, so perhaps an example will help. Let's say that your application needs an array (a collection of values) of 20 bytes and that this type of array will be used over and over again. You can declare a new type as follows:

type
  TMyArray = array [0..19] of Byte;

Now you can use the identifier TMyArray instead of typing out array [0..19] of Byte every time you want an array of 20 bytes. I'll have to leave it at that for now, but you'll see more examples of declaring types later in the book.

The var Keyword

New Term: The var keyword is used to declare a section of code in which variables are declared.

You use the var keyword to declare variables (variables are discussed in detail in the section entitled "Variables"). There are several places you can declare a var section. You can have a var section at the unit level, you can have a var section for a procedure or function, or both. You can even have multiple var sections in a unit. Listing 1.5 shows the sample unit with type and var sections added.

LISTING 1.5. THE UNIT WITH type AND var SECTIONS ADDED.

unit Unit2;
interface
type
  TMyArray = array [0..19] of Byte;
const
  AppCaption = `My Cool Program 1.0';
var
  X : Integer;
  MyArray : TMyArray;
  procedure DoSomething;
implementation
const
  BaseX = 20;
  BaseY = 200;
  procedure DoSomething;
  begin
    { Code for DoSomething goes here. }
  end;
end.

As with the const keyword, the var keyword has more than one use. It is also used to declare function and procedure parameters as variable parameters. Rather than go into that now, I'll save that discussion for tomorrow when you read about functions and procedures.


NOTE: The sections described by the var, const, and type keywords begin at the keyword and end at the next keyword in the unit.

Comments in Code

Before getting into the Pascal language in detail, let me talk briefly about commenting code. Comments are lines of text in your source code that are there for documentation purposes. Comments can be used to describe what the code does, to supply copyright information, or simply to make a note to yourself or other programmers.

Comments can be designated in as many as three different ways. The following are all valid comments lines:

{ Don't forget to free this memory! }
{
 ADTAPI.PAS 2.50
 Copyright (c) TurboPower Software 1996-98
}
(* Mason needs to fix this section of code *)
// This is really good code!
{ This code needs to be reworked later }

Probably the most common type of comment used in Delphi programs uses curly braces as illustrated in the first two cases above. The opening brace is used to start a comment, and the closing brace is used to end a comment. Another type of comment uses (* to start the comment, and *) to end the comment. There is one difference between comments designated this way as opposed to using curly braces: The (*/*) comment pair can be used to block out large sections of code containing other comment lines. These two comment types can be used to comment single lines of code or multiple lines.


NOTE: Curly braces have another use in Pascal. When used in conjunction with a dollar sign, the braces signify a compiler directive. To tell the compiler not to generate compiler hints, you can put a line like this in your source code:

{$HINTS OFF}



When the compiler sees this line, it stops generating hints in this unit until a corresponding {$HINTS ON} directive is encountered. I'll talk about individual compiler directives at different points in the book as the need arises.


The third type of comment is designated by the double slash. This is often called the C-style comment because it is used by C and C++. This type of comment can only be used on single lines of code. You should also be aware that this type of comment is not valid in all versions of Delphi. If you are writing code that might be used in Delphi 1 as well as later versions, you should be sure not to use this style of comment.


NOTE: I use the curly brace style of comment for production code (code that others will see). I use the double slash type of comment for quickly commenting out a line or two for testing purposes, but only as a temporary measure. I rarely use the (*/*) style of comment.

Any commented text is ignored by the compiler. If you are using the default Delphi IDE settings, all comment lines will show up in italicized, blue text. This makes it easy to quickly identify comment lines.


NOTE: If you work in a team programming environment, you might have to read your coworkers' code and vice versa. Concise comments in the code can save hours of time for any programmer who has to read and maintain another programmer's code. Even if you work in a single-programmer environment, commenting your code is a good idea. You'd be surprised how quickly you forget what code you wrote is supposed to do. Good code commenting can save you and your coworkers hours of time, so don't forget to comment your code!

Variables

Variables have to be declared before they can be used. You declare a variable in a special section of code designated with the var keyword, as described earlier--for example,

var
  X : Integer;  { variable X declared as an integer variable }
  Y : Integer;  { variable Y declared as an integer variable }
Earlier, I talked about the var keyword in terms of a Pascal unit. In that section, I said that variables used in the unit are declared in the unit's var section. That's true, but you can also have a var section in a function or procedure. This 
enables you to declare variables in functions and procedures as well as in units. Here's an example of a var section in a procedure:
procedure TForm1.Test;
var
  S : string;
begin
  S := `Hello World!';
  Label1.Caption := S;
end;

After you declare a variable, you can then use it to manip