Visual Basic 2008 Programming: Business Applications with a Design Perspective
Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9
Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14 Appendix A Appendix B Appendix C Home
Loading
Last change: February 13 2016 18:48:19.

 Chapter in PDF

Table of Contents

Chapter 4: Data, Operations, and Built-In Functions
Last change: February 13 2016 18:47:36.
<<PreviousNext>>

Scope and Program Modularity

As you can see from the preceding discussion, a variable declared in the general declaration area is recognized by all procedures in the class. This also means that only one memory location is used to handle the variable. You may be tempted to declare all variables at the class level for convenience and to conserve memory; however, you should avoid this programming practice.

When a variable is recognized by all procedures, it is shared by all procedures. When the value of this variable is changed in one procedure, the result affects all procedures. In some cases (and too often), such a change may not be expected when you write your code. This coding practice makes the resulting program difficult to maintain. In addition, because of the duration of the class level variables, the memory use is not necessarily minimized; therefore, the general rule is to declare each variable with a scope as narrow as possible—that is, to the extent possible, declare the variables you need to use in the procedures where you need them and declare variables at the class level only if they absolutely have to be shared by more than one procedure. By declaring variables with the narrowest scope possible, you keep procedures independent of each other, which is the basic foundation of modular design.

Tip
When you absolutely need for the procedures to share certain variables, try to design your code such that each of these variables is assigned/changed in as few procedures as possible. This makes it easier to trace the source of the change when there is a problem. If the value of a variable needs to be changed to perform some operations within a procedure, and such a change is not intended for all other procedures, you should take care to restore the original value of the variable. This can be done by the use of a temporary variable, for example, a properly declared variable named TempVar, as shown in the following code fragment:
TempVar = YourVariable ‘Save the original value YourVariable = New Value ‘Change the variable to a new value ‘ Your code that uses the New value YourVariable = TempVar ‘Restore the value at the end
Last change: February 13 2016 18:47:36.
<<PreviousNext>>