A boolean property that’s really an integer…

In my previous post I have been writing about how you can mimic properties in a PL/SQL package. One of the ideas I wrote about was a boolean property that internally is an integer value. How can this be useful. If, for instance, you want to turn logging on and of during the program, wouldn’t it be nice not to have to worry about it’s previous state when turning it on (for instance when calling sub-programs).

Suppose I have the following package spec:

CREATE OR REPLACE PACKAGE bar
IS
— Author : PBAREL
— Purpose : demonstrate properties
  PROCEDURE LOG(log_in IN BOOLEAN );
  FUNCTION LOG RETURN BOOLEAN;
END bar;

There appears to be a boolean property to turn the logging on and off. If I turn on logging at one point in the execution of the program and turn if off later on, I would have to preserve the original state to see if logging was already turned on before I turned it on (again). If however, I would implement the property that would do the checking for me, it would be a big help. But, I wouldn’t know how many times it would be consecutively be turned on. That could be endless.

I can implement the internal variable as an integer, that is raised when turning logging on and lowered when logging is turned off. When checking the state of the property it will return a boolean value based on the value of the internal variable.

CREATE OR REPLACE PACKAGE BODY bar
IS
  flog PLS_INTEGER;
  PROCEDURE LOG(log_in IN BOOLEAN )
  IS
  BEGIN
    IF log_in THEN
      flog := flog + 1;
    ELSE
      flog := flog – 1;
    END IF;
   
IF flog < 0 THEN
      flog := 0;
    END IF;
  END LOG; 
 
FUNCTION LOG RETURN BOOLEAN
  IS
  BEGIN
    RETURN( flog > 0 );
  END LOG;
END bar;

Since we have more control over the property than just a package variable, this has become pretty straight forward and we can easily change the internal behavior of the property, while the signature wouldn’t change to the outside world.

Leave a Reply

Your email address will not be published.