|Think about Loose Coupling|
Re: How will you use state declared variables in Perl6?by BrowserUk (Pope)
|on Jul 08, 2005 at 21:07 UTC||Need Help??|
So how will you use state declared variables
With great caution!
Globals are trouble, no matter how you label them. Closures are much safer.
In your example, foo() is a global sub, so there can never be two instances of it, but if foo() was a method, multiple instances of whatever class foo() was a method of, would all share the same %seen. Effectively, %seen becomes a Class variable. These can be useful--eg. counting the number of instances created or in existiance--but why not use a Class variable instead?
The danger lies in that if I inherit a new class from that class, instances of both classes will access and modify the single %seen. Whilst there maybe legitimate reasons to do this, they are much rarer and harder to see, as whatever values are contained in %seen, they will represent a classic mix of apples and oranges.
This is giving the potential to create the same sort of problems we see in Perl5 with it's global vars. Eg. $| & $/ & $\ -- Having to use one function (select), to control which handle setting $| will affect is a pita.
However, not having a similar possibility to control which handle, setting applied to $/ and $\ will affect, is worse. The separation and encapsulation of state is what makes OO so useful.
I can see state vars being used to hold things like DB handles (wrapped inside singleton classes if you must :), but done that way, it stops you from writing singleton factories. I also see problems with even this use.
If P6 objects are going to be usable across threads, then using state varibles for singletons is going to produce potential problems where, for example, DB handles can only be used from one thread.
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.