Programming Proverbs 11: Use intermediate variables properly
Intermediate variables are variables that are used to break calculations down into several steps. For example the use of intermediate variables takes something like this:
x = a + b * (sqrt(y) + w)
and turns it into something like this:
var1 = a + b
var2 = sqrt(y) + w
x = var1 * var2
Why would you do that? Well if you were using mnemonic names this would tell the reader what each piece of the calculation was doing. This also lets you use the individual sub calculations in other independent calculations. Your code may be more efficient that way.
Another example is when you want to use the result of a calculation several times. For example:
If (a + b * (sqrt(y) + w) ) > 0 then ans = "Big"
If (a + b * (sqrt(y) + w) ) = 0 then ans = "Same"
If (a + b * (sqrt(y) + w) ) < 0 then ans = "Smaller"
Doing things that way presents several possibilities that are not optimal. One is that the same set of calculations are ( or not - more on that later) done several times. Another is that any change that may be required to the calculation will have to be made three times. The potential for error is multiplied several times. Lastly that's a lot of typing. The more typing I do the greater my chances of making a typographical error. A better way of doing this is something like:
var1 = (a + b * (sqrt(y) + w) )
If (var1) > 0 then ans = "Big"
If (var1) = 0 then ans = "Same"
If (var1) < 0 then ans = "Smaller"
This saves typing, reduces the chances of error and makes modifications easier by keeping them in one place. The performance issue is not as simple as it once was though.
The need for this as a performance issue is largely diminished by modern compilers. Today's compilers know how to optimize calculations. Today the performance hit that intermediate variables were often used to prevent are mostly history. I'm not convinced that trusting the optimizer in the compiler is a good habit to get into. Especially not for beginners. I think that it is generally a good idea to make life easy for the compiler. There are also cases where optimizers are not going to be available and its better to develop good habits in advance. And the other values of intermediate variables remain as valid today as they always were.
This is the eleventh of a series of posts based on the book Programming Proverbs by Henry Ledgard. The index for the series is an earlier post and discussion of the list as a whole is taking place in the comments there. Comments on this "proverb" are of course very welcome here.