MainframeSupports
tip week 44/2004:

PL/1 was born with object oriented facilities before object oriented languages became fashion. This tip will show you how to use encapsulation in PL/1 and will work for non reentrant programs as well as reentrant programs. As usual an example will help to understand the concept. Encapsulation in PL/1 is established using CONTROLLED variables:

ooexmpl: PROC OPTIONS(MAIN);

CALL oo_procedure;
CALL oo_procedure;
CALL oo_procedure;

oo_procedure: PROC;

  DCL allocation BUILTIN;
  DCL call_no FIXED BIN(31) CONTROLLED;

  IF allocation(call_no) = 0
  THEN DO;
    ALLOCATE call_no;
    call_no = 0;
  END;

  call_no = call_no + 1;
  IF call_no = 1
  THEN
    PUT SKIP LIST('First call');
  ELSE
    PUT SKIP LIST('Call no.' !! call_no);

END oo_procedure;

END ooexmpl;

The procedure OO_PROCEDURE just keeps track of the number of times it has been called. The first time it is called, the built-in routine ALLOCATION will return 0, because the variable CALL_NO hasn't been allocated. Then it is allocated and can be used as any other PL/1 variable. The difference is that CONTROLLED variables survive the termination of procedures and functions and therefore make them ideal to implement encapsulation in PL/1.

CONTROLLED variables in PL/1 doesn't take up any space until they are allocated using ALLOCATE. You can issue another ALLOCATE of the same variable. This will result in allocation of a new instance of the same variable and the old instance is not available any more. ALLOCATION will return the value 2 to indicate that the variable has two instances. Now you can issue a FREE of the variable to make the newest instance disappear and the old one reappear. Now ALLOCATION will return the value 1. Consequently CONTROLLED variables can be used as stack variables.

If you issue a FREE of a CONTROLLED variable that has been allocated only once then ALLOCATION will return the value 0. A reference to a CONTROLLED variable that hasn't been allocated will result in a PL/1 runtime error.

Previous tip in english        Sidste danske tip        Tip list