[Tutor] Global Variable Gotcha

Alan Gauld alan.gauld@blueyonder.co.uk
Wed Jun 25 03:13:01 2003


> I must rewrite code in the newly seperated functions so
> that the global object is passed as a parameter. 

That's the clean and theoretically "best" solution since it 
follows good functional programming principles of "no side 
effects". If you  have the freedom to do so, then go ahead.
Of course sometimes you need to maintain the interface as-is
(because of reuse etc) in which case fudges become necessary.

There are several solutions:
1) write a function to set a reference in your new module 
that gets called from the original
- bad because the first is now tightly coupled to the second

2) import the first into the second
- bad because the copupling now exists the other way round

3) create a third module for the shared code and import into 
both original modules - if you must use globals this is probably 
best but may break existing code which already uses the global from
the original module
 
> I'd welcome comments on how to avoid this(passing as an argument)

Why do you feel the need to avoid using an argument?
It is the best, (ie most pure) solution to the problem promoting 
much better levels of reuse and extensibility of your code.
All the opther options compromise the solution by building in 
undesirable dependencies(coupling).

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld