< previous page page_402 next page >

Page 402
0402-01.gif
Figure 8-2
Side Effects
the function stores a temporary result into one of the reference parameters, accidentally changing the value of an actual parameter back in the calling code. As we mentioned before, using value parameters avoids this type of side effect by preventing the change from reaching the actual parameter.
Side effects can also occur when a function accesses a global variable. An error in the function might cause the value of a global variable to be changed in an unexpected way, causing an error in other functions that access that variable.
The symptoms of a side effect error are misleading because the trouble appears in one part of the program when it really is caused by something in another part. To avoid such errors, the only external effect that a function should have is to transfer information through the well-structured interface of the parameter list (see Figure 82). If functions access nonlocal variables only through their parameter lists, and if all incoming-only parameters are value parameters, then each function is essentially isolated from other parts of the program and there are no side effects.
When a function is free of side effects, we can treat it as an independent module and reuse it in other programs. We cannot reuse functions with side effects.
Here is a short example of a program that runs but produces incorrect results because of global variables and side effects.
//******************************************************************
// Trouble program
// This is an example of poor program design, which
// causes an error when the program is executed

 
< previous page page_402 next page >