[Tutor] global vars vs. func args

Scott Widney SWidney@ci.las-vegas.nv.us
Fri, 8 Mar 2002 09:51:04 -0800


On Friday, March 08, 2002 at 4:43 AM, Erik Price wrote:
> On Thursday, March 7, 2002, at 01:31  PM, Kirby Urner wrote:
> 
> > I find this a good way to use IDLE because you can build
> > up your modules by "unit testing" each piece (each
> > function or class) as an individual unit.  This tends to
> > promote good habits, as your units have more standalone
> > integrity if they have to bear up as testable, versus
> > relying on global variables or side effects smeared all
> > over the place.
> 
> So instead of global variables, it's good form for functions 
> to simply use arguments and act upon those?  If this is what
> you're saying, I can see that, since it makes the code more
> reusable in scripts that don't provide these same [global] 
> variables.
> 
> Isn't using a globalized variable just a way to save time/space 
> by not having to declare it as an argument?
> 
> Always curious about good style,
> 
> Erik

The term that Kirby mentioned, "side effects", is mentioned all over the
place in Functional Programming land. Functions should not have
side-effects; which is to say that functions should receive data, operate on
that data, and return the results. The function shouldn't touch anything
outside of this scope. The idea behind it is not unique to FP though; and,
as you can see, there are several Tutors on this list that encourage this
philosophy in Python programming, too. [You'll really reap the rewards when
you start fiddling with objects: encapsulation relies on effective
partitioning.]

So, yes, the idea is to pass as arguments everything that a function needs
to do its thing. And there are drawbacks to using globals. Foremost in my
mind is: how do you keep track of which functions are reading/modifying it?
Especially in a large project? Data integrity and data access is a real
concern.

One big benefit of avoiding side effects is that you can remain confident
that these functions won't mess with any of your structures and/or data
without explicit permission.

Of course, having said all that, there are those rare times when using a
global makes sense. "The most important thing about knowing the rules is
knowing when to break them."


Scott