View Single Post
 
Old 06-09-2002, 02:15 AM
loquin's Avatar
loquin loquin is offline
Google Hound

Retired Moderator
* Guru *
 
Join Date: Nov 2001
Location: Arizona, USA
Posts: 12,400
Post Scope that!

"A place for everything and everything in it's place." When growing up, that's what my Mother would tell me, as with a firm grasp on my ear, she marched me towards my room. Of course, Mum was talking about the state of my closet, and not about programming. Those words DO have application in the world of programming though.

Of course, we have a different term for that idea. It's called 'Scope.' So, that being said, what do we mean by the word scope, anyway?

Essentially, scope defines where a variable will be used. Visual Basic allows three levels of scope. Procedure level, or Local scope is confined to a Sub or Function. Form level scope is confined to a given form (or module.) And Global scope is defined as anyplace within a project.

There is only one simple guideline to follow in regards to scope. You shouldn't define a variable so that it can be accessed outside the local programming area unless there is a good reason for doing so.

Well, that's simple enough. But why? What is the basic reasoning behind such a rule? The answer to this question is a pragmatic one. By doing so, we all will have less opportunity to screw up. Essentially, it's awfully easy to be working in a procedure and inadvertently use a variable name that you intended to be used in another place entirely. If you defined the variable scope too broadly, VB won't complain. It assumes that you know what you are doing. (That's a scary thought, isn't itů ) Then, unexpected things can happen, results that are sometimes very hard to find a reason for. And, to troubleshoot...

As I mentioned earlier, Visual Basic's three levels of scope are Procedure level, Form Level, and Global. Details of the three levels follow.

Procedure Level Scope: The variable is said to be Local. It can't be accessed outside the procedure. And it is safe. You know that your variable CAN'T be changed from the outside. This isolation of the local properties enables you to make your code modular: Write a small portion of the main code. Test It. Then, forget it. The use of procedure level variables is efficient from a memory usage viewpoint also. When the procedure runs, memory is allocated at that time, and this memory is released when the procedure finishes. If you have to have a Sub or Function level variable which needs to stay present in memory between calls to the procedure, you may declare it using the Static keyword:
Code:
Static intWinSockPort as Integer
In this manner, the variable remains local, but will stay in memory (and retain it's value) between procedure calls.

Form (Module) Level Scope: There are two types: Public or Private. The Private Form level variable is available by all the functions or subs within the form, but is not available outside the form. This is useful when defining a variable that pertains to the entire form. A Public form level variable is available to all functions and Subs inside the form, and is also available outside the form by referencing the form and the variable name. Essentially, a public form level variable appears as a new property of the form. For example, assume that you want to create a simple form called frmUserInput to obtain user input. You would create the form, and at the top of the form code, add a public variable called strFormResponse. From another form, you would then access the new variable like this:
Code:
UserResponse = frmUserInput.strFormResponse
Of course, you could also write to the variable in the same manner. However, since you specifically have to refer to the form name as well as the variable, the risk of accidental data corruption is small. Since data transfer between forms is a common requirement, I've attached a sample project which provides an example of this.

Global Scope: In your module code in a project, you may also define public and private variables and constants. In a similar manner to the form level variables, those defined as Private in a module are only accessible from subs and functions within the specific module. If they are defined as Public, however, they may be accessed from any code in any module or form. (The old convention for the public module variable is "Global." The global keyword has been made obsolete by the Public keyword, and is only included in VB 6 for backwards compatibility with older code.

Keep in mind that a public module variable is dangerous to use; any code, anywhere in the project may read or write to this variable. And, since the variable is not associated with a form, it is referred to by name; just as if it were a local variable. Even IF you are using the recommended "Option Explicit" setting you may accidentally refer to a public module variable. Another disadvantage of public module level variables is that memory is assigned to them when your application loads, and this memory is not relinquished until the program shuts down.

A word about "Option Explicit". Use it. Always use it. What it does for you is simple. It won't let you compile or run a program if you haven't explicitly defined all your variables. In other words, there must be a Dim VariableName as VariableType for every variable in your code. If you don't use option explicit, VB will implicitly define a variable if you don't. And, there's a couple of problems with this. First, VB will pick a variant type, which is compatible with many different variables. However, a variant is probably the largest and most inefficient of all variable types, which may have performance implications. Variants also sometimes won't work for your purposes. The second main problem with VB defining a new variable for you is that often, the reason for a new variable is not that you don't have one, it's that you mis-typed the correct variable name. This means that either your new variable or your old variable will be "orphaned," which can lead to logic errors in your program that can be hard to spot. Visual Basic even has an option setting so that the words "Option Explicit" will automatically be added to each and every new form as you create them. Just go to the Tools, Options menu and select the check box labeled "Require Variable Declaration."

In spite of the dangers involved with using public module level variables, in some instances, especially with constants, they can be invaluable. I'm NOT saying "Don't use public level variables," I'm suggesting that you use them carefully.

Essentially, the golden rule in regards to scope is "Always define your variables at a scope level no higher than is necessary for proper function." By doing so, you can ensure that your code remains as modular as possible, and will not have its operation inadvertently changed by external code.

So, just remember, as I'm figuratively holding on to your ear, "It's for your own good, and it hurts me more than it hurts you, andů"
Attached Files
File Type: zip ShowDataXfer.zip (2.6 KB, 168 views)
__________________
Lou
"I have my standards. They may be low, but I have them!" ~ Bette Middler
"It's a book about a Spanish guy called Manual. You should read it." ~ Dilbert
"To understand recursion, you must first understand recursion." ~ unknown

Last edited by loquin; 11-08-2007 at 12:16 PM. Reason: Add zip attachment, and reference to same.
Reply With Quote