The discussion around global variables and their misuse seems to hold a a certain dogmatic tone to it. I am not here to dispute the "globals are bad" concept as it makes sense to me why they are bad. However I was wondering if people had some interesting code snippets that demonstrate exactly how to effectively refactor higher scoped variables and objects out of the code. In this question I am looking for examples or patterns of generic but useful solutions to the "I need to use a global variable here because it is easy" problem.
Here is a hypothetical and perhaps contrived example. I am using the global variable to keep track of the parameters sent to a function. And then if there is a failure that happens further down the chain I could go back and call the function again using parameters from the global variable.
public var myGlobalState:Object = new Object();
public function addPerson (name:String, person:Object, personCount:int, retryCount:int):void
{
myGlobalState = null; // clear out old values
myGlobalState = new Object();
myGlobalState.name = name;
myGlobalState.person = person;
myGlobalState.personCount = personCount;
myGlobalState.retryCount = retryCount;
person.userId = personCount + 1;
person.name = name;
savePerson(person);
}
public function savePerson (person:Object):void
{
// Some code that attempts to save the person object properties to a database...
// process returns a status code for SUCCESS of FAILURE
// CODE TO SAVE TO DATABASE ....
// Return status code ...
if (status == "fail")
{
// Retry at least once by calling the addPerson function again
if (myGlobalState.retryCount < 3)
{
addPerson (myGlobalState.name, person, myGlobalState.personCount, myGlobalState.retryCount);
}
}
}