<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AlecMcE.com</title>
	<atom:link href="http://alecmce.com/feed" rel="self" type="application/rss+xml" />
	<link>http://alecmce.com</link>
	<description>Coding on the Flash Platform</description>
	<lastBuildDate>Sun, 07 Mar 2010 16:00:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Fast 2D Arrays/Vectors (and the Game Of Life)</title>
		<link>http://alecmce.com/as3/fast-2d-arrays</link>
		<comments>http://alecmce.com/as3/fast-2d-arrays#comments</comments>
		<pubDate>Sun, 07 Mar 2010 06:01:24 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=757</guid>
		<description><![CDATA[Introduction
I was recently looking at an implementation of Conway&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>I was recently looking at an implementation of <a href="http://en.wikipedia.org/wiki/Conway's_Game_of_Life">Conway&#8217;s Game Of Life</a>, 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.</p>
<p>An example of Conway&#8217;s Game Of Life can be found <a href="#example">below</a>.</p>
<p>I should point out at the start that in these I am using <code>for (var x:int = 0; x < 100; x++)</code> loops. Using <code>while (x--)</code> or even <code>while(--x > -1)</code> 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.</p>
<h2>Slow</h2>
<pre class="brush: as3;">
public function generate():void
{
	grid = [];
	for (var x:int = 0; x &lt; 100; x++)
	{
		grid[x] = [];
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[x][y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[x][y];
}
</pre>
<p>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.</p>
<h2>Fast</h2>
<pre class="brush: as3;">
public function generate():void
{
	grid = [];
	for (var x:int = 0; x &lt; 100; x++)
	{
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[x * 100 + y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[x * 100 + y];
}
</pre>
<p>Instead of putting your 2D grid in a nested array, we can just use a one-dimensional array, and use an expression <code>x * 100 + y</code> within the lookup to differentiate between cells.</p>
<p>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, <a href="http://www.adobe.com/products/player_census/flashplayer/version_penetration.html">the latest Flash player penetration statistics</a> suggests about 95% adoption in the western hemisphere, and above 90% adoption elsewhere)</p>
<h2>Fast (again, but with Vector)</h2>
<pre class="brush: as3;">
public function generate():void
{
	grid = new Vector.&lt;Boolean&gt;(10000, true);
	for (var x:int = 0; x &lt; 100; x++)
	{
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[x * 100 + y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[x * 100 + y];
}
</pre>
<p>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!</p>
<h2>Faster</h2>
<pre class="brush: as3;">
public function generate():void
{
	shift = 7;
	grid = new Vector.&lt;Boolean&gt;(100 &lt;&lt; shift, true);

	for (var x:int = 0; x &lt; 100; x++)
	{
		for (var y:int = 0; y &lt; 100; y++)
		{
			grid[(x &lt;&lt; shift) | y] = Math.random() &lt; 0.5;
		}
	}
}

public function retrieve(x:int, y:int):Boolean
{
	return grid[(x &lt;&lt; shift) | y];
}
</pre>
<p>By referencing the cell using <code>[x * 100 + y]</code> 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 <code>[(x << shift) | y]</code> 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.</p>
<p>I do not intend to go into the details of bitwise operations here, but for further reading, try <a href="http://en.wikipedia.org/wiki/Bitwise_operation">this Wikipedia article</a>.</p>
<p>Interestingly, if you try this approach with Array, it does not run as quickly as the example labelled 'Fast'. This is because, as <a href="http://jacksondunstan.com/articles/529">Jackson Dunstan</a> and <a href="http://jpauclair.net/2009/12/02/tamarin-part-i-as3-array/">JP Auclair</a> 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.</p>
<h2>Results Summary</h2>
<div style="text-align: center;"><img src="http://alecmce.com/wp-content/uploads/2010/03/Picture-6.png" alt="" title="Chart Showing The Relative Speeds of The Different Approaches" width="502" height="345" /></div>
<p></p>
<p>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.</p>
<h2>After-Thought - Game Of Life</h2>
<p>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:</p>
<ol>
<li>Each grid cell's value is determined by the values of the eight adjacent grid cells;</li>
<li>For each cell, If exactly three of those adjacent cells are 'on', then in the next iteration, that cell will be 'on';</li>
<li>For each cell, if two adjacent cells are 'on' then in the next iteration that cell will remain in it's current state;</li>
<li>Otherwise, that cell's value in the next iteration will be set to 'off'.
</ol>
<p>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.</p>
<p>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.</p>
<p><a name="example" /></p>
<div style="text-align: center;">

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="640" height="480">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2010/03/Main2.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2010/03/Main2.swf" width="640" height="480">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p><a href="http://gist.github.com/324161">source code</a></p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/fast-2d-arrays/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Introducing RacetrackStats v.0.0.1</title>
		<link>http://alecmce.com/as3/introducing-racetrackstats</link>
		<comments>http://alecmce.com/as3/introducing-racetrackstats#comments</comments>
		<pubDate>Tue, 02 Mar 2010 08:08:34 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=741</guid>
		<description><![CDATA[Introduction
RacetrackStats is an in-Flash performance profiler that gives real-time feedback about how the code it is contained within is performing. It can be found at GitHub:
http://github.com/alecmce/RacetrackStats
RacetrackStats is inspired by and seeks to move forward from Mr Doob&#8217;s Stats package (http://code.google.com/p/mrdoob/wiki/stats)
In Action
Below is the first alpha of RacetrackStats in action.


source: http://github.com/alecmce/RacetrackStats/blob/master/test/demo/RacetrackStatsDemo.as
The SWF comprises three small animations [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>RacetrackStats is an in-Flash performance profiler that gives real-time feedback about how the code it is contained within is performing. It can be found at GitHub:</p>
<h3 style="text-align: center;"><a href="http://github.com/alecmce/RacetrackStats">http://github.com/alecmce/RacetrackStats</a></h3>
<p>RacetrackStats is inspired by and seeks to move forward from <a href="http://twitter.com/mrdoob/">Mr Doob</a>&#8217;s Stats package (<a href="http://code.google.com/p/mrdoob/wiki/stats">http://code.google.com/p/mrdoob/wiki/stats</a>)</p>
<h2>In Action</h2>
<p>Below is the first alpha of RacetrackStats in action.</p>
<div style="text-align: center;">

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_1" width="660" height="500">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2010/03/RacetrackStatsDemo.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2010/03/RacetrackStatsDemo.swf" width="660" height="500">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
</div>
<p style="text-align: center;">source: <a href="http://github.com/alecmce/RacetrackStats/blob/master/test/demo/RacetrackStatsDemo.as">http://github.com/alecmce/RacetrackStats/blob/master/test/demo/RacetrackStatsDemo.as</a></p>
<p>The SWF comprises three small animations (from left to right):</p>
<ul>
<li>A mixture of computation and rendering: A simple BitmapData-driven particle system attempting to model smoke using 100000 pixels and a heavy glow filter and blur filter;</li>
<li>Heavy computation: A prime-factorisation algorithm, which computes 24 * 100 prime factor decompositions per frame. As it continues to run, the numbers get larger which leads to heavier calculation cycles;</li>
<li>Extremely heavy rendering: A cycadelic circle pattern that has hundreds of semi-transparent circular sprites moving around and overlapping with each other.</li>
</ul>
<p></p>
<h2>The &#8216;Elastic Racetrack&#8217;</h2>
<p>RacetrackStats attempts to go beyond Mr Doob&#8217;s Stats by measuring how the elastic racetrack is being stretched. The Elastic Racetrack was a phrase coined to describe how the original AVM1 Flash Player segmented each second into frames and attempted to balance the requirements of code, refreshing the screen and doing work like garbage collection. The AVM2 player&#8217;s model is sufficiently similar, that the name remains appropriate.</p>
<h3>Code Execution</h3>
<p>It does this by hooking into the Event.ENTER_FRAME and Event.RENDER events to record when portions of the code start and end. By recording when the ENTER_FRAME starts and when the RENDER starts, the intervening time is taken to be code execution.</p>
<h3>Pre-Render Code Execution</h3>
<p>Commonly this part of the code cycle is almost unused. If you exploit stage.invalidate and Event.RENDER in order for your classes to execute code after the main code execution has completed, then it will be captured here, between the top-priority Event.RENDER and the bottom-priority Event.RENDER calls.</p>
<h3>Rendering</h3>
<p>A problem is, the time between the RENDER ending and the ENTER_FRAME starting is used to draw the screen but if time is left over in which the Flash Player has nothing to do, it will idle during this time also. To counteract this, RacetrackStats attempts to throttle the FlashPlayer so that the application is always running as fast as it can, minimising, or even eliminating that idle time. I call this the &#8220;render&#8221; portion &#8211; the &#8220;Event.RENDER&#8221; event is badly named &#8211; screen rendering happens after the RENDER event has finished.</p>
<h2>Work To Do</h2>
<p>As soon as you add weight like this to an application, the speed at which it runs changes. By measuring the speed, you change the speed. It is the classic scientific paradox. It is mitigated by shrinking down the weight of the stats package as far as possible. At the moment, functionality rather than size is the chief concern, though I have tried to minimize the package by avoiding embedding fonts, and so forth.</p>
<p>I would love to hear what you think about the package, whether positive or negative. I&#8217;d also really appreciate it if you use it in your applications. If you have any problems, questions, queries or comments, please leave a comment below, or open an issue on GitHub.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/introducing-racetrackstats/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Gotcha &#8211; transform.matrix and scaleX/Y</title>
		<link>http://alecmce.com/as3/gotcha-transform-scale</link>
		<comments>http://alecmce.com/as3/gotcha-transform-scale#comments</comments>
		<pubDate>Tue, 23 Feb 2010 17:00:47 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[gotcha]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=720</guid>
		<description><![CDATA[I came across this gotcha for the first time today. Praise-be to ASUnit, without which this could have been extremely difficult to unearth:

// given two sprites called &#34;a&#34; and &#34;b&#34;...

a.transform.matrix = new Matrix(-.5, 0, 0, -.5, a.x, a.y);
b.scaleX = b.scaleY = -.5;

trace(a.scaleX, a.scaleY, b.scaleX, b.scaleY); // outputs: 0.5, 0.5, -0.5, -0.5

Both clips have been scaled [...]]]></description>
			<content:encoded><![CDATA[<p>I came across this gotcha for the first time today. Praise-be to <a href="http://asunit.org/">ASUnit</a>, without which this could have been extremely difficult to unearth:</p>
<pre class="brush: as3;">
// given two sprites called &quot;a&quot; and &quot;b&quot;...

a.transform.matrix = new Matrix(-.5, 0, 0, -.5, a.x, a.y);
b.scaleX = b.scaleY = -.5;

trace(a.scaleX, a.scaleY, b.scaleX, b.scaleY); // outputs: 0.5, 0.5, -0.5, -0.5
</pre>
<p>Both clips have been scaled by -0.5, but because the transform was used to produce the scale for a, the scaleX/Y variables do not reflect the object&#8217;s true scale.</p>
<p>Now, just to confuse yourself, add a third sprite to the stage:</p>
<pre class="brush: as3;">
// given another sprite called &quot;c&quot;...

c.transform.matrix = new Matrix(-.5, 0, 0, -.5, c.x, c.y);
c.scaleX = c.scaleY = -.5;
</pre>
<p>Curiouser and curiouser! This needed a more complete experimentation&#8230;</p>
<div style="text-align: center;">

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_2" width="550" height="400">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2010/02/scaleAndTransform.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2010/02/scaleAndTransform.swf" width="550" height="400">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

</div>
<p>The source for this experiment can be found here: <a href='http://alecmce.com/wp-content/uploads/2010/02/scaleAndTransform.zip'>scaleAndTransform</a>. The buttons call the following methods:</p>
<pre class="brush: as3;">
function onGo(event:Event):void
{
	a.transform.matrix = new Matrix(-.5, 0, 0, -.5, a.x, a.y);

	b.scaleX = b.scaleY = -.5;

	c.transform.matrix = new Matrix(-.5, 0, 0, -.5, c.x, c.y);
	c.scaleX = c.scaleY = -.5;
}

function onResetScale(event:Event):void
{
	a.scaleX = a.scaleY = 1;
	b.scaleX = b.scaleY = 1;
	c.scaleX = c.scaleY = 1;
}

function onResetTransform(event:Event):void
{
	a.transform.matrix = new Matrix(1, 0, 0, 1, a.x, a.y);
	b.transform.matrix = new Matrix(1, 0, 0, 1, b.x, b.y);
	c.transform.matrix = new Matrix(1, 0, 0, 1, c.x, c.y);
}
</pre>
<h2>What Is Going On?</h2>
<p>If you apply a transformation matrix then a scale, the magnitude of the scale is applied, but the direction is determined by the product of the transformation and the scalar&#8230; which is to say that:</p>
<pre class="brush: as3;">a.realScaleX = (a.transform.matrix.a * a.scaleX &gt; 0 ? 1 : -1) * a.scaleX;</pre>
<p>If however you apply a scale then a transformation, the scale is defined by the transformation only!</p>
<pre class="brush: as3;">a.realScaleX = a.transform.matrix.a;</pre>
<h2>Bug?</h2>
<p>Does this qualify as a bug? I haven&#8217;t thought about this for long enough. The conditions in which a transformation matrix rotates and skews the MovieClip confuse me; how would I define scaleX and scaleY in that scenario? I need to give this some thought; perhaps you the community can give me some help! I am reluctant to call anything a bug immediately now, after my experience with my <a href="http://alecmce.com/as3/the-problem-with-vector">The Problem With Vector.&lt;T&gt;</a> post, where I was just plain wrong!</p>
<p>A similar bug exists in Adobe JIRA: <a href="http://bugs.adobe.com/jira/browse/SDK-25247"> UIComponent.scaleX, scaleY differ from transform.matrix.a,d</a>. You&#8217;ll need an account to look at this &#8211; it&#8217;s free, and once you&#8217;ve got it you can pester Adobe with your bugs too.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/gotcha-transform-scale/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>When is a sub-class appropriate?</title>
		<link>http://alecmce.com/as3/when-is-a-sub-class-appropriate</link>
		<comments>http://alecmce.com/as3/when-is-a-sub-class-appropriate#comments</comments>
		<pubDate>Mon, 15 Feb 2010 17:00:22 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[composition]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[Liskov Substitution Principle]]></category>
		<category><![CDATA[polymorphism]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=694</guid>
		<description><![CDATA[My colleague Anatoly and I regularly need to create dialogs which pop-up in front of our application. Anatoly has created a class which allows the dialog to be configured by a packet of data which contains header, any text or images, button labels, footers, and information about how the buttons are processed, like this:

public class [...]]]></description>
			<content:encoded><![CDATA[<p>My colleague <a href="http://twitter.com/akarp">Anatoly</a> and I regularly need to create dialogs which pop-up in front of our application. Anatoly has created a class which allows the dialog to be configured by a packet of data which contains header, any text or images, button labels, footers, and information about how the buttons are processed, like this:</p>
<pre class="brush: as3;">
public class Dialog extends Sprite
{
	public function Dialog(data:DialogData)
	{
		... composes the dialog according to the data that is passed into it ...
	}
}
</pre>
<h2>Anatoly &#8211; Dialog Composition</h2>
<p>Let&#8217;s say that Anatoly wants to create a dialog in a particular view class (please ignore any other architectural considerations &#8211; I say &#8220;view class&#8221; broadly, hoping not to rile anyone who might shout &#8220;mediator&#8221;, which is beside the point in this case):</p>
<pre class="brush: as3;">
public class SomeClassWhereDialogsAreShown
{
	...

	public function onActionWhichTriggersExampleDialog():void
	{
		// this is a simplified structure to avoid complicating the point
		var header:String = &quot;This is Header&quot;;
		var body:String = &quot;This is body&quot;;
		var buttons:Array = [&quot;OK&quot;,&quot;Cancel&quot;];
		var data:DialogData = new DialogData(header, body, buttons);
		var dialog:Dialog = new Dialog(data);

		showDialog(dialog);
	}

	// this is one of many dialogs defined here...
	public function onActionWhichTriggersADifferentDialog():void { ... }
	public function onActionWhichTriggersAThirdDialog():void { ... }
	public function onActionWhichTriggersAFourth():void { ... }
	public function onActionWhichTriggersAFifthDialog():void { ... }
}
</pre>
<p>It is important to note that I have massively over-simplified the DialogData. It could be dozens of lines long, contain nested arguments, and so on. This point becomes part of the discussion later on.</p>
<h2>Me &#8211; Dialog Inheritance</h2>
<p>In contrast, I want to create a dialog sub-class and package away the dialog data:</p>
<pre class="brush: as3;">
public class ExampleDialog extends Dialog
{
	public function ExampleDialog()
	{
		// this is a simplified structure to avoid complicating the point
		var header:String = &quot;This is Header&quot;;
		var body:String = &quot;This is body&quot;;
		var buttons:Array = [&quot;OK&quot;,&quot;Cancel&quot;];
		var data:DialogData = new DialogData(header, body, buttons);

		super(data);
	}
}

public class SomeClassWhereDialogsAreShown
{
	public function onActionWhichTriggersExampleDialog():void
	{
		showDialog(new ExampleDialog());
	}
}
</pre>
<p>This approach allows me to encapsulate the ExampleDialog very neatly, though it requires more lines of code than the composition approach. ActionScript is verbose enough without actively seeking to add more lines of code.</p>
<h2>Single Responsibility Principle</h2>
<p>If the dialog needs to be changed, the inheritance approach ensures that the only place that code editing need take place is in the code which relates to the particular dialog. This conforms to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>, based on the principle of cohesion: the degree to which lines of code form a single unit of functionality is the extent to which they should be in their own class.</p>
<p>I would argue that creating a particular dialog is a functional unit, especially in user-interface code. Anatoly makes the point that all our dialogs are <em>functionally equivalent</em> (more of which below). I suppose he thinks of functionality in terms of the developer, and I the interface.</p>
<p>OOP Design principles are not inviolate, but they point us towards ways of writing code which lead to more robust code. This principle points towards the dialog configuration data not being defined in the <code>SomeClassWhereDialogsAreShown</code> class. (which is different from saying it supports the inheritance approach!)</p>
<h2>Liskov Substitution Princple</h2>
<p>Creating inheritance chains can be problematic. It might be considered reasonable to create a Square class as a subclass of the Rectangle, like this:</p>
<pre class="brush: as3;">
public class Rectangle
{
	...

	public function set width(value:Number):void
	{
		_width = value;
	}

	public function set height(value:Number):void
	{
		_height = value;
	}

	public function get area():Number
	{
		return _width * _height;
	}

}

public class Square extends Rectangle
{
	override public function set width(value:Number):void
	{
		_width = _height = value;
	}

	override public function set height(value:Number):void
	{
		_height = _width = value;
	}
}
</pre>
<p>However, this can cause problems. Imagine, during your code that you utilise Rectangle like this:</p>
<pre class="brush: as3;">
public class SomeOtherClass
{
	public function doubleRectangleArea(rectangle:Rectangle):void
	{
		rectangle.width *= 2;
	}
}
</pre>
<p>The <code>doubleRectangleArea</code> method presupposes that the <code>Rectangle</code>&#8217;s <code>width</code> and <code>height</code> properties are independent. Polymorphism allows a <code>Square</code> to be passed into the <code>doubleRectangleArea</code> method, but as configured this would quadruple the square&#8217;s area. The functionality of the <code>doubleRectangleArea</code> method is broken because the Square-Rectangle relationship breaks <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov Substitution Principle</a> (LSP).</p>
<p>This principle serves as a general warning against inappropriate inheritance. Anatoly invoked it in our discussion as a reason to be cautious about inheritance, but I remain unconvinced &#8211; surely not all inheritance is bad, and I am pretty sure that as things stand, no particular thing about our dialogs violate LSP?</p>
<h2>Function and Configuration</h2>
<p>Let&#8217;s suppose you want to model two cars: A <a href="http://www.topgear.com/uk/honda/jazz">Honda Jazz</a> and a <a href="http://www.topgear.com/uk/lotus/exige/road-test/cup-260">Lotus Exige</a>. The following class structure may be appropriate:</p>
<pre class="brush: as3;">
public class Car { ... }

public class HondaJazz extends Car { ... }

public class LotusExige extends Car { ... }
</pre>
<p>If, on the other hand, you have two colours of Honda Jazz, the following structure makes little sense:</p>
<pre class="brush: as3;">
public class HondaJazz extends Car { ... }

public class BlueHondaJazz extends HondaJazz { ... }

public class WhiteHondaJazz extends HondaJazz { ... }
</pre>
<p>More sensible would be:</p>
<pre class="brush: as3;">
public class HondaJazz extends Car
{
	public function HondaJazz(color:uint) { ... }
}
</pre>
<p>In the case of the two types of car there are clear functional differences: acceleration, top-speed, fuel efficiency, to name a few. In the case of the two jazzes, there are no functional differences, merely different <em>configurations</em>.</p>
<p>Anatoly argues that different dialogs are essentially like different <em>configurations</em>, rather than different <em>functionalities</em>. Therefore, they should all be the same class, but the Dialog should be configured through parameters in its constructor.</p>
<h2>Discussion</h2>
<p>So what is the right approach? The Single Responsibility Principle (SRP) definitely points away from the composition approach, if the class in which the composition is made has many other responsibilities. Anatoly has offered to meet me half-way having conceded this point, instead storing the various configurations in static methods of Dialog, or elsewhere, rather than create a subclass.</p>
<p>To me, this still feels wrong. The Function and Configuration argument is a good one, and points towards no sub-class being created. However, I still feel that the sheer quantity of configuration that some dialogs require start to make the act of configuration feel inappropriate.</p>
<p>Furthermore, if all we are really doing is is configuring the same dialog over and over, then I do not think that the Liskov Substitution Principle (LSP) is a concern. If all dialogs really are functionally equivalent, then how can they violate LSP?</p>
<p>Aesthetically, the inheritance approach feels right to me, but it is important to respect that Anatoly comes from a very different tradition and has been coding a lot longer than me! The discussion was an interesting (and pleasant) one. If any of you can add to it, then I would be delighted to hear your points of view.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/when-is-a-sub-class-appropriate/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Mr Tayto Website</title>
		<link>http://alecmce.com/as3/mr-tayto-website</link>
		<comments>http://alecmce.com/as3/mr-tayto-website#comments</comments>
		<pubDate>Sun, 14 Feb 2010 23:10:41 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[animation]]></category>
		<category><![CDATA[as3]]></category>
		<category><![CDATA[website]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=599</guid>
		<description><![CDATA[Just before I left for San Francisco, I was asked to work on the Mr Tayto website for Yomego. During my time at Yomego, I was mostly working on big projects, some of which never really saw the light of day. This was a bit of light relief.

 


 

The website was well received, Creative [...]]]></description>
			<content:encoded><![CDATA[<p>Just before I left for San Francisco, I was asked to work on the <a href="http://mrtayto.ie/">Mr Tayto</a> website for <a href="www.yomego.com">Yomego</a>. During my time at Yomego, I was mostly working on big projects, some of which never really saw the light of day. This was a bit of light relief.</p>
<div style="text-align: center; margin: 0 auto; padding-bottom: 20px;">
 <a href="http://mrtayto.ie/"><img src="http://alecmce.com/wp-content/uploads/2009/12/tayto1.png" alt="tayto1" title="tayto1" width="550" height="389" class="aligncenter size-full wp-image-600" /></a>
</div>
<div style="text-align: center; margin: 0 auto; padding-bottom: 20px;">
 <a href="http://mrtayto.ie/"><img src="http://alecmce.com/wp-content/uploads/2009/12/tayto2.png" alt="tayto2" title="tayto2" width="550" height="370" class="aligncenter size-full wp-image-601" /></a>
</div>
<p>The website was well received, <a href="http://www.creativematch.com/viewNews/?98034">Creative News</a> attributing some of the success of the book to the website and the surrounding social media campaign.</p>
<p>The site itself was assembled in under two weeks by myself and Colin McKinney. The page turning mechanism was built from scratch in that time in order to guarantee integration with the initial animation sequence, the bookmark turn effects. More polish could have been applied with a longer time-frame, but this was not a bad effort, in the circumstances.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/mr-tayto-website/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Events and Signals &#8211; Performance Tests</title>
		<link>http://alecmce.com/as3/events-and-signals-performance-tests</link>
		<comments>http://alecmce.com/as3/events-and-signals-performance-tests#comments</comments>
		<pubDate>Tue, 26 Jan 2010 08:20:29 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[as3signals]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=673</guid>
		<description><![CDATA[The new as3signals library devised by Robert Penner offers a replacement to the native AS3 event model. One benefit is that signals are more lightweight, and therefore faster. Grant Skinner&#8217;s Performance Harness is a widely accepted library for comparing the speeds of code execution.
I found the following results on Mac OS X, Flash Player 10.0.42.34, [...]]]></description>
			<content:encoded><![CDATA[<p>The new <a href="http://github.com/robertpenner/as3-signals">as3signals library</a> devised by Robert Penner offers a replacement to the native AS3 event model. One benefit is that signals are more lightweight, and therefore faster. Grant Skinner&#8217;s <a href="http://www.gskinner.com/blog/archives/2009/04/as3_performance.html">Performance Harness</a> is a widely accepted library for comparing the speeds of code execution.</p>
<p>I found the following results on Mac OS X, Flash Player 10.0.42.34, with a <em>release build</em>.</p>
<p>When an event (signal) is dispatched but nothing is listening for it:</p>
<div style="text-align: center; margin: auto; padding: 10px;"><img src="http://alecmce.com/wp-content/uploads/2010/01/results1.jpg" alt="A graph indicating that as3signals events dispatch roughly 5 times faster than native as3 events." width="357" height="262" /></div>
<p>When an event (signal) is dispatched and handled by one method listener:</p>
<div  style="text-align: center; margin: auto; padding: 10px;"><img src="http://alecmce.com/wp-content/uploads/2010/01/results2.jpg" alt="A graph indicating that as3signals signals are dispatched and captured at twice the speed of native as3 events." width="357" height="265" /></div>
</p>
<p>The source code for my test methods follows:</p>
<ul>
<li><a href="http://gist.github.com/286640">Dispatching events without listeners</a></li>
<li><a href="http://gist.github.com/286642">Dispatching events with listeners</a></li>
</ul>
<p>If you browse these tests, you will notice that more tests were run than I have displayed above. The graphs above reference results from running the <code>dataEventOptimised</code> and <code>dataSignal</code> methods in each context.</p>
<p>These tests are not scientific. No attempt has been to control for player version, computer version, computer specifications, so on and so forth. You are invited to download and run these tests for yourself. If you do, remember that testing on a <em>release build</em> not a debug build is appropriate, and then please post your results as a comment, particularly if your results differ from my own.</p>
<h2>Updates</h2>
<p>For a comparison with good old fashioned callbacks, please put on your sarcasm snorkel and visit <a href="http://va.lent.in/blog/2010/01/27/omg-as3-signals-are-faster-than-events1">va.lent.in&#8217;s follow up post</a>.</p>
<p>From the <a href="http://groups.google.com/group/as3-signals/browse_thread/thread/3f9a203e6604b0f0?utoken=VwX81i4AAADzSqymN73RML18dAjSp6G6iJqNSdlwl88TjV7a-ukVihfEbSR7To5PnLe8EpnsVXE">as3signals Google Group</a> there was a suggestion that the Flash Player 10.1 might produce different results. Here are my results; they appear to corroborate the earlier results:</p>
<pre class="brush: plain;">
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
performancetests.EventsTest (5 iterations)
Player version: MAC 10,1,51,66 (regular)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
dataEvent                                                  2344   468.80
dataEventOptimised                                         2270   454.00
dataSignal                                                  313    62.60
simpleEvent                                                2755   551.00
simpleEventOptimised                                       2285   457.00
simpleSignal                                                174    34.80
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
performancetests.CapturedEventsTest (5 iterations)
Player version: MAC 10,1,51,66 (regular)
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
method...................................................ttl ms...avg ms
dataEvent                                                  2708   541.60
dataEventOptimised                                         2703   540.60
dataSignal                                                 1182   236.40
simpleEvent                                                2724   544.80
simpleEventOptimised                                       2717   543.40
simpleSignal                                               1042   208.40
––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
</pre>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/events-and-signals-performance-tests/feed</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>RobotLegsPong Part 1 &#8211; Overview</title>
		<link>http://alecmce.com/as3/robotlegspong1</link>
		<comments>http://alecmce.com/as3/robotlegspong1#comments</comments>
		<pubDate>Tue, 19 Jan 2010 07:01:23 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[tdd]]></category>
		<category><![CDATA[as3signals]]></category>
		<category><![CDATA[asunit]]></category>
		<category><![CDATA[RobotLegs]]></category>
		<category><![CDATA[Ticker]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=649</guid>
		<description><![CDATA[Introduction
RobotLegsPong attempts to combine RobotLegs application framework with the as3signals event model and a Frame-Ticker (as well as a pinch of ASUnit unit-testing) to create a &#8216;game&#8217;.
It is an open-source project, available on GitHub as an example of using RobotLegs together with these other technologies.
Source Code: github/alecmce/RobotLegsPong
RobotLegsPong is not a very good game; it is [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>RobotLegsPong attempts to combine RobotLegs application framework with the as3signals event model and a Frame-Ticker (as well as a pinch of ASUnit unit-testing) to create a &#8216;game&#8217;.</p>
<p>It is an open-source project, available on <a href="http://github.com/alecmce/RobotLegsPong/tree/master">GitHub</a> as an example of using RobotLegs together with these other technologies.</p>
<p style="text-align: center;">Source Code: <a href="http://github.com/alecmce/RobotLegsPong/tree/master">github/alecmce/RobotLegsPong</a></p>
<p>RobotLegsPong is not a very good <em>game</em>; it is playable only in the loosest sense. Bats require to be dragged in order to move (and there is no computer-logic to play against), so you could not really play against an opponent. The purpose of the exercise was to see what structure a game like Pong would take within the RobotLegs framework.</p>
<p>The purpose of this article is to describe the particulars of the technologies and why I chose them. In a follow-up article, I will look in more detail how RobotLegsPong is wired up.</p>
<h2>Why I Chose These Technologies</h2>
<h3>RobotLegs</h3>
<p>The RobotLegs framework is a lightweight, flexible application framework that allows coders to spend less time wiring up their application, and more time working on its functionality.</p>
<p>Frameworks are often criticised because they force developers to write code in a particular way, which might be inappropriate for a particular context. I have used Cairngorm, Pure MVC, as well as some proprietary frameworks, and have found that all of them do some things well, and do other things clumsily. So far I have not found this problem with RobotLegs, because most of the time it gets out of the way and lets you code; in fact, it does more than that: it reduces the amount of code you have to write.</p>
<h3>as3signals</h3>
<p>RobotLegs comes with an application event bus, but I have decided to circumvent that and use as3signals instead. as3signals allows you to define an object which acts as an event dispatcher within an application.</p>
<p>I like as3signals because describing an event as a Signal object allows my event model to be described through interfaces. as3signals is supposed to be fast too. Then again, interfaces are slow. The relative speeds of the approaches is interesting, but not a significant factor in my decision making process.</p>
<h3>Frame-Ticker</h3>
<p>The frame-ticker is a simple idea: rather than creating multiple enter-frame event listeners, each creating event objects, create one enter-frame listener and a main game loop iterating through those methods that need to be called per-iteration.</p>
<p>This implementation came out of a discussion on Twitter that I was involved in on the fringes; I wrote about it <a href="http://alecmce.com/as3/replacing-enter_frame">in a previous blog post</a>.</p>
<h3>ASUnit</h3>
<p>Unit testing enables developers to test portions of their code in isolation, so that they can be confident that every method works exactly as the developer intended. They also represent a secondary form of documentation-in-code; if you want to know how I meant a method to work, reading the unit test will tell you almost everything you need to know (including, if a good test is missing, what I <em>didn&#8217;t</em> consider).</p>
<p>That said, I have not unit tested every method; in this example I have only unit-tested the geometric logic for the bats. This is bad practice, however under time constraints I think that it is most important to unit test what is complex, mathematical or ambiguous, since this is where behaviour is most likely to fall down.</p>
<h2>[Inject]</h2>
<p>The &#8216;trick&#8217; to using RobotLegs is that you do not need to inject dependent objects into classes when you contruct them; this is done automatically. This code:</p>
<pre class="brush: as3;">
public class Dependee {}

public class MyExample
{
	public var dependee:Dependee;

	public function MyExample(dependee:Dependee)
	{
		this.dependee = dependee;
	}
}
</pre>
<p>becomes this code:</p>
<pre class="brush: as3;">
public class Dependee {}

public class MyExample
{
	[Inject]
	public var dependee:Dependee;
}
</pre>
<p>The metadata tag <code>[Inject]</code> has the effect of automatically injecting the dependee into the class when it is constructed. This isn&#8217;t much on the face of it, but it is enough. It feels to me as though a quarter of my code is actually just wiring up classes so that they each have access to the classes that they need to function, or passing objects around methods. The <code>[Inject]</code> tag lets me shift all of that wiring into the RobotLegs framework.</p>
<h2>Context</h2>
<p>There is a little more to the RobotLegs story however; how should RobotLegs react when it comes across an <code>[Inject]</code> tag? It could construct a new <code>Dependee</code> object, or it could be that I want only one <code>Dependee</code> object to be injected wherever the <code>[Inject]</code> tag is found. This is where the <code>Context</code> class becomes meaningful.</p>
<p>In the <a href="http://github.com/alecmce/RobotLegsPong/blob/master/src/app/PongContext.as">PongContext</a>, different classes are wired up in different ways. Their definitions are defined by adding <code>injector</code> mappings and the <code>mediatorMap</code> mappings in the <code>startup</code> method.</p>
<pre class="brush: as3;">
public class PongContext extends Context
{
	override public function startup():void
	{
		...
		injector.mapSingleton(DragMechanism);
		injector.mapSingletonOf(Geometry, GeometryModel);
		injector.mapClass(BatGeometry, BatGeometryModel);
		...
	}
}
</pre>
<h3>injector.mapSingleton</h3>
<pre class="brush: as3;">injector.mapSingleton(DragMechanism)</pre>
<p><code>mapSingleton</code> indicates that only one instance of the class entered should be constructed. In this case, just one <code>DragMechanism</code> will be created, and injected whenever this is found:</p>
<pre class="brush: as3;">
[Inject]
public var mechanism:DragMechanism;
</pre>
<h3>injector.mapSingletonOf</h3>
<pre class="brush: as3;">injector.mapSingletonOf(Geometry, GeometryModel);</pre>
<p><code>mapSingletonOf</code> extends the <code>mapSingleton</code> idea to interfaces and their implementing classes. In this case the <code>Geometry</code> interface is mapped to the <code>GeometryModel</code> class. The injection is called as follows:</p>
<pre class="brush: as3;">
[Inject]
public var model:Geometry;
</pre>
<p>No reference to the <code>GeometryModel</code> is needed in any class other than the <code>PongContext</code>. This allows a very pure use of interfaces across the application.</p>
<h3>injector.mapClass</h3>
<pre class="brush: as3;">injector.mapClass(BatGeometry, BatGeometryModel)</pre>
<p><code>injector.mapClass</code> works a little differently; whenever a <code>BatGeometry</code> interface is flagged to be injected, a new instance of <code>BatGeometryModel</code> is constructed and injected into the class, so the following code is used to create the injection:</p>
<p>Each <code>BatMediator</code> needs its own <code>BatGeometry</code> object. By using the <code>mapClass</code> method, multiple <code>BatGeometryModel</code> objects will be constructed, one for each time the following code is found:</p>
<pre class="brush: as3;">
[Inject]
public var model:BatGeometry;
</pre>
<h2>Mediators and Components</h2>
<pre class="brush: as3;">
public class PongContext extends Context
{
	override public function startup():void
	{
		...
		mediatorMap.mapView(Background, BackgroundMediator);

		addChild(new Background());
	}
}
</pre>
<p><code>mediatorMap</code> references a slightly different aspect of the application: your view objects. The <code>mediatorMap</code> allows users to define associations between display objects and <code>Mediator</code>s. These two parts comprise the <em>View</em> aspect of the standard MVC pattern.</p>
<p>The <code>DisplayObject</code> &#8211; in this case <code>Background</code> &#8211; is the asset that you want to be visible on the stage. In my pong example this is essentially just a Sprite, though it might just as well have been imported as a graphical asset in a SWC.</p>
<p>The <code>Mediator</code> is associated with the <code>DisplayObject</code> so that when an instance of the <code>DisplayObject</code> is created, the corresponding <code>Mediator</code> is also constructed. The <code>BackgroundMediator</code> looks something like this:</p>
<pre class="brush: as3;">
public class BackgroundMediator extends Mediator
{
	[Inject]
	public var view:Background;

	override public function onRegister():void
	{
		...
	}
}
</pre>
<p>The <code>DisplayObject</code> <code>Background</code> is injected into the <code>BackgroundMediator</code> when it is constructed. The <code>DisplayObject</code> can then be manipulated. It is an elegant solution that separates display object from UI logic.</p>
<pre class="brush: as3;">addChild(new Background());</pre>
<p>is all that is needed to wire the entire <code>DisplayObject</code>/<code>Mediator</code> combination.</p>
<h3>RobotLegs &#038; Tickers</h3>
<p>The RobotLegs structure is particularly useful for wiring up a <code>Ticker</code>-based application because one ticker can be mapped as a singleton, and injected to all those methods that need to iterate every frame:</p>
<pre class="brush: as3;">
public class PongContext extends Context
{
	override public function startup():void
	{
		...
		injector.mapSingletonOf(Ticker, EnterFrameTicker);
		...
	}
}
</pre>
<h3>RobotLegs with as3signals</h3>
<p>I really like the style of event dispatching that <code>as3signals</code> provides, but my implementation demands that if one class requires another class then it must flag it to be injected, and then the signal wired up in a method flagged as <code>[PostConstruct]</code> (see <a href="http://github.com/alecmce/RobotLegsPong/blob/master/src/app/model/GeometryModel.as">GeometryModel</a>). This doesn&#8217;t feel like the right solution.</p>
<p>Integrating <code>as3signals</code> with RobotLegs is beyond the scope of this article. It looks like Joel Hooks and Robert Penner are making inroads into this problem through <a href="http://groups.google.com/group/as3-signals/browse_thread/thread/fabc7995e9e55ec3#">as3signals&#8217; Google Group</a>. I look forward to seeing what they come up with.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/robotlegspong1/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Circle Segments</title>
		<link>http://alecmce.com/as3/circle-segments</link>
		<comments>http://alecmce.com/as3/circle-segments#comments</comments>
		<pubDate>Mon, 21 Dec 2009 13:01:04 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[math]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=643</guid>
		<description><![CDATA[I&#8217;ve added circle segments to the as3geometry library. The two examples below demonstrate the definition of a segment by two vertices constrained to the circle radius and by a line and circle:
Circle Segment By Vertices
view source &#124; click-and-drag the red points to interact
Circle Segment By Line And Circle
view source &#124; click-and-drag the red points to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve added circle segments to the <a href="http://github.com/alecmce/as3geometry">as3geometry library</a>. The two examples below demonstrate the definition of a segment by two vertices constrained to the circle radius and by a line and circle:</p>
<h2>Circle Segment By Vertices</h2>
<div style="text-align: center; padding-bottom: 20px; font-size: small;">
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_3" width="550" height="400">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2009/12/CircleSegmentByVertices.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2009/12/CircleSegmentByVertices.swf" width="550" height="400">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
<br/><a href="http://github.com/alecmce/as3geometry/blob/master/src/examples/CircleSegmentByVertices.as">view source</a> | click-and-drag the red points to interact</div>
<h2>Circle Segment By Line And Circle</h2>
<div style="text-align: center; padding-bottom: 20px; font-size: small;">
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_4" width="550" height="400">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2009/12/CircleSegmentFromCircleAndLine.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2009/12/CircleSegmentFromCircleAndLine.swf" width="550" height="400">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
<br/><a href="http://github.com/alecmce/as3geometry/blob/master/src/examples/CircleSegmentFromCircleAndLine.as">view source</a> | click-and-drag the red points to interact</div>
<p>The library update also includes some preliminary work on the intersection of two polygons, but I haven&#8217;t yet sorted out the mutability yet, because it&#8217;s pretty complicated, and because I&#8217;m furiously busy this December preparing to move from the UK to the USA! Expect more udpates from late January onwards, once I&#8217;m settled in.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/circle-segments/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>The Problem With Vector.&lt;T&gt;</title>
		<link>http://alecmce.com/as3/the-problem-with-vector</link>
		<comments>http://alecmce.com/as3/the-problem-with-vector#comments</comments>
		<pubDate>Wed, 16 Dec 2009 15:11:11 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=626</guid>
		<description><![CDATA[I thought I&#8217;d found a bug with respect to Adobe&#8217;s new Vector class. I logged it in JIRA, but the answer came back that it is Not A Bug. Respectfully, I disagree. Here&#8217;s why.
UPDATE: I may be wrong about this. My brother has written a response: http://bit.ly/9OotIS. For further discussion, please also see the comments [...]]]></description>
			<content:encoded><![CDATA[<p>I thought I&#8217;d found a bug with respect to Adobe&#8217;s new Vector class. I logged it in JIRA, but the answer came back that it is <em>Not A Bug</em>. Respectfully, I disagree. Here&#8217;s why.</p>
<p><em><strong>UPDATE</strong>: I may be wrong about this. My brother has written a response: <a href="http://bit.ly/9OotIS">http://bit.ly/9OotIS</a>. For further discussion, please also see the comments below.</em></p>
<h2>The Problem</h2>
<pre class="brush: as3;">
// create an interface and implementing class
public interface Fruit {}
public class Apple implements Fruit {}

// create a vector of Apple objects and try to cast it to a vector of Fruit objects
public class TheProblemWithVectors
{
	public var fruits:Vector.&amp;lt;Fruit&amp;gt;;

	public function TheProblemWithVectors()
	{
		var apples:Vector.&amp;lt;Apple&amp;gt; = new Vector.&amp;lt;Apple&amp;gt;();
		apples.push(new Apple());

		// THIS THROWS AN ERROR!
		fruits = apples as Vector.&amp;lt;Fruit&amp;gt;;
	}
}
</pre>
<p>The following is indisputable:</p>
<ul>
<li>All (elements in) <code>apples</code> must be an <code>Apple</code>;</li>
<li>All <code>Apple</code>s are <code>Fruit</code>s;</li>
<li>Therefore, (elements in) <code>apples</code> are <code>Fruit</code>.</li>
</ul>
<p>In which case, why can&#8217;t <code>apples</code> be cast as <code>fruits</code>? The Flash player does not accept that a Vector of <code>Fruit</code> could be described as a Vector of <code>Apple</code>. To me this feels like a bug. Does it to you?</p>
<h2>Not A Bug?</h2>
<p>To Adobe it is Not A Bug:</p>
<p style="text-align: center;"><a href="http://bugs.adobe.com/jira/browse/ASC-3836">http://bugs.adobe.com/jira/browse/ASC-3836</a></p>
<p>According to Chris Peyer who works at Adobe:</p>
<blockquote><p>This is the expected behavior. Vector.<ExampleA> and Vector.<Example> are unrelated types no matter what the relation is between Example and ExampleA.</p></blockquote>
<p>It seems to me that this argument can only stem from the idea that if one object is composed of <code>Fruit</code>s and another composed of <code>Apple</code>s, that does not mean that the two objects are themselves related:</p>
<pre class="brush: as3;">
public class MarketStall
{
	public var forSale:Apple;
}

public class Supermarket
{
	public var forSale:Fruit;
}
</pre>
<p>There is no relationship between <code>MarketStall</code> and <code>Supermarket</code> in this code.</p>
<p>Surely though the relationship between two Vectors defined by a generic is much stronger than that? The Vector <em>is nothing more than</em> an indexed plurality of the objects that compose it. We know it doesn&#8217;t have other unrelated functionality. We can do this:</p>
<pre class="brush: as3;">
var fruits:Vector.&amp;lt;Fruit&amp;gt; = new Vector.&amp;lt;Fruit&amp;gt;();

for each (var apple:Apple in apples)
	fruits.push(apple);
</pre>
<p>without problem, but not this:</p>
<pre class="brush: as3;">var fruits:Vector.&amp;lt;Fruit&amp;gt; = apples as Vector.&amp;lt;Fruit&amp;gt;;</pre>
<p>Most importantly however, can&#8217;t the Adobe engineers see how damned <em>useful</em> it would be if we could cast Vectors like this? Languages should not get in the way of what is intuitively right. You should not have to struggle with the language like this, or find workarounds. Flash developers are almost always looking for improvements in speed and memory, but here you the language makes you waste memory and take time. Or, use the other workaround and avoid <code>Vector</code> and use <code>Array</code> instead. That&#8217;s what I did; what a triumph, Adobe!</p>
<h2>Please Vote On This Bug</h2>
<p>I&#8217;ve been here before! My former Colleague <a href="http://blog.vizio360.co.uk/2009/11/buttonmodetrue-prevent-swf-to-unload/"> Vizio360 rediscovered this bug</a> about buttonMode=true preventing unloading of SWF files, but it too was resolved by being called <em>Not A Bug</em>. The clamour for it to be reopened has so-far fallen on deaf ears, but the only way anyone will ever take any notice is if you vote and comment.</p>
<p>Currently Adobe consider this issue closed. Pehaps if you comment on the post they will give it second thoughts. (this is edited text after it was pointed out to me that you can&#8217;t vote for closed bugs)</p>
<p style="text-align: center;"><a href="http://bugs.adobe.com/jira/browse/ASC-3836">http://bugs.adobe.com/jira/browse/ASC-3836</a></p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/the-problem-with-vector/feed</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>as3geometry &#8211; line &amp; circle intersection</title>
		<link>http://alecmce.com/as3/as3geometry-line-circle-intersection</link>
		<comments>http://alecmce.com/as3/as3geometry-line-circle-intersection#comments</comments>
		<pubDate>Wed, 02 Dec 2009 21:32:24 +0000</pubDate>
		<dc:creator>alec</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[math]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=604</guid>
		<description><![CDATA[Addition to my as3geometry library, the intersection between a line and a circle
view source &#124; click-and-drag the red points to interact
]]></description>
			<content:encoded><![CDATA[<p>Addition to my <a href="http://github.com/alecmce/as3geometry">as3geometry library</a>, the intersection between a line and a circle</p>
<div style="text-align: center; padding-bottom: 20px; font-size: small;">
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_5" width="550" height="400">
      <param name="movie" value="http://alecmce.com/wp-content/uploads/2009/12/IntersectCircleAndLine.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://alecmce.com/wp-content/uploads/2009/12/IntersectCircleAndLine.swf" width="550" height="400">
      <!--<![endif]-->
        <p>The Flash plugin is required to view this object.</p>
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>
<br/><a href="http://github.com/alecmce/as3geometry/blob/master/src/examples/IntersectCircleAndLine.as">view source</a> | click-and-drag the red points to interact</div>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/as3geometry-line-circle-intersection/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
