围绕全局变量及其滥用的讨论似乎持有某种教条主义的基调。我不是在这里对“全局变量不好”的概念提出异议,因为对我来说它们为什么不好是有道理的。但是我想知道人们是否有一些有趣的代码片段来准确地演示如何从代码中有效地重构更高范围的变量和对象。在这个问题中,我正在寻找“我需要在这里使用全局变量,因为它很容易”问题的通用但有用的解决方案的示例或模式。
这是一个假设的,也许是人为的例子。我正在使用全局变量来跟踪发送给函数的参数。然后,如果在链的下游发生故障,我可以返回并使用全局变量中的参数再次调用该函数。
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...
// The 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);
}
}
}