Invalidation Manager
Introduction
Invalidation is a pattern employed to solve problems where updating a model’s data may happen multiple times per frame, but updating the view’s rendering should happen only once. When dependencies exist between multiple models this can get complicated and potentially messy. This article looks at a solution to this mess by unifying invalidation logic into a single manager class.
The purpose of this discussion is not to offer a new class for people to take and use in their libraries so much, though you are welcome, if you should want to. Rather it is to discus a problem and my solution. Hopefully some people will learn something from reading it, and hopefully I will learn something by getting feedback about it!
The Invalidation Pattern
Consider the following simple implementation for drawing a coloured circle:
public class Circle extends Sprite
{
private var _color:uint;
private var _radius:Number;
public function get color():Number { return _color; }
public function set color(value:Number):void
{
_color = value;
resolve();
}
public function get radius():Number { return _radius; }
public function set radius(value:Number):void
{
_radius = value;
resolve();
}
private function resolve():void
{
graphics.clear();
graphics.beginFill(_color);
graphics.drawCircle(0, 0, _radius);
graphics.endFill();
}
}
The problem here is that if in one frame I changed both the radius and the color, the resolve() function would be called twice. Though not a problem in this case, it could be if the resolve() function involved a lot of complex logic.
The invalidation pattern resolves it this way:
public class Circle extends Sprite
{
private var _color:uint;
private var _radius:Number;
public function get color():Number { return _color; }
public function set color(value:Number):void
{
_color = value;
invalidate();
}
public function get radius():Number { return _radius; }
public function set radius(value:Number):void
{
_radius = value;
invalidate();
}
public function invalidate():void
{
... at some future point of my choosing, trigger resolve() ...
}
public function resolve():void
{
graphics.clear();
graphics.beginFill(_color);
graphics.drawCircle(0, 0, _radius);
graphics.endFill();
}
}
Often in AS3, the invalidate() function looks like this:
public function invalidate():void
{
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
resolve();
}
It is a good pattern that solves the problem of multiple resolve() calls. The actual mechanism contained inside invalidate() which causes resolve() to be called once at a convenient point is unimportant. For this sort of structure, this simple implementation does the job.
Where The Invalidation Pattern Becomes Complicated
Imagine that you have two classes: a line, and a circle, the intersection of which defines two circular segments. In fact, don’t imagine: look at this:
Both the line and circle implementations consist of two points which, on moving, invalidate the their equations. On resolve() the equations are resolved. The segments depend upon the the line and circle; when the line or circle is invalidated, they should be invalidated also.
A mechanism for the segments to know when their definiens (that which defines them) are resolved is required, suggesting that each element conforms to a common interface:
public interface Invalidates
{
function invalidate():void;
function get invalidated():Signal;
function resolve():void;
}
and an implementation along these lines:
public class Line implements Invalidates
{
private var _ax:Number;
private var _ay:Number;
private var _bx:Number;
private var _by:Number;
private var _invalidated:Signal;
public function Line()
{
_invalidated = new Signal(Invalidates);
}
public function get ax():Number { return _ax; }
public function set ax(value:Number):void
{
_ax = value;
invalidate();
}
... missing a few uninteresting methods ...
public function invalidate():void
{
_invalidated.dispatch(this);
}
public function resolve():void
{
... resolve the line ...
}
}
public class Segment implements Invalidates
{
private var _line:Line;
private var _circle:Circle;
... missing the constructor ...
public function get line():Line { return _line; }
public function set line(value:Line):void
{
_line = line;
_line.invalidated.add(onInvalidated);
}
... missing a few uninteresting methods ...
private function onInvalidated(definien:Invalidates):void
{
invalidate();
}
public function resolve():void
{
_line.resolve();
_circle.resolve();
... the rest of the resolution ...
}
}
The problem here is the same problem that led us to consider the Invalidation Pattern in the first place: namely, that the Line’s resolve() method is going to get called a lot. Sure, we can pack the methods with lots if calls like:
private function invalidate():void
{
if (_isInvalidated)
return;
_isInvalidated = true;
invalidate();
}
public function resolve():void
{
if (!_isInvalidated)
return;
_isInvaldiated = false;
_line.resolve();
_circle.resolve();
... the rest of the resolution ...
}
However, it starts to feel like the classes are consumed with handling the invalidation management, rather than with what should be their single responsibility of properly modelling the geometrical entities for which they are named.
An important feature of this implemenation is that it guarantees that the Line’s and Circle’s resolve() methods are called before the sgement resolves. If B depends on A, then A must resolve before B resolves. This is a key feature of the Invalidation Manager, below.
Managing Invalidation
The current as3geometry library attempts to solve the problem of invalidation using the InvalidationManager.as class.
The Invalidation Manager handles classes that satisfy the Invalidates.as interface. Invalidates objects can be registered to the InvalidationManager, and dependencies can be established. As this happens, objects are categorized into tiers.
Initially, since every object is independent of each other when registered, newly registered elements are considered in tier 0. However, if a dependency is established such that B depends on A, B is put into the tier above A, so if A is in tier 0, B is in tier 1. If then C depends on B, since B is already in tier 1, C goes into tier 2.
The utility of the tiers comes from the fact that all objects in tier 0 are independent of each other and may be resolved in any order. Tiers are resolve in ascending order, ensuring that any object that is depended upon is resolved before any object which depends on it.
The problem with this approach comes when, for example, A depends on B depends on C already so they have the following tiers:

Then, if I have another object D already in tier 3, and define that B depends on D, I must move B to tier 4 and therefore also move C to tier 5.

Circularity presents an interesting problem within this system. If A depends on B depends on C, and then I define that C depends on A, the tier system breaks down. Currently attempting to create a circular reference will fail and an error will be thrown.
In order to keep the InvalidationManager clean, it does not actually handle when it resolves, but instead dispatches a signal when it has elements that require resolution. In the as3geometry implementation the AS3GeometryContext.as wraps the InvalidationManager and hooks it to the player events to so that when invalidation occurs it is resolved in good time.
The Invalidates classes, other than telling the contxt what it has a relationship to and what it does not, no longer contains any code that tries to manage other objects’ invalidations:
public class Line implements Invalidates
{
private var _ax:Number;
private var _ay:Number;
private var _bx:Number;
private var _by:Number;
private var _context:InvalidationManagerContext;
private var _invalidated:Signal;
public function Line(context:InvalidationManagerContext)
{
_invalidated = new Signal(Invalidates);
// elements that don't depend on other classes like this don't really need the
// context stored, but I store it here for consistency, and in case the structure
// changes
_context = context;
context.register(this);
}
public function get ax():Number { return _ax; }
public function set ax(value:Number):void
{
_ax = value;
invalidate();
}
... missing a few uninteresting methods ...
public function invalidate():void
{
_invalidated.dispatch(this);
}
public function resolve():void
{
... resolve the line ...
}
}
public class Segment implements Invalidates
{
private var _line:Line;
private var _circle:Circle;
private var _context:InvalidationManagerContext;
private var _invalidated:Signal;
public function Segment(context:InvalidationManagerContext)
{
_invalidated = new Signal(Invalidates);
_context = context;
_context.register(this);
}
public function get line():Line { return _line; }
public function set line(value:Line):void
{
_line = line;
_context.addDependency(_line, this);
}
... missing a few uninteresting methods ...
private function onInvalidated(definien:Invalidates):void
{
invalidate();
}
public function resolve():void
{
... just resolve here! this is the big win ...
}
}
Conclusion
A benefit to this approach is that Invalidates classes need very little boiler-plate code. The author of an Invalidates class need know only that changes should call invalidate() and that all resolution logic happens in resolve(). Responsibilities are extremely well separated.
The as3geometry implementation wraps the InvalidationManager into an AS3GeometryContext.as class that has a little more logic than the InvalidationManager, which does not have a mechanism for actually triggering the mass resolution. While the InvalidationManager handles the internal logic set-out above, the AS3GeometryContext handles hooking up the InvalidationManager to the player events.
There is a downside, of course. Currently in as3geometry, the constructor of every class contains a reference to the AS3GeometryContext, and every class stores a reference to it. It is not clear to me that this approach is avoidable, unless the manager is defined as a singleton. There are lots of good reasons why singletons are bad, not least because I might have good reason to have two parallel geometric contexts in one application.
Parabolas and Quadratic Bezier Curves
As a follow-up to my as3geometry update on parabolas and quadratic bezier curves, I wanted to record the mathematics used to make the translation from parabola to quadratic bezier curve. Hoping to avoid the work of thinking about this for myself, I went online to understand the relationship, but could not find the calculation explained anywhere. The answer presented itself once I started to draw this diagram in Illustrator. It is amazing how a well-drawn, careful diagram can give you the insights you need!

The parabola is defined by the directrix AB and the focus C
It was apparent from the diagram that:
- H is the midpoint of the line segment AC;
- AD is perpendicular to AB, and HD is perpendicular to AC, so D can be calculated as the intersection of these lines;
- J is the midpoint of the line segment BC;
- BE is perpendicular to AB and JE is perpendicular to BC, so E can be calculated as the intersection of these lines;
- K is the intersection of the lines JE and HD, so E can be calculated as the intersection of these lines;
- The parabolic segment defined by the line segment directrix AB and the focus C is also defined by a quadratic bezier curve with the start point D, the end point E and the control point K.
The full calculation (with some different variable names I’m afraid!) was codified in the ParabolaDrawer.as class.
as3geometry – Parabolas
The as3geometry library has been neglected of late, but I have managed to push out a couple of important updates this week: the invalidation manager and parabola handling. I will discuss the invalidation manager later in the week since it is quite a technical and complex update. The implementation of parabolas is rather more straightforward.
Parabola defined by a line and vertex
The Flash plugin is required to view this object.
view source | click-and-drag the red points to interact
Parabola segment defined by a line segment and vertex:
The Flash plugin is required to view this object.
view source | click-and-drag the red points to interact
Usefully, a parabola (which, precisely, is “the locus of points equidistant from a point and a line”) can be expressed as a quadratic bezier curve. The implementation ‘simply’ finds the three control points of a quadratic bezier curve and then uses the Flash Player’s Graphics.curveTo method to draw.
Error #2078 on Flash IDE publish – Gotcha
I just spent a couple of hours creating an asset in the Flash IDE, and when I went to publish this FLA with absolutely no code except one stop(); in it, I got the following error:
Error: Error #2078: The name property of a Timeline-placed object cannot be modified. at flash.display::DisplayObject/set name() at flash.display::Sprite/constructChildren() at flash.display::Sprite() at flash.display::MovieClip()
The culprit? I had named a MovieClip instance within the IDE “name”, which the Flash player doesn’t like at all. It would have been good of the IDE to warn me of this problem (ie, scan the named MovieClips in an FLA and check for reserved words), or give me a more graceful error message, but sadly not. Instead I had to find it the hard way – changing stuff and publishing, changing stuff and publishing, changing stuff and publishing… Hopefully this will save someone a few minutes!
[Embed(source="asset.swf")] Gotcha (and Workaround)
It’s been a long-time without a post. Part of the reason for that has been starting work at a new job (which involves a commute), and part has been that as part of my new job, I was actually encouraged to spend time playing World of Warcraft. To me, that’s like taking a crowbar to Pandora’s Box and having a peek inside. I learned quite a lot, but have also played just a few too many Warsong Gulches.
Back to work, and I was doing a little prototyping this evening, when I came across a familiar problem: In AS3 we can use
[Embed(source="asset.swf", symbol="symbol")] private var symbolClass:Class; var symbol:MovieClip = new symbolClass();
to embed a symbol from an art SWF in what is probably a code-built SWF. That’s great, but what if you want to embed an entire SWF?
[Embed(source="asset.swf")] private var assetClass:Class; var asset:MovieClip = new assetClass();
looks like it should do the trick, but you can’t access any of the information within the asset. That’s a real pain, the reason for which is pretty convoluted. I remembered working around this problem in the past, and happily managed to unearth a long-forgotten treasure in my codebase, which I thought I’d share (having rapidly refactored it to use as3-signals, naturally).
package com.alecmce.util
{
import org.osflash.signals.Signal;
import mx.core.MovieClipAsset;
import flash.display.Loader;
import flash.display.LoaderInfo;
import flash.display.MovieClip;
import flash.events.Event;
public class UnpackEmbed
{
private var _ready:Signal;
private var _asset:MovieClipAsset;
private var _content:MovieClip;
public function UnpackEmbed(assetClass:Class)
{
_asset = new assetClass();
_ready = new Signal(UnpackEmbed);
var loader:Loader = Loader(_asset.getChildAt(0));
var info:LoaderInfo = loader.contentLoaderInfo;
info.addEventListener(Event.COMPLETE, onLoadComplete);
}
private function onLoadComplete(event:Event):void
{
var info:LoaderInfo = LoaderInfo(event.target);
info.removeEventListener(Event.COMPLETE, onLoadComplete);
_content = MovieClip(info.loader.content);
_ready.dispatch(this);
}
public function get content():MovieClip
{
return _content;
}
public function get ready():Signal
{
return _ready;
}
public function get asset():MovieClipAsset
{
return _asset;
}
}
}
When you embed a SWF in this way then instantiate it, Flash somehow conspires to create a MovieClipAsset with a Loader inside, which will be ‘loading’ the already-embedded content. The content is not available immediately (it may be sometimes, I have encountered cases where it was not), so you have to wait for an Event.COMPLETE to be fired before you can access it. This class exposes a signal that informs you when the content is ready. It could probably be more rigorous, such as including an isComplete flag, but it serves my purposes, when used in the following manner:
[Embed(source="asset.swf")]
private var assetClass:Class;
asset = new UnpackEmbed(assetClass);
asset.ready.addOnce(onAssetReady);
private function onAssetReady(asset:UnpackEmbed):void
{
// now we can access the asset.content!
}
Why we need Generics in AS3
Introduction
Almost not a day goes by that I write some code destined for a library and wish that Adobe had implemented generics for AS3. Generics is the ability to specify a type that will be used within a class without explicitly defining the type. If you are developer that has started coding for player 10, then you’re probably familiar with the Vector implementation. This is currently the only place that generics exists in AS3, and it sticks out like a sore thumb. Generics are useful for one main reason: it is easier to write code that can be massively re-used if you can use generics. More code reuse means less code. Less code means smaller applications, faster code, and more time for better features. There are few down-sides to generics.
What Are Generics?
Object pooling is something I need to do reasonably often. I would like to be able to create an interface that allows me to describe some common features of an IObjectPoolable item, such as a reset() method that could be called to clear out any data particular to an ‘instance’ of the object. I would then like to be able to specify an ObjectPool class and specify which kind of IObjectPoolable type it is pooling. Then, when I call ObjectPool.consume(), I don’t have to type-cast the object it gives me, because the compiler knows what kind of object it is. It knows, because I defined it when I constructed the ObjectPool.
The code for such a class might look something like this:
class ObjectPool.<T:IObjectPoolable>
{
private var _pool:Vector.<T>;
private var _index:uint;
public function ObjectPool.<T>()
{
_pool = new Vector.<T>();
_index = 0;
}
public function alloc(count:uint):void
{
for (var i:uint = 0; i < count; i++)
_pool.push(new T());
}
public function dealloc(count:uint = 0):void
{
if (!count)
count = _pool.length;
_pool.length -= count;
}
public function consume():T
{
return _pool[_index++];
}
public function release(object:T):void
{
var i:uint = _pool.indexOf(object);
if (i == -1)
throw new Error("You cannot release an object into a pool that it does not come from");
object.reset();
_pool[i] = _pool[index];
_pool[--index] = object;
}
}
T in the above example stands for the type which the ObjectPool pools. Of course, I can’t test this code so there may be logical errors, but hopefully you see where I’m going with this.
Perhaps you think that I could do the same thing without generics, by adding run-time checks into my code. That will make the code slower than it should be, and in order to check whether it works I’ll have to run it because errors will only arise at run-time. Compile-time checking is better than run-time checking.
Perhaps if I have Robot objects and Donkey objects I could create two object-pool classes: a RobotObjectPool and a DonkyObjectPool class? That implies that for each IObjectPoolable object that I create I will also need to create a new object pooling class. That’s bad in so many ways. It means less code reuse (in fact, I may end up copying-and-pasting code into classes!), the application’s code weight will increase (fewer bangs for your bytes), there are more places where errors could creep into my code, and I have to spend all that extra time creating all those extra classes.
A Related Limitation of interface
You may have noticed that in the alloc method above I am constructing the type using new T(). Within the interface IObjectPoolable I have no way of enforcing that the constructor requires no arguments. I should have, either by being able to specify:
public interface IObjectPoolable
{
function IObjectPoolable();
}
or
public interface IObjectPoolable
{
function new();
}
or something like C#, in the ObjectPool class itself, specifying new() to indicate a parameterless constructor:
class ObjectPool.<T:(IObjectPoolable,new())>
Note also that to illustrate generics I chose an example in which I wanted to be able to restrict T to a particular set of types, using <T:IObjectPoolable>. This is elegantly done in C#, it should be done in ActionScript too.
Vector.<T>
Currently one implementation of generics exists, for Vector.<T>. On the face of it, it is extremely perplexing why generics have been implemented only for Vector, but there are practical reasons why Adobe can’t simply roll generics out. The Vector.<T> was implemented because of a realisation that iterating over Array represented a specific performance overhead that Adobe could do something about.
During his recent visit to the Flash Gaming Summit, Nicolas Cannasse explained to me that Vector is a hack comprising three classes under the hood. In fact, Adobe engineers have created Vector.<int>, Vector.<Object> and (I think – though this one is hazy) Vector.<Number>.
UPDATE: Robert Penner informs me that I remember this incorrectly. There are in fact four Vector implementations. Follow the link to the comment below for more details.
The two numerical implementations are designed to give specific speed improvements when iterating over collections of numbers. The Vector.<Object> implementation is the catch-all for all other type. However, Adobe has clearly done the work necessary for compile-time checking that the type being passed into the Vector.<Object> is preserved throughout the code.
Adobe then has done a lot of work towards implementing generics, but the Vector implementation was a specific workaround. As we are probably all aware, there’s a huge difference between a workaround and a truly flexible feature.
haXe
If I like generics, why not start using haXe, since haXe has generics already built in?
There are a few reasons why I’m reluctant to go down the haXe road at the moment.
- Firstly, there’s code I write for myself, and code I write for my work. The work code has to be AS3. I find it harder writing in two dialects of the same fundamental language than I do writing to completely different languages.
- Then, there’s the prospect of having to rewrite almost everything in my library. If I move back into a self-employed mode in the future, then there is little doubt that I’ll adopt haXe, but if I’m doing this in spare time, it is a daunting task.
- Then there’s the lack of haXe support in FDT. This is going to change soon, but until I can write haXe without having to give up the tools that I love to work with, that represents a significant barrier to entry.
In many ways, haXe blazes far ahead of AS3 for these sorts of language requirements. It is frustrating that AS3 lags behind haXe when AS3 has a team and corporation behind it, while haXe has a handful of extremely talented people. If AS3 can’t iterate closer to haXe and soon, there may be no option but to go down the haXe road in the next few months.
Issues
With generics there are certain complications that should be addressed. The most subtle of these is something I highlighted in my article The Problem with Vector<T>. I incorrectly argued that the following should be ok:
public interface Fruit; public class Apple implements Fruit; var fruits:Vector.<Fruit>; var apples:Vector.<Apple> = new Vector.<Apple>(); fruits = apples;
The problem was really that perhaps I had a makeSmoothie(Vector.<Fruit>) method somewhere that expected Vector.<Fruit>, I would have to construct a new Vector.<Fruit> and pass in each member from Vector.<Apple> before then passing that newly constructed object into makeSmoothie. This seemed like an expensive overhead to me.
My brother Ewan pointed out that this is not straightforward. He wrote three articles on this:
- the first exploring the problem of trying to add an
Orangeto thefruitsvector, and the consequences surrounding that; - the second discussing how C# 4.0 has the potential functionality to get around that problem, by defining two generic types, so that perhaps a class could be defined as
Vector.<Fruit, Apple>, where essentially the first type is the exposed type (what you get if you reference an index in theVector), while the second type is the required type (what type is allowable to be set as a reference for an index). - and finally an article which explains the concepts behind the C# 4.0 implementation from it’s core concepts of covariance and contravariance.
Conclusions
This stuff it extremely complex; it is a can of worms that if AS3 did implement generics it would have to consider and take seriously. Though designers complained about AS3′s complexity over AS2, I doubt anyone can seriously argue that AS3 wasn’t a huge step forward in terms of potential and power. ActionScript is now grown up, but it is still young and it still has lots to learn. Now Adobe are creating tools that allows designers to produce many of the more simple functionalities in Flash without having to touch code. That’s great in my opinion, it allows people like me to spend more time developing more interesting stuff that can’t be tied down to a drop-down menu in Flash CS5. I have a good toolset for that right now, but I want and need more tools. While the IDE and player evolve, the language is standing still.
The ActionScript developer community is a huge asset for Adobe. We are the heart of the Flash Platform. Right now, it’s much stronger than most people give it credit. For example, Microsoft’s new KIN website was developed in Flash, not Silverlight! This is surely because the UI developer talent still works in ActionScript for Flash, not in C# for Silverlight.
However, this can change quickly. The Flash Platform is now clearly challenged, from Apple, HTML5 and Silverlight. Many developers are considering migrating to other languages and platforms. Many have retooled to work on Objective-C, Android, and HTML5. Many work in multiple languages. The danger for Adobe is that gradually more and more people drift away from using ActionScript as their day-to-day language of choice. If people move elsewhere and the quality of Flash content starts to wane, Adobe’s power-base dissolves with it.
ActionScript needs to evolve. It could do worse than evolving to support generics.
3-Party Swingometer
The BBC coverage of UK elections is well-known for its use of the Swingometer. The Swingometer represents parliamentary constituencies as points on a line. A central point represents equality between the two major parties: the Labour Party (red, politically centre-left) and the Conservative Party (blue, politically centre-right). How far from that central point the seat is to the left or right denotes how strongly that seat is held by Labour or the Conservatives respectively, and how big a shift in opinion is required for the seat to fall into the other party’s hands.
However, if two parties can be compared one-dimensionally, then three parties can be compared two-dimensionally. In many ways, the UK has a three-party parliamentary system. The Liberal Democrats hold a position in UK politics far stronger than any other party that would be considered ‘others’ (see political notes below). It is not inconceivable that at some future point the Liberal Democrats could displace one of the two major parties, and after the upcoming general election their roll could be the most significant for a generation if – as the polls have been predicting – the UK experiences a hung-parliament.
This small application was the product of a day or so prototyping, using Bit 101′s Minimal Components and RobotLegs to see if I could come up with something a bit more interesting than theBBC’s online Swingometer. It lacks the BBC’s finesse (which is unsurprising for a very quick prototype), but I think it is rather more fair to the Liberal Democrats.
The Flash plugin is required to view this object.
Political Notes
Several smaller parties exist, notably the Scottish National Party and Plaid Cymru, the Welsh nationalists. However, these do not have UK-wide reach, and swings to or from either party will not have large national implications, simply because the populations of Scotland and Wales are so much smaller than that in England.
Northern Ireland politics is also omitted from this graph. The source data did not contain Northern Ireland data, but I have not sought to add it either, since Northern Ireland has a quite different political system which is largely based on religious and cultural social differences; the trends in the rest of the UK do not apply to Northern Ireland, and vice versa. Its data would be trivial for the purposes of this visualisation.
Apparently, the change of popularity in the Liberal Democrats has caused the BBC to change its use of the swingometer over the years. They reduced the role of the swingometer as the Liberal Democrats’ power grew in the seventies, and reintroduced it as it waned in the eighties and nineties. Now, the current implementation on their website has three swingometers that can be tabbed between. It is strange then that they haven’t chosen to adopt a more sophisticated representation.
The source data that I used for this application can be found at pippanorris.com. The limitations of the data is most evident in the 1997 election data. The landslide Labour victory is masked by the omission of most of the Scottish constituencies. The problems with historical data are frustrating. If any better data source is known, I would love to know of it.
Ifs and Buts and Strings
It has been a fun morning in the twitterverse. @kaeladan (aka David Wagner, my replacement at Yomego, and friend) tweeted that:
Dear Flash programmers, stop using if( foo ) or if( !foo ) to check if an object is null. It’s both Bad and Wrong. Luv, K #dodgylibraries
To support the argument, David put this gist on github:
var iAmAStringInstance :String = "";
var iAmANullString :String = null;
if(iAmAStringInstance)
trace("iAmAStringInstance: That there is an instance!");
else
trace("iAmAStringInstance: That there is a null object!");
if(iAmANullString)
trace("iAmANullString: That there is an instance!");
else
trace("iAmANullString: That there is a null object!");
It took me a while to understand what I had trouble with in David’s tweet, but the gist helps. The trick is that the semantic label that David has applied to the if (foo) conditional is not correct in the context of a String. If we use if (foo) we are not in fact testing for existence. We are testing for existence and non-triviality. The implication that all we’re doing is testing for existence versus nullity comes from the trace statements within the conditionals. These are well-meant, but misleading.
That David used a String for this example is significant. A typed object reference can only resolve to false if it is null. String is one of the few ambiguous cases, like a Number or an Object (which is ambiguous because it could be a String or a Number).
Once we got going some people argued that we should change the language so that an empty string or 0 casts to a Boolean as true. Clearly this is a hypothetical decision, since you can’t change the API of a language after the fact. They have a point in terms of consistency with a typed Object I suppose, though I think it’s a over-the-top to argue as DavidArno does that:
@alecmce The idea that a non-zero length string is true and a zero-length string is false is a broken paradigm. That was my point.
That’s a bit strong I think. How often does it break down your code? Sometimes, it is positively useful that an empty string (or 0) casts to Boolean as false.
I often want to test whether something is substantive. Take a URL for example – potentially someone could have initialised a variable for a URL in the constructor, or potentially it could be null. I want to know if it’s been filled in, so I can use if (url) to test for that. It would be as annoying in this brave new paradigm to have to write if (url != "") as it would to have to write if (url == null) in the current one.
To go back to the example then, we need to be careful to be clear about what our code actually means:
if(iAmAStringInstance)
trace("iAmAStringInstance is neither null nor empty");
else
trace("iAmAStringInstance is either null or empty");
if(iAmANullString)
trace("iAmANullString is neither null nor empty");
else
trace("iAmANullString is either null or empty");
In one sense then, I agree with David, though not in the sense he intended. It goes over Twitter’s character limit, and it’s rather less pithy, but perhaps he might have tweeted:
Dear Flash programmers, stop using if( foo ) or if( !foo ) to check if an untyped object, string or number is null. It’s Bad and Wrong in these particular contexts, if what you really are trying to do is to check for existence, rather than substance..
Ordering ENTER_FRAME events
About ENTER_FRAME
If you create multiple listeners to one event, then the listener methods run in their priority order (or if priority doesn’t differentiate, in the order that they were registered to the event).
If you create a listener for an ENTER_FRAMEon a display object, then it dispatches ENTER_FRAME each frame.
When an ENTER_FRAME listener is created for an object, the object is added to the end of a list of objects that need to dispatch ENTER_FRAME. It doesn’t matter what the relationship between the objects are, the ENTER_FRAME listeners of whichever object was added to that list first fire before objects later in the list.
Maybe that’s obvious to you; I don’t find it obvious. Without thinking about it, I want a high-priority listener to run before a low priority listener, irrespective of the objects to which they are listening. At least intuitively, I think of ENTER_FRAME as a universal event, rather than emanating separately from each object.
The Problem
The difficulty with this is that I cannot control the order in which ENTER_FRAME calls happen over an application. I can’t, for example, create an ENTER_FRAME listener for a Sprite and make sure that it runs before any other existing ENTER_FRAME listener across the application. I can make sure that for the particular Sprite it runs first by using priority, but the only way I can re-order the objects that dispatch ENTER_FRAME is by temporarily removing (and subsequently re-applying) every listener for each object ahead of it in the list
For RacetrackStats, a project that I am currently working on which attempts to measure the time that it takes to execute code and to render the screen, I want to be able to ‘get in first’ and ensure that a particular ENTER_FRAME listener is the first method that runs in an ENTER_FRAME cycle. The only way I can do this is by telling the developer who uses the RacetrackStats library to construct the RacetrackStats instance before doing anything else, and then keeping an ENTER_FRAME listener registered from that point onwards, even if the stats package is not on the stage and not being used.
Most of the time this isn’t a big deal. Normally the function of an ENTER_FRAME listener in an object is internal to that object, so a conflict between the code running in two different objects’ ENTER_FRAME listeners is unlikely.
Tickers and Signals
The most simple solution to this problem – if it is a problem – is to use only one object to dispatch ENTER_FRAME events. If you use some form of dependency injection like Swiz or RobotLegs this can be done relatively painlessly, since you can inject the dispatching object wherever it’s required. Then, you can use priority to determine the order in which listener methods run.
A related solution might be to use a Ticker; essentially to have only one ENTER_FRAME listener which iterates through a collection of methods that you subscribe to it and runs those in order. The linked example is a very simple Ticker, but more complex functionality like priorities would be relatively easy to add.
Similarly, you could use as3-signals and wrap the stage’s ENTER_FRAME into a native signal event. This would give you all the functionality you are likely to want ‘out of the box’. If you feel like you need to have a greater level of control over your ENTER_FRAME, this is probably the way to go. This is my preferred solution – at the moment!
Example
Hopefully the description demonstrates what I mean. If you’d like a more concrete demonstration, then you can build this file and inspect it’s output:
Fast 2D Arrays/Vectors (and the Game Of Life)
Introduction
I was recently looking at an implementation of Conway’s Game Of Life, and was struck by the way in which the developer had constructed his grid. The Game of Life requires that you construct a two-dimensional array, but Flash does not support 2D arrays natively, so work arounds have to be found. There are slow workarounds, fast workarounds, and very fast workarounds. Of course, for very fast workarounds, we use Vector and target the Flash Player 10.
An example of Conway’s Game Of Life can be found below.
I should point out at the start that in these I am using for (var x:int = 0; x < 100; x++) loops. Using while (x--) or even while(--x > -1) may well be quicker, but here I am trying to highlight the relative speeds of the data structures that are being looped around, not the loops themselves.
Slow
public function generate():void
{
grid = [];
for (var x:int = 0; x < 100; x++)
{
grid[x] = [];
for (var y:int = 0; y < 100; y++)
{
grid[x][y] = Math.random() < 0.5;
}
}
}
public function retrieve(x:int, y:int):Boolean
{
return grid[x][y];
}
This is the slowest good method around. It's undoubtedly good, in that it is readable and concise. It's not so good in terms of speed though, because of the double Array reference that is required to get to the relevant reference. Array lookups are slow, and should be avoided in performance-critical areas.
Fast
public function generate():void
{
grid = [];
for (var x:int = 0; x < 100; x++)
{
for (var y:int = 0; y < 100; y++)
{
grid[x * 100 + y] = Math.random() < 0.5;
}
}
}
public function retrieve(x:int, y:int):Boolean
{
return grid[x * 100 + y];
}
Instead of putting your 2D grid in a nested array, we can just use a one-dimensional array, and use an expression x * 100 + y within the lookup to differentiate between cells.
If you're targetting the version 9 player still, then this is probably the fastest mechanism you're going to get. (there is probably no need to, the latest Flash player penetration statistics suggests about 95% adoption in the western hemisphere, and above 90% adoption elsewhere)
Fast (again, but with Vector)
public function generate():void
{
grid = new Vector.<Boolean>(10000, true);
for (var x:int = 0; x < 100; x++)
{
for (var y:int = 0; y < 100; y++)
{
grid[x * 100 + y] = Math.random() < 0.5;
}
}
}
public function retrieve(x:int, y:int):Boolean
{
return grid[x * 100 + y];
}
Moving to use the FP10 Vector class gives you some great benefits. The Flash Player can be told up-front how big the array is going to be, and it knows the type of element. It is all-round quicker to do it this way. However, this is not the quickest structure we can use!
Faster
public function generate():void
{
shift = 7;
grid = new Vector.<Boolean>(100 << shift, true);
for (var x:int = 0; x < 100; x++)
{
for (var y:int = 0; y < 100; y++)
{
grid[(x << shift) | y] = Math.random() < 0.5;
}
}
}
public function retrieve(x:int, y:int):Boolean
{
return grid[(x << shift) | y];
}
By referencing the cell using [x * 100 + y] we get the computer to do a multiplication and an addition. That's pretty quick, but while we consider these two of the most primitive mathematical operations, they are not two primitive calculations for a computer! Instead, we can use [(x << shift) | y] which replaces the multiplication and addition with a bit-shift and a bitwise disjunction. They are about as simple calculations as a computer can make, and the time it gains us is small, but significant if we are working with big grids.
I do not intend to go into the details of bitwise operations here, but for further reading, try this Wikipedia article.
Interestingly, if you try this approach with Array, it does not run as quickly as the example labelled 'Fast'. This is because, as Jackson Dunstan and JP Auclair noted, it will leave 'gaps' in the Array (for example no values will be entered in the above Vector for values, 100 - 127. For a Vector of a known size, that is not a performance problem, but Arrays work differently.
Results Summary

The results on the horizontal access are milliseconds that it took to iterate through the grid 1000 times. The difference in speed by adopting Vector and the bitwise-shift approach is to cut the calculation time by nearly a quarter. The bigger the grid is, the more this technique becomes useful.
After-Thought - Game Of Life
The Game Of Life is a grid structure, in which each cell is a Boolean switch; either 'on' or 'off'. Iteratively, the grid changes, according to a very simple instruction set:
- Each grid cell's value is determined by the values of the eight adjacent grid cells;
- For each cell, If exactly three of those adjacent cells are 'on', then in the next iteration, that cell will be 'on';
- For each cell, if two adjacent cells are 'on' then in the next iteration that cell will remain in it's current state;
- Otherwise, that cell's value in the next iteration will be set to 'off'.
At the edges, either those cells just have fewer neighbours, or the neighbours are thought to 'wrap around' the 2D space, so that the cells' universe resembles a torus in 3D space.
The result of these simple rules is an interesting pattern which is very interesting for a great number of reasons. The example below should show you what I mean. It will run only when the mouse is over the application. Click on it to break the iteration cycle and populate the cells with random data.
The Flash plugin is required to view this object.
