Re: Scope for Beginners
Re: Scope for Beginners
- Subject: Re: Scope for Beginners
- From: "Mark J. Reed" <email@hidden>
- Date: Sat, 16 Jun 2007 10:18:26 -0400
On 6/16/07, Ruth Bygrave <email@hidden> wrote:
Is this an example of the stuff Matt N says in his Applescript book
about scope and why not to use global variables, or is there
something else happening I haven't understood yet?
No, you're just running into a problem with property persistence.
Totally different issue, pretty much unique to AppleScript, while
misuse of global variables is a nearly universal problem across all
programming languages.
And in fact, a value that doesn't change over the course of the
script's run is a perfect candidate for a global variable. You can
declare it at the top and it becomes a sort of source-code-embedded
configuration parameter that you only have to change in one place if
you want it to be different later. If the language supports making it
unmodifiable by the code, that's even better.
When global variables become a problem is when you have situations like this:
set i to 1
repeat while i < 10
someHandler();
end
on someHandler()
{
set i to 1
repeat while i < 10
... do stuff
end
}
If i is a global variable, then the loop in the main code will only
execute once, rather than 10 times, because someHandler is changing
its value. It's easy to construct other problematic cases.
The main reason we put code into handlers/subroutines/functions is
chunking: we turn a whole series of steps into a single logical step,
which we can then use as building blocks for more complex logic. It's
easier to build a wall when you have a pile of bricks than when you
have a bunch of clay. From the point of view of the code that calls
it, someHandler is a black box, a single action, and its innards
shouldn't matter. But because of the global variable, those innards
are leaking out and breaking the calling code.
--
Mark J. Reed <email@hidden>
_______________________________________________
Do not post admin requests to the list. They will be ignored.
AppleScript-Users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
Archives: http://lists.apple.com/archives/applescript-users
This email sent to email@hidden