This question was brought up during a Standards discussion, which should revolve around SOLID Principles for Object Oriented Development.
In your experiences, have you seen benefits or drawbacks in either code readability or performance based on whether variables are passed ByRef vs Module-Level Variable?
Obviously: If a method calls a submethod, which will not only use but also modify a parameter, it should be passed as a reference pointer (aka: ByRef).
Based on this logic, some in my discussion are very strict to never use module-level variables.
In response, I say we have a toolbox and should know when to use what tool. For example, a sub declares a variable. That sub calls a function, which calls a sub, which calls a function, which calls a sub, etc etc, and eventually that variable is changed 10 methods down the line.
I’d say make that variable a module level, whereas some say pass it ByRef through your tree of methods.
So where is the line when examining SOLID OOP Principles?
Do you go with an extreme?:
Never use ByRef, or Never use Module-level Variables.
Or do you set a routine depth?:
1-method, always ByRef; 2 deep, consider it; 3-depth, Module-level Variable.
Or maybe a Branching Principle?:
If, in your list of methods, the variable is really only updated in one place then passed ByRef all the way back up to the original… ByRef them all. But if the variable is changed during multiple stages in multiple branches of the tree of methods, make it a module level.
If the latter is the case, should that also mean 20 methods down the line, ByRef all the way back up to the original is still fine? Or maybe a hybrid of these possible rules. What’s your take on it?
First off, in programming rules there are no absolutes. Every rule that is stated as an absolute has its share of exceptions.
With that out of the way, you should avoid using module-level variables as much as you should avoid global variables. Apart from the portion of the program that can access them, the two share the same problems.
Just about any advise against using global variable applies equally well to module-level variables.
5