If you want to be a productive programmer, you have to know how to create your own procedures. Procedures enable you to reuse your own code in one or more projects and to separate application logic into more manageable, smaller pieces of code. They also help minimize the number of errors in the application. If the procedure contains a bug, we only have to repair the bug once, inside the procedure, and the problem is solved in the entire application.
A really simple procedure looks like this:
procedure Hello; begin end;
As you can see, all you have to do to create a simple procedure is to define the name of the procedure in the procedure header and write the procedure block. The problem is where to write the procedure implementation. If you have any doubts as to where you have to write a piece of code, remember that in Delphi everything has to be declared before it can be used. So, since we're going to use this procedure in the main block of the application, it has to be written before the main application block. Actually, it has to be located between the uses list and the main application block, as shown in Listing 5-3.
Listing 5-3: Our first procedure
program Project1; {$APPTYPE CONSOLE} uses SysUtils; procedure Hello; begin end; begin end.
To see how procedures actually work, we have to add some code to the Hello procedure:
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var i: Integer; procedure Hello; begin WriteLn('I ', #3, ' Delphi.'); end; begin end.
If you run this code, the message from the Hello procedure will not be displayed on screen because we didn't call the Hello procedure in the main block of the application. No matter how many procedures there are in the source code, the execution of the application always starts at the beginning of the main application block.
Listing 5-4: Calling the Hello procedure
program Project1; {$APPTYPE CONSOLE} uses SysUtils; var i: Integer; procedure Hello; begin WriteLn('I ', #3, ' Delphi.'); end; begin for i := 1 to 20 do Hello; ReadLn; end.