Have you gotten bitten in the ass by reference assigment lately?
References are cool. References are lightweight. References are bulletproof. Hmmm, not on the last one.
Reference assignment can really bite you in the S if you are not careful of its use. And more often times than not, because they are so darn convenient, you just wouldn't pay a second thought to using it...that's where the the ass-bitten timer starts counting down on you.
Take a look at this scenario:
Let's say you are building a puzzle game. You have an app that's pulling in dynamic data from your server. And you store it in your Game class property called puzzles.
Fine, now you can access the data via an instance of your game class, say game.puzzles.
Now, somewhere in your app, in order to make things easy to understand, you set a member variable to point to game.puzzles, like so:
class PuzzleManager
{
function PuzzleManager(game:Game)
{
_puzzles = game.puzzles;
}
function getCompletedPuzzles()
{
var completedPuzzles = new Array();
for (var p in _puzzles)
{
...check for score in each puzzle, pick out the ones with fullscore, etc.
}
return completedPuzzles;
}
}
Everything was working cool, until one day, your puzzle data requirement has changed. No longer do you just query your puzzle data at the start of the game. Now the puzzle data gets updated every time you finish solving a puzzle. That means game.puzzles points to a new set of contents every time you solve a puzzle. All good? No, your _puzzles member variable in PuzzleManager is still pointing to the old content, because reference in Actionscript acts more like pointer instead of reference in C++. That is, you are free to change your reference to point to anything during its lifetime, and just because you are pointing at what B is pointing at now doesn't mean it will always remain that way. At some point, B can be pointing at something else and you won't have a clue about it and remain pointing at the what B *USED TO* point to.
The moral of the story is - Use local variable where possible. Use reference assigment with extreme care.
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home