Public vs Global Variable Scope

shamas21

Registered User.
Local time
Today, 19:52
Joined
May 27, 2008
Messages
162
Hi All

Can someone explain when Public and Global variables lose scope and pros and cons of using both?

Thanks
 
I don't think there is a Global access specifier in VBA, the Public is the Global equivalent..
 
Public and Global variables are essentially the same thing if you are talking about Public and Global as declarations in VBA, so if you declare a variable . . .
Code:
Global ThisIsATest As String
. . . this appears in the object browser as if it was declared . . .
Code:
Public ThisIsATest As String
. . . so in this regard they are syntactically the same.

In general usage though, "global" can refer to scope directly, so you might declare a Private module level varaible, like . . .
Code:
Private m_moduleLevel as Object
. . . and the variable is "private," but it is said to be "global to the module in which it is declared." So all members of the module itself can see the private variable, but it is not visible outside the module in which it is declared.

The biggest drawback of using "application global" public variables is that you can never be certain when they were last written to, and so to be certain that they contain the value you expect, you should write to them just before you use them, but in that case, why write to them at all? Rather, yield that result directly to calling code without storing it. That is essentially the argument.

Also, a global is very hard to document because no piece of code "owns" it, and given that software is dynamic and subject to constant change, globals can easily get out of hand if you use them whimsically. I've seen lists of probably unused variables in people's code, and you can't delete anything or tidy up because maybe they're still in use, but who knows? So they can be messy, and they look like uncertainty because they just hang there, and uncertainty in code is a drag.

But it's a pragmatic sort of reality, like, robust alternatives to application-global variables require some coding skills, which are not super easy to get, and so discovering globals can also make your life way easier if you don't really know or care about robust code, and you just want to get your report working.

Anyway, there's my 2c on the topic

Pros: ease of use, simplicity
Cons: fragile, sloppy, undocumentable
 

Users who are viewing this thread

Back
Top Bottom