Sunday, March 16, 2014

Software Maintenance and Variables

A variable for every purpose, and a purpose for every variable.  This is a useful maxim for writing maintainable, coherent software.  A variable is more than a piece of computer memory used for storing data.  Variables with useful names and coherent usage contribute to the meaning and structure of a program.  Changing the meaning of a variable is a symptom of lazy coding that degrades the quality of the code.

Here is an example of "a variable for every purpose." I worked on one software product that had two resources (A and B) that were used with equal numbers: NumberOfA was equal to NumberOfB.  The programmer made the mistake of using one variable for two purposes.  Instead of using NumberOfA = 16 and NumberOfB = 16, he used NumberOfUnits = 16.  Perhaps he did not make this mistake on his own.  Perhaps he was directed by a code reviewer to eliminate a variable for the sake of efficiency.  Some years later, the customer decided to double the number of type B hardware units in the system.  So I had to read every section of code that used NumberOfUnits and change it to either NumberOfA or NumberOfB.  Changing the variable declarations and initializations was easy.  But the way this code was written, the variable NumberOfUnits appeared in hundreds and hundreds of places, and every instance of this variable had to be studied and modified.  Every time I had to guess, due to a lack of comments, whether it was A or B hardware units that were being commanded, an element of risk was introduced into the product.  What could have been a simple change, changing from NumberOfB = 16 to NumberOfB =32, turned into a laborious task that went on for hours.  Time is money, and lazy programming is expensive in the long run.

Here is an example of "a purpose for every variable."  One complex product I worked on had a class with an instance variable that was used for two different purposes.  The same variable was used in two different operations (methods), and used for two different purposes.  This was done out of sheer laziness.  This worked at first because the operations did not overlap in the original releases of the code.  Later on, however, new requirements from our customer required the first operation to be used again, after the second operation had changed the value of the shared instance variable.  Because one variable was used for two purposes, the code was now broken and a hunt for the bug ensued.  Once the problem was discovered the solution was to simply add a second variable for the second purpose.

There is nothing clever about eliminating a variable.  Following the maxim, "a variable for every purpose, and a purpose for every variable," saves money.  There is a difference between efficiency and laziness.

Robert