Boolean Variables: Underused and Unappreciated
May 16, 2012 Ted Holt
Boolean variables can have only two values: true and false. In CL, they are known as logical variables. In RPG, they’re called indicator variables. They’re not essential; I got by without them for years. But they are useful. Let’s take a closer look at Boolean variables.
Let me share a story with you. Some years ago, a certain factory started faxing requirements reports to their suppliers. The suppliers liked the reports, but some of them asked if they might receive the requirements electronically in a spreadsheet format. The IT department added a one-digit code to the database.
The new electronic format was a hit, but wouldn’t you know it? Some suppliers asked to receive their reports in both formats. The IT department added another code value.
Over time, new options were added to send a PDF file by email, to send a CSV file by email, and various combinations of transmission methods.
The result was that the RPG program that created the requirements report and file was full of logical expressions like these:
if option = 1 or option = 3; if option >= 1 and option <= 3; if option = 4 or option = 5 or option = 7;
This type of code is difficult to modify when a new transmission option is added, because the meaning of each option is not readily apparent. Use Boolean variables to clarify the conditions, like this:
D SendByFax s n D PutOnFTPSvr s n D EmailPDF s n D EmailCSV s n /free SendByFax = (option = 1 or option = 3); PutOnFTPSvr = (option = 2 or option = 3 or option = 5); EmailPDF = (option = 4 or option = 5 or option = 7); EmailCSV = (option = 6 or option = 7); if SendByFax; if SendByFax or PutOnFTPSvr; if EmailPDF;
Now, instead of adding expressions like this one:
option = 8 or option = 9
to one or more conditions, you can do this sort of thing instead:
D SendTelepathically... D s n /free SendTelepathically = (option = 8 or option = 9); EmailCSV = (option = 6 or option = 7 or option = 9); if EmailPDF or SendTelepathically;
This style of code is self-documenting, because the emphasis has shifted from mechanics to intention.
Some say that beginning a Boolean variable with a verb, or embedding a verb in the variable name, makes the intent even clearer. For example, this indicator variable begins with the verb Is:
D IsEDICust s n /free IsEDICust = (Customer.EDICode = '1');
If you’re not in the habit of using Boolean variables, I challenge to look at something you wrote but haven’t worked on in a while. Chances are, you will see plenty of conditions that have to be deciphered, and that could be improved by a judicious use of Boolean variables.