Mirror

Local Routines or Nested Routines (Views: 101)


Problem/Question/Abstract:

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.

<< Back to main page