Title: Local/Nested Routines
Question: How to declare Local routines in delphi ?
Answer:
It is possible to declare local procedures or
Functions within a procedure or function.
Though it seems some how unusual at the first glance to declare
Local routines within a routine, it is efficient to do this.
If we do not need them anywhere other than the routine, why should
make them public even within the unit ? Let us place them in their proper
place, proper routines in proper place !
We declare local variables, constants and types before the BEGIN statement of
a function or procedure. We can also include local routines here. Though it is
efficient to include local routines here, but, in practice, very few delphi programmers
use these techniques.
Example:
Procedure PublicProc(p1:TypeofP1;p2:TypeofP2;....pn:TypeOfPn);
var
v1:TypeofV1;
V2:TypeofV2;
.....
Vn:TypeofVn;
const
c1:TypeofC1;
............
............
procedure LocalProcedure1(p1:TypeofP1;p2:TypeofP2;....pn:TypeOfPn);
var
.........
.........
begin
.........
.........
end;
procedure LocalProcedure2(p1:TypeofP1;p2:TypeofP2;....pn:TypeOfPn);
var
.........
.........
begin
.........
.........
end;
Function LocalFunction1(p1:TypeofP1;p2:TypeofP2;....pn:TypeOfPn):ResultType;
var
.........
.........
begin
.........
.........
result:=.....
end;
Function LocalFunction2(p1:TypeofP1;p2:TypeofP2;....pn:TypeOfPn):ResultType;
var
.........
.........
begin
.........
.........
result:=.....
end;
begin {PublicProc}
...........
'''''''''''
LocalProcedure1(...., ...., ....);
...........
LocalProcedure2(...., ...., ....);
...........
v1:=LocalFunction1(...., ...., ....);
...........
v2:=LocalFunction2(...., ...., ....);
...........
'''''''''''
end;{PublicProc}
In this example, the scope of the nested routines
LocalProcedure1,
LocalProcedure2,
LocalFunction1 and
LocalFunction2
is limited only to PublicProc. No other routines in the same unit or in other
units can see them.
For some real examples of nested routines, please have a look in the article
"Converting Numbers to words !".