Kenneth Ismert
kismert at gmail.com
Tue Sep 20 15:54:34 CDT 2011
Steve, Jim, Gustav: In VBA, standard modules are a kind of static class. Modules can have Properties, and employ data hiding through private member variables, just like a class. Modules can't be instantiated, and have no initialization method, similar to other static class implementations. So, Steve is right in a way: Jim's CurDb function can be viewed as a global method of a static class. In response to Gustav's argument that discipline is all that is needed to use global variables properly, I say that works well for single programmers, but it is begging for trouble with multiple programmers. A construction like Jim's makes the intent of the global much more apparent. But, in defense of Gustav, Jim's construction only works for 'set once' globals. What about globals that need to change over time? How does one implement a changeable global in a 'safe' way in VBA? Put another way, once you allow a global property to be changed, you are in the same boat as a plain global variable: anyone can change it anywhere at any time. Any 'enforcement' scheme you put in place can easily be copied by a fellow programmer with access to the code to do the wrong thing at the wrong time. The question remains: is there any way to enforce safe global value modification in VBA, except by employing Gustav's discipline? -Ken Steve Goodhall: > I missed where you said standard module. So long as it's private I can > live with it, public would be anathema. > > Jim Dettman: > Well except for the fact that it's not in a class module<g>. It doesn't > represent a property. > > Steve Goodhall: > By definition, that's a class variable not a global. > > Jim Dettman: > There is nothing wrong with using a global variable like this: > > Private objcurDB As DAO.Database > > Public Function CurDb(Optional bolRefresh As Boolean = False) As > DAO.Database > > If objcurDB Is Nothing Or bolRefresh = True Then > Set objcurDB = CurrentDb() > End If > > Set CurDb = objcurDB > > End Function >