
Originally Posted by
Irmaxx
@6StringJazzer
I forgot to ask: "What does your earlier remark, see quote below, entail?"
Global variables create an undesirable degree of data coupling.
Coupling is how tightly different modules are connected together by virtue of how they communicate. The most desirable coupling is loose, to keep modules as independent as possible from other modules. This minimizes the chance that making a change in one module will require a change in another module, and also makes tracing data easier in case of a bug.
The loosest coupling is passing variables as arguments. This creates a kind of a contract with a Sub that says, "Here is the data you will give me, and here is the data I will give you back." Nothing else happening outside the Sub should affect it.
Common data coupling is tight coupling. When several subs share the same data, a change in how one Sub uses data that could affect any other sub that shares the data.
There are many other types of coupling.
This I already know and I use this method of programming a lot.
But my main issue here is whether or not I should 'declare' and 'set' objects every time in every Subs as they are needed OR like I did in the attachments in the beginning to be used everywhere?
If you declare everything once globally, then use them everywhere, then there is no contract. The sub could get something that it wasn't expecting. Here is an example.
The programmer's original intent was to read a value, calculate using it, then write it back. But there is nothing that enforces that is the way the code has to be used. If another line of code is added
Now an unexpected value appears in the cell, and you have to read every line of code in every sub to figure out what may have happened.
This is kind of an oversimplified example. When you get more complex code that uses global variables it can be a nightmare to diagnose when you get a result you don't expect.
And when I 'declare' and 'set' objects every time in every Subs as they are needed, do I end those Subs with Set Object = Nothing?
You should not have to set an Object to Nothing at the end of a Sub but many people feel it is a good practice. When you create an object, space is allocated dynamically, and the variable points to that space. When the Sub exits, the space is still allocated, but the variable is gone so nothing points to it anymore. When the system discovers this condition it will deallocate the space. This process is called "garbage collection." There is some discussion about how good garbage collection is in VBA. I have never had a problem but with complex programs it is possible that space is not deallocated in a timely manner, or deallocated ever. When unused space is not deallocated it creates what is known as a memory leak.
So it never hurts to set your objects to Nothing.
Bookmarks