Are Global Variables Really that bad ? (1 Viewer)

Solo712

Registered User.
Local time
Today, 03:09
Joined
Oct 19, 2012
Messages
837
I have recently veered into a discussion about global variables and received a handful of opinions from respectable contributors to AWF ranging from the the standard caution not to overuse them to the view that there is always a better solution than a global variable. I certainly do not accept the latter one, as I would not with any “rules” that are reflective more of a group-thing than a reasoned approach. In fact, in certain situations (spelled out further on) I consider a global variable or a set of globals to be the most logical and appropriate tool to use.
What really whetted my curiosity about the globals now apparently carrying the stigma of a spaggetti go-to factory was the origin of this conviction in the developer community. So I googled and googled to find some sensible discussion about what is good about globals and what is less so. I have not found much that was. I found a lot of shameless babble, though. The standard level of the discussion seemed to converge to this. Globals lead to bad, evil code launching nukes.
If you give pause for some thought to what is being shown and said in the link you will likely find two things: One, the example hopelessly exaggerates the effect of choosing global variables, and two, the silly mistake (of the kind everyone makes all the time) has not anything to do with the use of the global variable as such but rather with reversing the order of processing, in this case that of initializing and, "doing Something" with, the variable. The same type of mistake could have occurred with equal probability using a function or any language resource.
All things told I do think I would be more willing to consider restrictions regarding globals in low-level language like C++ because of the power of the language and its direct contact with some pretty sensitive resources and areas of memory. And yet even there, one gets the feeling the case against the use of global variables tends to be foggy and overstated.
Let’s look for example at the list of objections from here one by one:
Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be read or modified by any part of the program, making it difficult to remember or reason about every possible use.
Well, that is strictly QED. Some people write more readable and internally consistent code than others. Some people read code much better than others. The second statement is false. It simply assumes that the programmer does not have control over his program, which is assuming too much. There is no evidence that the memory of a programmer is impaired by the use of globals. It would have sufficed to say that if you use global variables, you need to be aware of them as having global scope and keep accounting of them in that scope.
No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its use can be easily broken or forgotten. (In other words, get/set accessors are generally preferable over direct data access, and this is even more so for global data.) By extension, the lack of access control greatly hinders achieving security in situations where you may wish to run untrusted code (such as working with 3rd party plugins).
Again, this protests too much. Naturally, if you create software in a team, rules need to be spelled out and adhered to. If a product is the work of a single developer, then it his/her ability to adhere to a plan and understand the effect of design decision that controls the use of resources, not the other way round.
Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings between variables and functions. Grouping coupled items into cohesive units usually leads to better programs.
I am not sure what specifically the writer has in mind by “coupling”. On the level of logical thought this principle simply assumes something is better than global variables instead of explaining why he thinks it is so.
Concurrency issues -- if globals can be accessed by multiple threads of execution, synchronization is necessary (and too-often neglected). When dynamically linking modules with globals, the composed system might not be thread-safe even if the two independent modules tested in dozens of different contexts were safe.
This of course is an issue, and not only on the thread level. There is a concurrency consideration in Access, specifically with different forms open at the same, theoretically being able to change the value of the variable. This extends further, if the program writes content of global variables into the tables of the database (which I don’t do, btw). So, yes, the effects of concurrency need to be considered.
Namespace pollution -- Global names are available everywhere. You may unknowingly end up using a global when you think you are using a local (by misspelling or forgetting to declare the local) or vice versa. Also, if you ever have to link together modules that have the same global variable names, if you are lucky, you will get linking errors. If you are unlucky, the linker will simply treat all uses of the same name as the same object.
No such thingl! There is a very simple way that makes this “pollution” miraculously disappear – at once. (see below).
Memory allocation issues -- Some environments have memory allocation schemes that make allocation of globals tricky. This is especially true in languages where "constructors" have side-effects other than allocation (because, in that case, you can express unsafe situations where two globals mutually depend on one another). Also, when dynamically linking modules, it can be unclear whether different libraries have their own instances of globals or whether the globals are shared.
Not all that applicable to Access except perhaps when doing some fancy work with COMs, custom OCX modules DLLs, etc.
Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean' environment between runs. More generally, source that utilizes global services of any sort (e.g. reading and writing files or databases) that aren't explicitly provided to that source is difficult to test for the same reason. For communicating systems, the ability to test system invariants may require running more than one 'copy' of a system simultaneously, which is greatly hindered by any use of shared services - including global memory - that are not provided for sharing as part of the test.
This again relates mostly to dev environments other than ours. In Access testing, the globals do not have any negative effect (that I am aware of) as the debug mode preserves the contents of all globals which aids in many instances in stepping through the execution.
It is interesting that after this list of reasons which in his eyes make globals unattractive Rishikesh Parkhe (the writer of the wiki article) makes some very sensible observations in their favour:
Why the Convenience of Global Variables Sometimes Outweighs the Potential Problems
• In a very small or one-off programs, especially of the 'plugin' sort where you're essentially writing a single object or short script for a larger system, using globals can be the simplest thing that works.​
• When global variables represent facilities that truly are available throughout the program, their use simplifies the code.​
Some programming languages provide no support or minimal support for non-global variables.
N/A​
• Some people jump through very complicated hoops to avoid using globals. Many uses of the SingletonPattern are just thinly veiled globals. If something really should be a global, make it a global. Don't do something complicated because you might need it someday.(my emphasis) If a global variable exists, I would assume that it is used. If it is used, there are methods associated with it. Colocate those methods in a single class and one has created a singleton. It really is better to specify all of the rules for use of a global variable in one place where they can be reviewed for consistency. The veil may be thin, but it is valuable.​
Now, of course, the question is “what is a global” ? I would say that a variable that holds data used by more than two forms / reports / modules, either throuout a session, or intermittently would most likely qualify for the honours. For my own purposes I routinely use global variables:
a. to set up and maintain session parameters: login status, name of logged in users, their privilege code, license info, activity marker for timer events (timeout), messages for custom message boxes, switches (read by master timer), etc.​
b. to maintain settings of forms: screen positions of popups, special effects, color schemes, etc.​
c. to pass strings around to forms (eg. custom splash screens) and report (mostly subheadings based on user report selection).​
d. For Whiteboard data in broadcasts or alerts about upcoming calendar events.
e. For data structures used to set up queries.
f. For switches controlling program execution (eg. release of quasi-dialog forms).
g. For session counters, and routine calculations used in decisions to trigger events.​

As for risks, deriving from the use of globals, in the greatest majority of cases an Access developer will only encounter two:

(1) I have noted one them above, “concurrency”. Your program will need to protect against two or more modules relying on the value same variable and yet both (or all) having access to writing it. You can’t really tell the sequence of events in which the reading / writing occurs because Access is an event-driven environment. How do you mitigate this ?
First, this problem would be way too more pronounced in a multi-user environment, but that level of risk is easily eliminated as an issue via splitting the DB into Front- and Back-End. As for a possible overwriting a global on account of it being shared between several modules at the same workstation, several measures exist, the simplest of which is the habit of setting the variable at the latest and re-initializing it immediately after use, in situations where more than one module can conceivably write into it.
(2) the possibility of serious problems on account of global variables’ getting lost is also a risk. But it is also grossly exaggerated. For starters, there is a very simple solution of how to eliminate this issue entirely and that is compiling the apps into accde form. Then all unhandled errors will terminate the program which solves the problem of “losing the globals” once and for all. This issue really is not as much a probem with the globals per se, but the development environment of Access which continues to miss on an obvious setting to terminate a session on a reset (or going into a design mode)! I have a hard time taking seriously professional developers citing globals as a data security issue. What ? Are they leaving the code in production dbs exposed to the users ? Letting Charlie Regular doing his own debugging ? Would that not be a far greater threat to the integrity of the database than some wily Thief of Baghdad making off with the loot of globals?

There are also some basic rules of thumb that one can follow that dispel much of the mythmaking about the hidden dangers inherent in the use of global variables. And it is mythmaking,make no mistake about it. Because, really there aren’t that many or that big problems despite some people developing a distaste for them by misapprehending the issues due to subscribing to a group-think. Common sense should dictate whether something should be use in place of a global variable.

• The first decision point I believe should be why not a global variable ? It is because whatever its shortcomings, a global variable will almost always be the simplest solution in passing data around Access objects. As Rishikesh says, “using globals can be the simplest thing that works”. Then why would one want to use something more complicated?
• Well, one usually wouldn’t use something more complicated but one would not want to fall into an indiscriminate use of globals, either. They may sometimes be clearly an overkill. There is a reason for scoping, and it is to keep resources used to accomplish something to a minimum. Don’t bring howitzer to swat a fly! It’s a good policy that helps to assure well-run programs. So if the scope for the variable is local (within a procedure) it should be local, if it is class then it should be class, and if it is global, then, yea Lord, there is no reason why it should not be global. “Don’t do something complicated” just because you think globals are bad, and experts would not use them. Use the least costly solution in terms of resources to get something done! If it is a global variable, it is a global variable.

• All that said, if you use globals, perhaps a few common-sense rules and testing of code should be observed:
a. make their scope known by naming them as globals, e.g. by a prefix “glb”, “g” or some such.
b. Make a habit of controling/checking which part(s) of the program write globals and (where applicable) keep the source of writing to a minimum (even at the cost of splitting the variable into two or three). Concurrency issues arise from writing variables, not reading them !
c. Learn to distinguish between different uses of globals. There may be variables that are session parameters, those controlling the settings of different forms, messages, flags, switches, etc. Some are transient settings controlling program flow. Some require more attention than others.
d. You may want to keep global variables (and constants) in a single standard module. Keep the different functional groups together as sections. This definitely helps orientation in a larger project. Comments on use will be welcome by anyone coming to admire your work.
e. In a serial use of a global variable, reset it to “empty” after each use. For Chrissakes!
f. In a dev environment, protect the modules against the loss of globals (those that have more than transient signifiance) by testing for a non-zero value in one of them and reloading the set if necessary in the form’s On Load event. (I usually leave this code in even in the accde, as it might be useful in the next version of the app).
g. Distribute production Access applications in accde format!
h. Don’t follow the leaders, watch the parking meters !​

If you don’t use globals, consider these options:
• In preference to manipulating Dialog forms to hidden and then closing them, you can open them as normal popup and then inhibit the return to the calling form until the called popup closes. While the popup remains open you can address the objects of the calling form directly as ([Forms]![CallingForm]![aControl]). The behaviour of this form will be the the same as the one open in a dialog mode without the restrictions attendant to the former. The user will not be able to interact with other form than the popup but the VBA code will have free access to all resources normally at its disposal.

Code:
‘in a calling from

      DoCmd.OpenForm “PopupAccessingMyControls”
      Do While IsLoaded("PopupAccessingMyControls ")
            DoEvents
      Loop

 ‘---------------------------------------------------------------
‘ in a standard module

Public Function IsLoaded(ByVal strFormName As String) As Boolean

' Returns True if the specified form is open in Form view or Datasheet view.

  Const conObjStateClosed = 0
  Const conDesignView = 0
  
  If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
      If Forms(strFormName).CurrentView <> conDesignView Then
          IsLoaded = True
      End If
  End If

End Function

This technique has a great potential in that it allows a sophisticated interaction between the two forms. In effect, it allows the execution loop to do stuff to the calling form based on commands from the Popup form. (I will be demo’ed soon in my own design of a generic Find Record utility)
• For session variables, i.e. persistent values that govern the behaviour of the forms, placements of objects, their visibility, colors etc. past a single session consider an excellent utility by Juan Soto. I am seriously considering using it.​

Best,
Jiri
 
Last edited:
What I don't like about globals is they can never be either deleted, nor can they be reused, with total confidence. You can never be totally sure, if you change a process that writes to or reads from a global, whether that is the last block of code that leverages that global, and I hate that kind of uncertainty in code.

To me globals are like burrs that cling to woolen socks, messy when they cling, and worse when you try to remove them.

My 2c,
Mark
 
What I don't like about globals is they can never be either deleted, nor can they be reused, with total confidence. You can never be totally sure, if you change a process that writes to or reads from a global, whether that is the last block of code that leverages that global, and I hate that kind of uncertainty in code.

To me globals are like burrs that cling to woolen socks, messy when they cling, and worse when you try to remove them.

My 2c,
Mark

Mark, seriously, isn't this more of a kneejerk than thinking through different possible scenarios? Is it true that you cannot reuse globals with confidence ? I mean, is it true in all cases ?

Case 1: Load info pertaining to a selection of report by the user into one or more globals to be referenced by the report as display strings and/or settings to formatting options. Reinitialize the global(s) for reuse. What level of confidence would you have that this setup will not mess the report up ? If it is less than 99.99% please explain why this should be so in this case.

Case 2: In the snippet of code in the OP I showed the use of "quasi-dialog form". I sometimes use a global variable instead of the function IsLoaded to hold the code. It is released from within the popup form just before closing. How can I claim I know that this is a foolproof method if I use it in dozens of forms in the app ? I know it is. Can you explain how I know or what it is one should not do if one chooses to do it with a global?

I could go on but I think I made my point.

Best,
Jiri
 
I'm not going to argue the case at all. It is a religious issue to the extent that what you believe alters how you validate the evidence, and I have already stated my values. There are believers and unbelievers, and that is one of the cool things about software.

Regards,
Mark
 
I'm not going to argue the case at all. It is a religious issue to the extent that what you believe alters how you validate the evidence, and I have already stated my values. There are believers and unbelievers, and that is one of the cool things about software.

Regards,
Mark

Fine, Mark, then don't argue the case. But calling it a 'religious issue' you are actually making my point, when I say that the naysayers in the discussion around the topic are not informed by a well-funded argument.

Incidentally, for those who wondered about this:
Solo712 said:
Case 2: In the snippet of code in the OP I showed the use of "quasi-dialog form". I sometimes use a global variable instead of the function IsLoaded to hold the code. It is released from within the popup form just before closing. How can I claim I know that this is a foolproof method if I use it in dozens of forms in the app ? I know it is. Can you explain how I know or what it is one should not do if one chooses to do it with a global?

Now if one analyzes the use of a global variable in a structure like
Code:
DoCmd.OpenForm “xxx”
Do While glbHold = True...LOOP
to close a form it can be said with confidence that it is safe no matter how many times it is used in an app and even if we don't know ahead of time which function / popup uses it. This is because the user only has access to it once to set it as TRUE. Once set, the user is inhibited from opening or interacting with other forms (where it may also exist) until the one using the global is closed with glbHold set to FALSE. The only way then this setup can be interfered with and the loop broken is by resetting the variable in VBA code. So if one designs software on the basis of logic and common sense, as opposed to religious superstition - a global variable - at least in this case, is safe (as anything in Access) and will do just fine.

Best,
Jiri
 
Last edited:
Too much of a good thing is not always good. There IS such a thing as making every variable global, which is probably NOT the most efficient layout possible.

Globals DO have a good purpose when you use them intelligently. I use globals (actually, Public variables in General modules) for a limited number of purposes.

1. Login-related data, machine-related data, session time data, and any other data that applies ONLY to the current session and that is reloaded if you exit the session followed by a re-launch.

2. To give names to commonly used things that are constant for my app but that are not Access, Office, or Windows constants. This explicitly includes things defined using either the Enum construct or a data-structure definition.

Anything outside of these uses, I would have to consider on a case-by-case basis. I still wouldn't give a blanket NO, but some things really SHOULD be of limited scope.

For instance, suppose I had a module that diddled around with Excel files. There is nothing wrong with the idea of keeping some declarations Private so that you are NOT tempted to write code that suddenly grows side-effects.

My viewpoint is more about bad habits that lead to a slippery slope than anything else. Like my own controversial viewpoints on closing what you open, I believe that there are many good uses for global (or at least widely visible) variables. They just are not the end-all and be-all for program data passage.
 
I think global variables are evidence of Adam’s sin of disobedience in eating from the Tree of Knowledge of Good and Evil. That knowledge should have been encapsulated, but instead Adam ate of the tree, and thenceforth ad hoc consumers could read the global value, and ad hoc producers could write to the global value, and in so doing encapsulation was broken, and a great evil was unleashed upon the world. ;)

IMO,
Mark
 
Jiri's has a clear case of Confirmation Bias. He dismissed opinions that contradict his own as "babble" and "mythmaking" while latching onto the one opinion that matches his own. He and that author both fail to acknowledge that there are often very good reasons to use something other than "the simplest solution".

He also dismisses the maintenance and development advantages of having the scope well contained, insisting that the developer can rely on their memory. Frankly this is a ridiculous position for obvious reasons.

It simply assumes that the programmer does not have control over his program, which is assuming too much. There is no evidence that the memory of a programmer is impaired by the use of globals. It would have sufficed to say that if you use global variables, you need to be aware of them as having global scope and keep accounting of them in that scope.

The overheads of such repeated accounting is entirely unnecessary without global variables.

A well constructed module is like a gated community of homes with each procedure being like a home. The external access to the community and its shared resources is via a gate where authorised access is defined and controlled. Each home can be sure of the integrity of the community resource.

Using a global variable in a procedure is like jumping out of a home window and climbing over the community perimeter fence to retrieve something abandoned on the side of the road and assuming (because there is no control over it) that it is in a usable state.

The well designed module can be reused in another application. It can be taken knowing that all required resources are explicitly defined in the interfaces. When a procedure expects a global variable it will break. But worse, it might find one in the new application and run with it.
 
And G's last two paragraphs are the "slippery slope" to which I referred.

If a given item is not being used session-wide then the odds are very high that it should not be treated globally.

Login info, session timing and security info, user privileges (if you went that way), host computer info, FE & BE pathing (if you are trying to protect people from directly opening the shared copy of the FE), and a few other items of that ilk would qualify for my loose definition of session-wide variables that have a REASONABLE purpose as globals.

The problem with too many globals is, as G pointed out, if you used one in a module and tried to port that code to another app, you carried broken goods with you. And this is part of the "mind set" that I sometimes talk about. There is a careful mind set that knows when a particular practice is good and when it is bad. If you avoid the bad unless you have extreme provocation, you are going to have fewer problems down the road.

In case anyone has forgotten, I am a pragmatist at heart and go theoretical only when I think it is appropriate. (O.K., stop snickering... I know I have a low threshold of "appropriate.") The pragmatist in me says that having globals is not all bad. But the word-order theoretician in me says that using ONLY globals IS bad.
 
Jiri's has a clear case of Confirmation Bias. He dismissed opinions that contradict his own as "babble" and "mythmaking" while latching onto the one opinion that matches his own. He and that author both fail to acknowledge that there are often very good reasons to use something other than "the simplest solution".
Galaxiom, I don't have nearly as much "confirmation bias", as you do since you need to misrepresent my position and argue ad-hominem. Neither Rishikesh nor I suggest that people use global variables because they are the simplest solution. Reread it! Also, I did not call someone's view "babble" because it argues against my position but because it does not make sense and argues with demonstrably bad examples. And when someone can't substantiate their convictions, they are engaging in "mythmaking". Mark actually confirmed this when he said this was a "religious argument".
He also dismisses the maintenance and development advantages of having the scope well contained, insisting that the developer can rely on their memory.
Again, both of these accusations are false, and brought forward simply because simply you don't have a more compelling argument.
The overheads of such repeated accounting is entirely unnecessary without global variables.
What do you mean by "overheads" ? What do you mean by "repeated" ? I did not say that. By "accounting for globals" I meant simply "be aware of them as globals". This should not represent any more strenuous effort to a programmer as having to grasp the difference between passing arguments to a function by value or by reference and choose the appropriate one.
A well constructed module is like a gated community of homes with each procedure being like a home. The external access to the community and its shared resources is via a gate where authorised access is defined and controlled. Each home can be sure of the integrity of the community resource. Using a global variable in a procedure is like jumping out of a home window and climbing over the community perimeter fence to retrieve something abandoned on the side of the road and assuming (because there is no control over it) that it is in a usable state.
I am sure some people here will find this style of arguing by metaphor compelling. I don't. I see it as cheap rhetoric which offers nothing of value. You choose to characterize the use of the global variable as something sneaky, not legit, unworthy, instead of showing us why this is so. This is very typical of a group-think.
The well designed module can be reused in another application. It can be taken knowing that all required resources are explicitly defined in the interfaces. When a procedure expects a global variable it will break.
No, it won't. You don't make any sense. If I design something, say a group of
interacting modules and they contain globals to exchange data between them, and the globals are shipped in one of the modules, then nothing is left abandoned on the road that I have to jump out of a window and over the fence to get. Nothing will break. You are talking through your hat.

Best,
Jiri
 
The problem with too many globals is, as G pointed out, if you used one in a module and tried to port that code to another app, you carried broken goods with you.

But "too many globals" is not what is being advocated here, is it ? Besides, nearly all my globals (constants and variables) are organized and packed into a module (one of the suggestions that I made in the OP) that automatically ports into a new app.

Let me restate my position, so we are not running at cross purposes. What I am saying, is: use globals where it makes sense, and don't allow yourself be bullied into beliefs that they are bad and their use invites disaster.

Best,
Jiri
 
...disaster...

giphy.gif


Mark :)
 
I also use global variables in many databases for the kind of uses stated by both solo and the doc man.

I also as a policy
1. Always define them in a dedicated module used for no other purpose
2. Tidy up after use by explicitly clearing their values at the end of sections of code.
Possibly overkill or unnecessary but it avoids potential issues.

I've been doing this for many years without problems but in most cases, I am the sole developer.
Problems can easily occur with their use when more than one person is involved writing code.

Having said all that, portability can be a big issue.
When I post examples of my code here, I have to go through checking and adding variable definitions that I had put in my dedicated module.
Similarly when applying the same code in other databases.
This can be time consuming.
One reason why I'm using them less and less.

I think that jiri is trying to express the view that many of the articles decrying their use are expressing extreme positions that aren't necessarily backed up by solid evidence.
Unfortunately, some of the arguments he raises are equally selective.

By all means use them in moderation and where beneficial to applying code globally but remember portability issues
 
I also use global variables in many databases for the kind of uses stated by both solo and the doc man.

I also as a policy
1. Always define them in a dedicated module used for no other purpose
2. Tidy up after use by explicitly clearing their values at the end of sections of code.
Possibly overkill or unnecessary but it avoids potential issues.

Not sure, why it would be overkill if it avoids potential issues.

I've been doing this for many years without problems but in most cases, I am the sole developer.
Problems can easily occur with their use when more than one person is involved writing code.

But then again you are thinking more a bunch of amateurs going bonkers with creativity. That does not happen in a real world of professional developers. I have taken as a model of handling globals a complex database utility written by a team of developers at Axios. The utility dumped data into Excel spreadsheets to perform data massages and other fancy stuff (like re-partitioning the Db) and import the tables back into the database. The code adapted itself to both SQL Server and Oracle (in different versions) as the back-end. It was really slick and a gold-mine for learning stuff and what passes for standards among developers of a large and successful commercial software.

ridders said:
Having said all that, portability can be a big issue.
When I post examples of my code here, I have to go through checking and adding variable definitions that I had put in my dedicated module.
One would expect people to test their creations before offering them at AWF.
That applies whether the modules contain reference to globals or not. So, again I don't think we are looking at anything beyond what I have stated in the OP. If you are using globals, be aware of their global scope and how it may affect your module. Better still, I would recommend when people offer standard modules for use here, they include all referenced public objects in them.
ridders said:
I think that jiri is trying to express the view that many of the articles decrying their use are expressing extreme positions that aren't necessarily backed up by solid evidence. Unfortunately, some of the arguments he raises are equally selective.
It would be good to know which arguments I have raised you consider "equally selective". I am always willing to explain myself. But please quote what I say, not what Galaxiom says I say.

Best,
Jiri
 
Last edited:
To boring to read the whole thread, but to derail it further:

...and argue ad-hominem

I know using Latin ispo facto boosts your credibility (e.g. in a debate, discussion et cetera) per se, but could you point out the ad-hominem part of Galaxiom's argument?

Ergo, if anything its vice versa. He accused you of being ad hominem (without actually using that term). Then presented facts to support that. GED.
 
To boring to read the whole thread, but to derail it further:



I know using Latin ispo facto boosts your credibility (e.g. in a debate, discussion et cetera) per se, but could you point out the ad-hominem part of Galaxiom's argument?

Ergo, if anything its vice versa. He accused you of being ad hominem (without actually using that term). Then presented facts to support that. GED.

:)
Hi plog. I understood all of that with the exception of the last 3 letters.
An acronym?
 
My guess is General Educational Development. It is what HIgh School dropouts get in lieu of a diploma. If I have that right, this thread is starting to get brutal and I am going to need some of MarkK’s popcorn...
 
Ha ha, nothing better than being a pompous prick online and doing it wrong. It should have been QED - quod erat demonstrandum. Mea culpa.
 
Jiri

I rarely get involved in this sort of thread, partly because the opposing arguments can often get more & more blinkered.
I think this may be happening here as well.

I read your first post in full and also skimmed the links.
You clearly spent a long time thinking your argument through & in my view stated your views well.

As I said, I also use global or public variables though less so than in the past.

However since that first post, I feel the level of debate has declined markedly.
I have no idea whether MarkK really does think globals are totally bad.
I'm fairly sure Galaxiom's views are genuine but I don't think you've helped your case in your responses to him.
However I'll leave it to Greg to respond further if he wishes

However I will reply to some of the points you made replying to me

Not sure, why it would be overkill if it avoids potential issues.

Because these will normally go out of scope when e.g. the form closes.
I just prefer not to take the risk

But then again you are thinking more a bunch of amateurs going bonkers with creativity. That does not happen in a real world of professional developers. I have taken as a model of handling globals a complex database utility written by a team of developers at Axios. The utility dumped data into Excel spreadsheets to perform data massages and other fancy stuff (like re-partitioning the Db) and import the tables back into the database. The code adapted itself to both SQL Server and Oracle (in different versions) as the back-end. It was really slick and a gold-mine for learning stuff and what passes for standards among developers of a large and successful commercial software.

Please don't assume you know what I was thinking.
The 'bunch of amateurs' comment was unhelpful to say the least.
I was referring to experience with a team of developers with widely differing backgrounds where it didn't work well
OK so in your case it worked with a team.
That doesn't mean it will always do so

One would expect people to test their creations before offering them at AWF.
That applies whether the modules contain reference to globals or not.

You may not have meant to imply the opposite but I can assure you I do thoroughly test everything I post to the repository or sample databases.
But using globals means it takes longer to make them work as standalone databases
If I were to avoid using global variables completely, sections of code I extract from my own databases would be instantly portable without the need to spend a long time 're-defining variables' so they work without errors before uploading.

Yes I could just transfer the modDefinitions module in which I place ALL globals.
I prefer not to do that as it would include lots of variables not needed for that item

===================
Nil illegitimus carborundum est
 
Here's a global I agree with...
Code:
Public Const PI_Double As Double = 3.14159265358979
Anything else I expose globally is a class instance. I almost always, for instance, write a cUser class that has rich data--like date/time of login, machine name, security info, prefs--about the current user. This class would be created automatically using WScript.Network.Username and drawing other data from a table. Another thing I commonly expose globally is...
Code:
private m_fso as Scripting.FileSystemObject

Public Property Get fso As Scripting.FileSystemObject
   If m_fso is nothing then set m_fso = new Scripting.FileSystemObject
   set fso = m_fso
End Property

I also commonly grab a ribbon reference from its OnLoad callback, and globally expose a ribbon wrapper class (which saves an ObjPtr() to said ribbon, in case it breaks, so I can automatically rebuild that reference)

Otherwise I only expose properties/functions that return classes as global resources that consumers can call. Sometimes these are initialized automatically, like fso, above, and sometimes they require some kind of start-up value. One system, for instance, has the concept of a CurrentJob, so that is a global object, but it requires a job number to be instantiated.

I never, ever, ever do this in a standard module as a means of data exchange between blocks of code.
Code:
Public StartDate as Date

I make no claim that what I do is "right." What I do is the way I like it. :)
Mark
 

Users who are viewing this thread

Back
Top Bottom