<?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 &#187; opinion</title>
	<atom:link href="http://alecmce.com/category/opinion/feed" rel="self" type="application/rss+xml" />
	<link>http://alecmce.com</link>
	<description></description>
	<lastBuildDate>Fri, 18 May 2012 02:54:03 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>CommandFlow &#8211; Another Approach to (RobotLegs) Asynchronicity</title>
		<link>http://alecmce.com/as3/commandflow-another-approach-to-robotlegs-asynchronicity</link>
		<comments>http://alecmce.com/as3/commandflow-another-approach-to-robotlegs-asynchronicity#comments</comments>
		<pubDate>Sun, 11 Sep 2011 11:38:18 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[robotlegs]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=1213</guid>
		<description><![CDATA[In this post I present another first draft of an extension for RobotLegs, my RobotLegs Flow Extension, which seeks to cope with problems surrounding asnychronicity in command-level code. In my last blog post, I argued that Robotlegs is poorly equipped to cope with asynchronous processes, and offered an extension to RobotLegs to seek to solve [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I present another first draft of an extension for RobotLegs, my <a href="http://bit.ly/qF9QqN">RobotLegs Flow Extension</a>, which seeks to cope with problems surrounding asnychronicity in command-level code.</p>
<p>In my last blog post, I argued that Robotlegs is poorly equipped to cope with asynchronous processes, and offered an extension to RobotLegs to seek to solve this problem, &quot;<a href="http://bit.ly/nEtgUZ">Async Processes Extension</a>&quot;. This extension follows in the footsteps of other interesting libraries, such as Shaun Smith&#8217;s <a href="https://github.com/darscan/robotlegs-extensions-Oil">Oil Extension</a> among many others.</p>
<h2>Reflecting about Processes</h2>
<p>Since I wrote that code and blog post, I have been reflecting on my approach. I have a few problems with it:</p>
<ul>
<li>RobotLegs is fundamentally lightweight. It is my framework of choice because it&#8217;s hardly a framework at all. The Processes extension adds a lot of conceptual overhead and does a lot of work under-the-hood.</li>
<li>It separates the concept of a process from the concept of a command, but it can often be the case that previously synchronous code can become asynchronous (for example: when moving from mocked data to live data), or the other way (for example: once data is  pre-loaded that was previously loaded just-in-time). Refactoring between commands and processes seems more trouble than it&#8217;s worth.</li>
<li>The under-the-hood part of the Process class means that it&#8217;s impossible to duck-type a Process. Duck-typing is good insofar as you know a framework that accepts duck-typable object has minimal dependencies.</li>
</ul>
<p>These criticisms of the library led me to think about a more lightweight approach.</p>
<h2>The Central Premise of Process</h2>
<p>The central premise of my critique of asynchronous code is that this sort of code is bad because the Command contains both its own logic and sequencing logic:</p>
<pre class="brush: as3; title: ; notranslate">
// pseudo-code!

class Context
{
	signalCommandMap.map(runSecond, SecondCommand);
	signalCommandMap.execute(FirstCommand);
}

class FirstCommand
{
	[Inject]
	public var runSecond:Signal;

	public function execute():void
	{
		process = new SomeProcess();
		process.run().addOnce(onComplete);
	}

	private function onComplete():void
	{
		runSecond.dispatch();
	}
}
</pre>
<p>It would be preferable to abstract the sequencing logic, so that the FirstCommand can just report that it has completed what it needs to do without having to know what&#8217;s next.</p>
<p>I have often found that you end up drawing diagrams for code written this way with each command in a box with arrows between them. I want a class that encapsulates that diagram, ensuring that the individual commands are truly agnostic with respect to their context in the application.</p>
<h2>A Different Approach</h2>
<p>If we abandon the notion of a Process, then how can we retain this separation? My second approach has been to abstract the sequencing logic into a class, called <a href="http://bit.ly/n46bVs">CommandFlow</a>. The intention is to use it like this:</p>
<pre class="brush: as3; title: ; notranslate">
// pseudo-code!

class Context
{
	injector.mapClass(ComamndFlow, CommandFlow);

	signalCommandMap.execute(InitCommand);
}

class InitCommand
{
	[Inject]
	public var flow:CommandFlow;

	public function execute():void
	{
		flow.push(FirstCommand);
		flow.push(SecondCommand);
		flow.next();
	}

}

class FirstCommand
{
	[Inject]
	public var flow:CommandFlow;

	public function execute():void
	{
		process = new SomeProcess();
		process.run().addOnce(onComplete);
	}

	private function onComplete():void
	{
		flow.next();
	}
}
</pre>
</p>
<p>The command sequencing is abstracted into InitCommand, so that FirstCommand doesn&#8217;t need to know anything more than that it is part of a sequence. CommandFlow is a helper that allows asnychronous command sequencing to take place with a minimum of impact on the classes&#8217; functionalities themselves.</p>
<p>Each CommandFlow injected into a command is a separate instantiation, so that if nested command logic is required, then it is possible. For example:</p>
<pre class="brush: as3; title: ; notranslate">
// pseudo-code!

class Context
{
	signalCommandMap.execute(InitCommand);
}

class InitCommand
{
	[Inject]
	public var flow:CommandFlow;

	public function execute():void
	{
		flow.push(FirstCommand);
		flow.push(LastCommand);
		flow.next();
	}
}

class FirstCommand
{
	[Inject]
	public var flow:CommandFlow;

	public function execute():void
	{
		flow.push(SecondCommand);
		flow.push(ThirdCommand);
	}
}
</pre>
<p>In this structure, FirstCommand will trigger SecondCommand and ThirdCommand before LastCommand is executed.</p>
<p>Payloads can be passed in explicitly through the push method, as CommandFlow exposes this method:</p>
<pre class="brush: as3; title: ; notranslate">
public function push(command:Class, ...args):Boolean;
</pre>
<p>A working demo of the code-in-action is provided in the github repository <a href="http://bit.ly/niwypL">here</a>.</p>
<h2>Notes</h2>
<p>At the moment it is not clear how to handle commands being pushed into a CommandFlow once the flow has been started with a next() call.</p>
<p>If the CommandFlow approach is to be useful, I will need to add branching into the CommandFlow class, and it could quickly become very difficult to maintain. Careful thought will be needed to cope with this.</p>
<p>After my previous post, <a href="http://www.creynders.be">Camille Reynders</a> made several good criticisms. One important one is how to handle failures. I think that this might be handled elegantly through branching, or possibly through some CommandFlow.error method that is a general &#8216;abandon-ship&#8217; method. I&#8217;m not sure yet how to implement this, since I&#8217;m not yet committed to using this sort of approach to solving asynchronicity problems.</p>
<p><a href="https://github.com/brianheylin">Brian Heylin</a> also pointed me towards some interesting resources that led me to adjust my Notices classes (my implementation of the Signals concept) to expose what I am calling a &#8216;<a href="http://bit.ly/r1z05O">Future</a>&#8216;; essentially a single-dispatch Signal/Notice, such that if you bind to it post-dispatch, the bound method is immediately called with the data that was originally dispatched.</p>
<h2>Last Thought</h2>
<p>I am keen to emphasise that these ideas are not complete; they need refining, tweaking and using. Perhaps I have gone down another blind-alley? Perhaps the Processes idea is better after-all? Or perhaps I&#8217;m misunderstanding something fundamental about how to wire-up applications with asynchronous functionality that you can enlighten me about?</p>
<p>A blog is for nothing if not shared learning. If you have any comments (positive or negative) then I would really appreciate hearing them!</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/commandflow-another-approach-to-robotlegs-asynchronicity/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Asynchronous Processes and RobotLegs</title>
		<link>http://alecmce.com/library/asynchronous-processes-and-robotlegs</link>
		<comments>http://alecmce.com/library/asynchronous-processes-and-robotlegs#comments</comments>
		<pubDate>Tue, 23 Aug 2011 20:15:05 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[robotlegs]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=1192</guid>
		<description><![CDATA[Asynchronous processes are a common feature of ActionScript applications: we often need to initiate some asynchronous process, wait for a response and handle it. We have good language tools and design patterns for solving these sorts issues. RobotLegs is an MVCS framework that aims to decrease inter-dependency between different parts of code, so that code [...]]]></description>
			<content:encoded><![CDATA[<p>Asynchronous processes are a common feature of ActionScript applications: we often need to initiate some asynchronous process, wait for a response and handle it. We have good language tools and design patterns for solving these sorts issues.</p>
<p>RobotLegs is an MVCS framework that aims to decrease inter-dependency between different parts of code, so that code is more robust, and more reusable. It does this through a combination of dependency injection and the model-view-controller (+services) design pattern. The &#8216;controller&#8217; portion of RobotLegs&#8217; MVCS implementation is achieved by offering coders a simple way of implementing the Command pattern and binding commands to events that can be called from other areas of the code.</p>
<p>Problematically, commands are stateless and synchronous. They are not wired up to handle asynchronicity under-the-hood. &#8220;Async Commands&#8221; amend the Command structure to attempt to solve this problem, but they still contain architectural limitations that force us to restrict the way we code to the potential of the framework. Using Commands for asynchronous processes often require us to &#8216;double wire&#8217; between different application elements to solve the problem of passing data between classes.</p>
<p>What I am calling Processes are a redesign of the Async Command concept that seek to resolve these issues. They can be used in parallel with Commands to elegantly handle the problems of asynchronous code in RobotLegs.</p>
<h2>The Async Pattern</h2>
<p>The event model exists explicitly because we often need to wire up code to be triggered at an indeterminate future event. Fundamentally, client-side programming is about state and asynchronicity: events handle the asynchronicity. We handle them with this sort of pattern:</p>
<pre class="brush: as3; title: ; notranslate">
public function init():void
{
	var process:AsyncProcess = new MyAsyncProcess();
	process.addEventListener(AsyncProcessEvent.COMPLETE, onProcessComplete);
	process.init();
}

private function onProcessComplete(event:AsyncProcessEvent):void
{
	var processs:AsyncProcess = event.process;
	process.removeEventListener(AsyncProcessEvent.COMPLETE, onProcessComplete);

	parse(process.data);
}
</pre>
<p>Signals improves upon this structure by removing the necessity of event classes and offers some added features like automatically handling the removal of listener functions:</p>
<pre class="brush: as3; title: ; notranslate">
public function init():void
{
	var process:AsyncProcess = new MyAsyncProcess();
	process.completed.addOnce(onProcessComplete);
	process.init();
}

private function onProcessComplete(process:AsyncProcess):void
{
	parse(process.data);
}
</pre>
<p>This pattern is simple but powerful &#8211; create an object to tokenise or act-as-delegate-to the process, bind to some generic event/signal defined on the token, then initialise the process. I take the signal implementation to be a substantial improvement to the original. </p>
<h2>The Async Pattern across different objects</h2>
<p>A more complex case emerges if one class wants to launch a process in another class and retrieve data from its result. Ideally we want to keep the same three-step process.</p>
<pre class="brush: as3; title: ; notranslate">
class Model
{
	public var service:Service;

	public function init():void
	{
		service.completed.addOnce(onServiceComplete);
		service.init();
	}

	private function onServiceComplete(process:AsyncProcess):void
	{
		parse(process.data);
	}
}

interface Service
{
	function get completed:Signal;

	function init():void;
}
</pre>
<p>Unfortunately, this pattern is now insufficient, because it is possible for two different objects to trigger an asynchronous process from the same service at overlapping times (such that the second one is triggered before the first response).</p>
<pre class="brush: as3; title: ; notranslate">
class InitModelsCommand
{
	public var a:Model;
	public var b:Model;

	public function execute():void
	{
		a.init();
		b.init();
	}
}
</pre>
<p>In this scenario, if modelA and modelB both call init() in turn, then modelB will receive the data for modelA, then remove its listener before its own data is retrieved (assuming that modelA&#8217;s data is returned first, otherwise vice-versa).</p>
<p>This problem comes about because the service exposes a single Signal for multiple requests. There are two options to remedy this limitation:</p>
<pre class="brush: as3; title: ; notranslate">
// option A - the calling service tells the response where to go
interface Service
{
	function init(signal:Signal):void;
}

// option B - the service generates a response signal on a per-call basis
interface Service
{
	function init():Signal;
}
</pre>
<p>There&#8217;s not a lot between the two solutions, but I prefer Option B because it keeps together the repsonsibilities for creating and managing delegates to the asynchronous process in the same place as the process itself.</p>
<p>The pattern morphs to this:</p>
<pre class="brush: as3; title: ; notranslate">
class Model
{
	public var service:Service;

	public function init():void
	{
		service.init().addOnce(onServiceComplete);
	}

	private function onServiceComplete(process:AsyncProcess):void
	{
		parse(process.data);
	}
}

interface Service
{
	function init():Signal;
}
</pre>
<p>Here, be aware that if the signal responds within the init() method then it will not be routed to onServiceComplete. This can be handled by defining a signal that once dispatched, will dispatch immediately to any methods that are then added.</p>
<h2>Asynchronous Processes in RobotLegs</h2>
<p>The point of RobotLegs is to keep as few dependencies between different parts of code as possible. Ideally a model and a service shouldn&#8217;t reference each other, so RobotLegs best-practises would suggest you separate their interaction into a Command:</p>
<pre class="brush: as3; title: ; notranslate">
class InitModelCommand
{
	[Inject]
	public var model:Model;

	[Inject]
	public var service:Service;

	public function execute():void
	{
		service.completed.addOnce(onResponse);
		service.init();

		commandMap.detain(this) // if we don't do this for an async command everything could explode
	}

	private function onResponse(process:AsyncProcess):void
	{
		commandMap.release(this) // if we don't do this for an async command commands stay in memory

		model.parse(process.data);
	}
}
</pre>
<p>There several problems with this implementation. Imagine that this command is called as part of an initialisation routine, and once complete, another command should be called:</p>
<pre class="brush: as3; title: ; notranslate">
class Context
{
	public function onStartup():void
	{
		signalCommandMap.mapCommand(InitModel, InitModelCommand);
		signalCommandMap.mapCommand(InitView, InitViewCommand);
	}
}
</pre>
<p>How should InitViewCommand be called? The only place where the InitModelCommand is known to be complete is in its own onResponse command:</p>
<pre class="brush: as3; title: ; notranslate">
class InitModelCommand
{
	[Inject]
	public var initView:InitView;

	...

	private function onResponse(process:AsyncProcess):void
	{
		model.parse(process.data);
		initView.dispatch();
	}
}
</pre>
<p>This is unsatisfactory. Without this, the command is neatly encapsulated and simple to describe and understand. Once this code is added, the command takes on two responsibilities: firstly to initialise the model, and secondarily to kick-off the InitViewCommand.</p>
<p>The stateless command design pattern is ill-suited for asynchronous processes, and the attempt to use them leads to poor code design.</p>
<h2>An asynchronous process for RobotLegs</h2>
<p>The simple cases at the start of this article are instructive if we try to design a preferred architecture from the ground up. While retaining the power of RobotLegs to remove class dependencies, we want to find a way to use the simple asynchronous process pattern to wire up processes.</p>
<p>These design considerations have led me to what I&#8217;ve tentatively called the <a href="https://github.com/alecmce/robotlegs-async-processes-extension">robotlegs-async-process-extension</a>. It&#8217;s very early stages, and as usual I&#8217;m sharing the code more to get feedback than as a polished piece of work, but it functions to provide what I think is a superior alternative to Async Commands.</p>
<p>The structure is roughly like this:</p>
<pre class="brush: as3; title: ; notranslate">
class Context
{
	public function onStartup():void
	{
		// a delegate is a new concept...
		processMap.map(InitModelDelegate, InitModelProcess);
		processMap.map(InitViewDelegate, InitViewProcess);
	}
}

Class InitModelDelegate extends ProcessDelegate {}

Class InitViewDelegate extends ProcessDelegate {}

class InitProcess extends Process
{
	[Inject]
	public var initModel:InitModelDelegate;

	[Inject]
	public var initView:InitViewDelegate;

	public function execute():void
	{
		initModel.execute().addOnce(onModelInited);
	}

	private function onModelInited():void
	{
		initView.execute().addOnce(onViewInited);
	}

	private function onViewInited():void
	{
		complete();
	}
}
</pre>
<p>Note the features here:</p>
<ul>
<li>Like the SignalCommandMap extension, a different core structure, the <a href="https://github.com/alecmce/robotlegs-async-processes-extension/blob/master/src/gaia/lib/robotlegs/process/ProcessMap.as">ProcessMap</a> is defined that allows Processes to be defined in a way similar to Commands;</li>
<li>Rather than binding an event or signal to a Process, we bind a <a href="https://github.com/alecmce/robotlegs-async-processes-extension/blob/master/src/gaia/lib/robotlegs/process/ProcessDelegate.as">ProcessDelegate</a>. We need a little bit of extra functionality in the ProcessDelegate for the structure to work satisfactorily, but this is not functionally different from the SignalCommandMap extension;</li>
<li>When a delegate is executed, it passes back a signal that the calling object binds to in order to know when the process completes (it may also send back data through this callback);</li>
<li><a href="https://github.com/alecmce/robotlegs-async-processes-extension/blob/master/src/gaia/lib/robotlegs/process/Process.as">Processes</a> can&#8217;t be duck-typed, because they also need to inherit the functionality from their base class Process. Process exposes a complete() method that is called when the Process completes. If complete() is called inside execute(), then the Process becomes functionally equivalent to a Command.</li>
</ul>
<p>In fact, this is not quite the library as developed, because I have started using <a href="https://github.com/alecmce/gaia-tween/tree/master/src/gaia/lib/notice">Notices</a> rather than Signals, so I have ported this across to Signals since it has a much broader adoption. Notices are pared down, simple implementations of Signals that allow you to expose very simple interfaces like <a href="https://github.com/alecmce/gaia-tween/blob/master/src/gaia/lib/notice/SingularNotice.as">the SingularNotice interface</a>. It&#8217;s a preference thing; if anyone would like the original implementation with Notices, I&#8217;m happy to publish it.</p>
<p>I hope that this gives you some food for thought with respect to asynchronous processes. I&#8217;d love to know what you think about the idea, the implementation, the implied critique of RobotLegs. Let me know!</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/library/asynchronous-processes-and-robotlegs/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Reflection on Code Design</title>
		<link>http://alecmce.com/opinion/reflection-on-code-design</link>
		<comments>http://alecmce.com/opinion/reflection-on-code-design#comments</comments>
		<pubDate>Sun, 17 Jul 2011 12:30:08 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=1117</guid>
		<description><![CDATA[I recently created a Time class which can cope with two distinct methodologies for pausing. Time will essentially be a wrapper for getTimer() that has a tick signal that fires once-per-frame and can be used as a replacement for Event.ENTER_FRAME listeners. Sometimes, if you&#8217;re making a game like Asteroids, you want to be able to [...]]]></description>
			<content:encoded><![CDATA[<p>I recently created a Time class which can cope with two distinct methodologies for pausing. Time will essentially be a wrapper for getTimer() that has a tick signal that fires once-per-frame and can be used as a replacement for Event.ENTER_FRAME listeners.</p>
<p>Sometimes, if you&#8217;re making a game like Asteroids, you want to be able to pause the game, and on resume, it continues precisely where it left off. Other times, if you&#8217;re making a social game, when you pause time continues. When you resume, your state has to suddenly catch-up.</p>
<p>You can think about this in terms of whether time is an intrinsic property of your game (if your game pauses, time pauses) or an extrinsic property that your game references (when your game pauses, time carries on).</p>
<p>Which leaves me with three possible designs for my Time class. I found it interesting that I actually went through each of these three designs, and am still unclear about whether the second or third strategy is the best.</p>
<h2>Strategy One</h2>
<pre class="brush: as3; title: ; notranslate">
public class Time
{

    public function Time();

    public function get now():uint;

    public function pause(strategy:PauseStrategy):void;

    public function resume():void;

    public function get tick():ISignal;

}

public class PauseStrategy
{
    public static const TIME_IS_EXTRINSIC;
    public static const TIME_IS_INTRINSIC;
}
</pre>
<p>The first strategy offers a great deal of flexibility. Each time you pause, you can decide whether in this case time is intrinsic or extrinsic. This seems flexible, but then it occurred to me that I couldn&#8217;t conceive of a case in which I would need to keep changing the &#8216;pause strategy&#8217;.</p>
<h2>Strategy Two</h2>
<pre class="brush: as3; title: ; notranslate">
public class Time
{

    public function Time(pauseStrategy:PauseStrategy);

    public function get now():uint;

    public function pause():void;

    public function resume():void;

    public function get tick():ISignal;

}

public class PauseStrategy
{
    public static const TIME_IS_EXTRINSIC;
    public static const TIME_IS_INTRINSIC;
}
</pre>
<p>That led me to the second strategy. I have dropped the PauseStrategy from the pause method and the API looks much easier to use, as it has fewer parameters.</p>
<p>I have left the PauseStrategy as stub-code, but the elegance of the whole PauseStrategy approach is that the TIME_IS_EXTRINSIC and TIME_IS_INTRINSIC constants could contain the core behavioural difference themselves, without needing switching inside either strategy one or two, like this:</p>
<h2>PauseStrategy</h2>
<pre class="brush: as3; title: ; notranslate">

public class PauseStrategy
{
    public static const TIME_IS_EXTRINSIC:PauseStrategy = new ExtrinsicPause();
    public static const TIME_IS_INTRINSIC:PauseStrategy = new IntrinsicPause();

    internal function onResume(timeAtPause:uint, timePaused:uint):uint
    {
        return Number.NaN;
    }
}

final internal class ExtrinsicPause extends PauseStrategy
{
    override internal function onResume(timeAtPause:uint, timePaused:uint):uint;
}

final internal class IntrinsicPause extends PauseStrategy
{
    override internal function onResume(timeAtPause:uint, timePaused:uint):uint;
}
</pre>
<p>In this way both the first two strategies can find out what the time after the pause should be by asking the strategy. The different strategies are geniunely encapsulated.</p>
<p>I am a little uncomfortable in enumerating in this way. There are plenty of ways that you can attempt to make this type-safe, but it does upset me that I have broken many a coding law by making the PauseStrategy class itself broken. It should probably be an interface itself&#8230; and then do I need a PauseStrategy factory? bah&#8230;</p>
<p>The neat API of the second strategy presents a third strategy:</p>
<h2>Strategy Three</h2>
<pre class="brush: as3; title: ; notranslate">
public interface Time
{
    function get now():uint;

    function pause():void;

    function resume():void;

    function get tick():ISignal;
}

public class ExtrinsicTime implements Time;
public class IntrinsicTime implements Time;
</pre>
<p>Here the different functionalities of the two different PauseStrategy objects would be shifted into the two different implementations of Time. Unless I ended up having an internal BaseTime class, the third strategy would mean giving up a certain amount of code <acronym definition="Don't Repeat Yourself">DRY</acronym>ness, since there would be a lot of repeated code in the two different Time implementations. I am always a little uncomfortable defining both an interface and a base class, though I have never been able to explicate exactly why.</p>
<p>So I have replaced two PauseStrategy implementations with two Time implementations. What have I gained? It seems unfeasible that there would be a third time strategy that someone could independently develop and satisfy the API for Time, so is there any good justification for interfacing Time?</p>
<h2>What would The Perfect Coder Do?</h2>
<p>The correct decision for the design of this class is that it should satisfy the current use-case. <acronym definition="Test-Driven Development">TDD</acronym> purists might argue that once the current use-case is satisfied, other design decisions are moot. I am sympathetic to this way of thinking, and cannot offer a counter-argument stronger than suggesting that this design thought-process is in-itself valuable; I do not want to minimally satisfy requirements, I want to satisfy them in the most elegant, satisfying way.</p>
<p>But which is more satisfying? While writing this I have drafted arguments that assert that both strategy 2 and strategy 3 are the best, and have found those arguments unconvincing. I am probably going to settle on strategy 2 for the time-being. Not being The Perfect Coder though, I would welcome a bit of wisdom from the community.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/opinion/reflection-on-code-design/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Working remotely and SVN</title>
		<link>http://alecmce.com/opinion/working-remotely-and-svn</link>
		<comments>http://alecmce.com/opinion/working-remotely-and-svn#comments</comments>
		<pubDate>Fri, 27 May 2011 11:48:31 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[opinion]]></category>
		<category><![CDATA[project]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=1112</guid>
		<description><![CDATA[I am working remotely with a company in Beijing from Aberdeen, UK. The Beijing team is primary, they have setup an svn server to host code and have a QA team for testing. Whatever other test harnesses are in play, a commit isn&#8217;t solid until it passes QA. This is a diary of events, written [...]]]></description>
			<content:encoded><![CDATA[<p>I am working remotely with a company in Beijing from Aberdeen, UK. The Beijing team is primary, they have setup an svn server to host code and have a QA team for testing. Whatever other test harnesses are in play, a commit isn&#8217;t solid until it passes QA. This is a diary of events, written retrospectively.</p>
<h3>Abereen 9am, Beijing 5pm</h3>
<p>Conference call with Beijing to decide what I&#8217;m working on. All goes well, I start working.</p>
<h3>Aberdeen 2pm, Beijing 10pm (Commit +0 hours)</h3>
<p>I try to commit and discover that the svn server has gone down. I am stuck with a commit that I cannot commit. What do I do? The Beijing team will want this commit first thing their time, but that&#8217;s 11 hours away, at 1am my time. I can&#8217;t sit on it until then, and I don&#8217;t want to do nothing. I decide to create a patch</p>
<pre class="brush: bash; title: ; notranslate">svn diff &gt; mywork.diff</pre>
<p>Now, if I get stuck, I can</p>
<pre class="brush: bash; title: ; notranslate">
svn revert -R *
patch -p0 -i mywork.diff
</pre>
<p>and I&#8217;m back to what would be HEAD if svn wasn&#8217;t down! Essentially I&#8217;ve found a way to store atomic commits before they&#8217;re committed, marvellous. And so I continue&#8230;</p>
<h3>Aberdeen 4pm, Beijing: 12pm (Commit +2 hours)</h3>
<pre class="brush: bash; title: ; notranslate">
svn revert -R *
patch -p0 -i mywork.diff

15 out of 15 hunks failed
8 out of 8 hunks failed
3 out of 3 hunks failed
...
</pre>
<p>What!? The patch failed? How can this be!? It makes no sense! Slowly it dawns on me that the Beijing office is universally PC, whereas I am using a Mac. diff and patch expect unix line-endings, and something in there has confused them. Without any external changes at all, I&#8217;ve screwed myself. My work is gone, and I&#8217;ll have to manually apply my diffs back to the source.</p>
<p>Now, clearly I&#8217;m at fault here. I make no bones about the fact that I should have thought long and hard before I svn reverted, but I didn&#8217;t. More fool me.</p>
<h3>Aberdeen 6pm, Beijing 2am (Commit +4 hours)</h3>
<p>I have manually applied my diffs to the source and now I&#8217;m going to stop working on that and do work on a personal project. The last thing I want to do is to have to do that again!</p>
<h3>Aberdeen 1am,  Beijing 9am (Commit +11 hours)</h3>
<p>I&#8217;m asleep, meanwhile Beijing sort out the svn server and get my emails. They don&#8217;t dare touch the diff, especially after my problems.</p>
<h3>Aberdeen 9am, Beijing 4pm (Commit +19 hours)</h3>
<p>I awake, and commit my code. I do other work&#8230;</p>
<h3>Aberdeen 1am, Beijing 9am (Commit +36 hours)</h3>
<p>This is the first opportunity Beijing has had to test my work.</p>
<h2>If we&#8217;d been using git</h2>
<p>Imagine what would have happened if we&#8217;d been using git. I put it to you that I would have saved maybe 6 hours of my time and my work would have been QAed 25 hours sooner.</p>
<h3>Aberdeen: 2pm, Beijing: 10pm (Commit +0 hours)</h3>
<p>Having git committed incrementally into a local branch in my locally cloned repo, I decide it&#8217;s time to merge back to master and push. Push fails, seems like their repo is down. Oh well. I&#8217;ll keep working.</p>
<h3>Aberdeen: 1am,  Beijing 9am (Commit +11 hours)</h3>
<p>Beijing comes in, sort out the git server and get my emails. Realising what has happened they pull from my repo as a remote, which I have made sure is available for them in as a conscientious guy, not only that commit but also the other work I could have done in the 4-6 extra hours I had during that day to do work. My work can be QAed, 25 hours sooner than it actually was.</p>
<h2>Discussion</h2>
<p>Is git better than svn, or svn better than git? Almost certainly your reaction to this question is that the one that you use most and are most comfortable with is better. Of course it is, and I&#8217;m not going to be able to dissuade you with one anecdote.</p>
<p>Don&#8217;t delude yourself: most people when asked this question don&#8217;t say or even think &#8220;well, I use x more so x is better&#8221;, they think of all the reasons why x is better&#8230; but here&#8217;s the thing, they do so <em>after</em> they make their mind up, and usually their minds are made up by emotion rather than rationality. Think about it; it happens a lot. It happens to me, and to everyone at one time or another.</p>
<p>So I&#8217;m not going to tell you that git is better than svn categorically, I&#8217;m just going to say that in this scenario, I think wouldn&#8217;t git have been much better?</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/opinion/working-remotely-and-svn/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Invalidation Manager</title>
		<link>http://alecmce.com/as3/invalidation-manager</link>
		<comments>http://alecmce.com/as3/invalidation-manager#comments</comments>
		<pubDate>Thu, 12 Aug 2010 06:45:27 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=961</guid>
		<description><![CDATA[Introduction Invalidation is a pattern employed to solve problems where updating a model&#8217;s data may happen multiple times per frame, but updating the view&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Invalidation is a pattern employed to solve problems where updating a model&#8217;s data may happen multiple times per frame, but updating the view&#8217;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.</p>
<p>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!</p>
<h2>The Invalidation Pattern</h2>
<p>Consider the following simple implementation for drawing a coloured circle:</p>
<pre class="brush: as3; title: ; notranslate">
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();
	}

}
</pre>
<p>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.</p>
<p>The invalidation pattern resolves it this way:</p>
<pre class="brush: as3; title: ; notranslate">
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();
	}

}
</pre>
<p>Often in AS3, the invalidate() function looks like this:</p>
<pre class="brush: as3; title: ; notranslate">
public function invalidate():void
{
	addEventListener(Event.ENTER_FRAME, onEnterFrame);
}

private function onEnterFrame(event:Event):void
{
	removeEventListener(Event.ENTER_FRAME, onEnterFrame);
	resolve();
}
</pre>
<p>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.</p>
<h2>Where The Invalidation Pattern Becomes Complicated</h2>
<p>Imagine that you have two classes: a line, and a circle, the intersection of which defines two circular segments. In fact, don&#8217;t imagine: look at this:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="640" height="480">
      <param name="movie" value="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/CircleSegmentFromCircleAndLine11.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/CircleSegmentFromCircleAndLine11.swf" width="640" height="480">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>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.</p>
<p>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:</p>
<pre class="brush: as3; title: ; notranslate">
public interface Invalidates
{

	function invalidate():void;

	function get invalidated():Signal;

	function resolve():void;

}
</pre>
<p>and an implementation along these lines:</p>
<pre class="brush: as3; title: ; notranslate">
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 ...
	}
}
</pre>
<p>The problem here is the same problem that led us to consider the Invalidation Pattern in the first place: namely, that the Line&#8217;s resolve() method is going to get called a lot. Sure, we can pack the methods with lots if calls like:</p>
<pre class="brush: as3; title: ; notranslate">
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 ...
}
</pre>
<p>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.</p>
<p>An important feature of this implemenation is that it guarantees that the Line&#8217;s and Circle&#8217;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.</p>
<h2>Managing Invalidation</h2>
<p>The current <a href="http://github.com/alecmce/as3geometry">as3geometry</a> library attempts to solve the problem of invalidation using the <a href="http://github.com/alecmce/as3geometry/blob/master/src/alecmce/invalidation/InvalidationManager.as">InvalidationManager.as</a> class.</p>
<p>The Invalidation Manager handles classes that satisfy the <a href="http://github.com/alecmce/as3geometry/blob/master/src/alecmce/invalidation/Invalidates.as">Invalidates.as</a> interface. Invalidates objects can be registered to the InvalidationManager, and dependencies can be established. As this happens, objects are categorized into <em>tiers</em>.</p>
<p>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.</p>
<p>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.</p>
<p>The problem with this approach comes when, for example, A depends on B depends on C already so they have the following tiers:</p>
<p><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/diagram11.png" alt="" title="diagram1" width="236" height="84" class="aligncenter size-full wp-image-962" /></p>
<p>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.</p>
<p><img src="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/08/diagram21.png" alt="" title="diagram2" width="365" height="75" class="aligncenter size-full wp-image-963" /></p>
<p>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.</p>
<p>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 <a href="http://github.com/alecmce/as3geometry">as3geometry</a> implementation the <a href="http://github.com/alecmce/as3geometry/blob/master/src/as3geometry/AS3GeometryContext.as">AS3GeometryContext.as</a> wraps the InvalidationManager and hooks it to the player events to so that when invalidation occurs it is resolved in good time.</p>
<p>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&#8217; invalidations:</p>
<pre class="brush: as3; title: ; notranslate">
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 ...
	}
}
</pre>
<h2>Conclusion</h2>
<p>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.</p>
<p>The <a href="http://github.com/alecmce/as3geometry">as3geometry</a> implementation wraps the InvalidationManager into an <a href="http://github.com/alecmce/as3geometry/blob/master/src/as3geometry/AS3GeometryContext.as">AS3GeometryContext.as</a> 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.</p>
<p>There is a downside, of course. Currently in <a href="http://github.com/alecmce/as3geometry">as3geometry</a>, 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. <a href="http://www.google.com/search?sourceid=chrome&#038;ie=UTF-8&#038;q=why+are+singletons+bad%3F">There are lots of good reasons why singletons are bad</a>, not least because I might have good reason to have two parallel geometric contexts in one application.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/invalidation-manager/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Why we need Generics in AS3</title>
		<link>http://alecmce.com/as3/why-we-need-generics-in-as3</link>
		<comments>http://alecmce.com/as3/why-we-need-generics-in-as3#comments</comments>
		<pubDate>Tue, 13 Apr 2010 17:27:53 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=861</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>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 <em>without explicitly defining the type</em>. If you are developer that has started coding for player 10, then you&#8217;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.</p>
<h2>What Are Generics?</h2>
<p>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 <code>IObjectPoolable</code> item, such as a <code>reset()</code> method that could be called to clear out any data particular to an &#8216;instance&#8217; of the object. I would then like to be able to specify an <code>ObjectPool</code> class and specify which kind of <code>IObjectPoolable</code> type it is pooling. Then, when I call <code>ObjectPool.consume()</code>, I don&#8217;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 <code>ObjectPool</code>.</p>
<p>The code for such a class might look something like this:</p>
<pre class="brush: as3; title: ; notranslate">
class ObjectPool.&lt;T:IObjectPoolable&gt;
{
	private var _pool:Vector.&lt;T&gt;;
	private var _index:uint;

	public function ObjectPool.&lt;T&gt;()
	{
		_pool = new Vector.&lt;T&gt;();
		_index = 0;
	}

	public function alloc(count:uint):void
	{
		for (var i:uint = 0; i &lt; 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(&quot;You cannot release an object into a pool that it does not come from&quot;);

		object.reset();

		_pool[i] = _pool[index];
		_pool[--index] = object;
	}
}
</pre>
<p><code>T</code> in the above example stands for the <em>type</em> which the <code>ObjectPool</code> pools. Of course, I can&#8217;t test this code so there may be logical errors, but hopefully you see where I&#8217;m going with this.</p>
<p>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&#8217;ll have to run it because errors will only arise at run-time. Compile-time checking is better than run-time checking.</p>
<p>Perhaps if I have <code>Robot</code> objects and <code>Donkey</code> objects I could create two object-pool classes: a <code>RobotObjectPool</code> and a <code>DonkyObjectPool</code> class? That implies that for each <code>IObjectPoolable</code> object that I create I will also need to create a new object pooling class. That&#8217;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&#8217;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.</p>
<h2>A Related Limitation of <code>interface</code></h2>
<p>You may have noticed that in the <code>alloc</code> method above I am constructing the type using <code>new T()</code>. Within the <code>interface IObjectPoolable</code> I have no way of enforcing that the constructor requires no arguments. I should have, either by being able to specify:</p>
<pre class="brush: as3; title: ; notranslate">
public interface IObjectPoolable
{
	function IObjectPoolable();
}
</pre>
<p>or</p>
<pre class="brush: as3; title: ; notranslate">
public interface IObjectPoolable
{
	function new();
}
</pre>
<p>or something like C#, in the <code>ObjectPool</code> class itself, specifying <code>new()</code> to indicate a parameterless constructor:</p>
<pre class="brush: as3; title: ; notranslate">
class ObjectPool.&lt;T:(IObjectPoolable,new())&gt;
</pre>
<p>Note also that to illustrate generics I chose an example in which I wanted to be able to restrict <code>T</code> to a particular set of types, using <code>&lt;T:IObjectPoolable&gt;</code>. This is elegantly done in C#, it should be done in ActionScript too.</p>
<h2>Vector.&lt;T&gt;</h2>
<p>Currently one implementation of generics exists, for <code>Vector.&lt;T&gt;</code>. On the face of it, it is extremely perplexing why generics have been implemented only for <code>Vector</code>, but there are practical reasons why Adobe can&#8217;t simply roll generics out. The <code>Vector.&lt;T&gt;</code> was implemented because of a realisation that iterating over <code>Array</code> represented a specific performance overhead that <code>Adobe</code> could do something about.</p>
<p>During his recent visit to the Flash Gaming Summit, Nicolas Cannasse explained to me that <code>Vector</code> is a hack comprising three classes under the hood. In fact, Adobe engineers have created <code>Vector.&lt;int&gt;</code>, <code>Vector.&lt;Object&gt;</code> and (I think &#8211; though this one is hazy) <code>Vector.&lt;Number&gt;</code>.</p>
<p><strong>UPDATE</strong>: <a href="http://alecmce.com/as3/why-we-need-generics-in-as3#comment-44647489">Robert Penner informs me that I remember this incorrectly</a>. There are in fact four Vector implementations. Follow the link to the comment below for more details.</p>
<p>The two numerical implementations are designed to give specific speed improvements when iterating over collections of numbers. The <code>Vector.&lt;Object&gt;</code> 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 <code>Vector.&lt;Object&gt;</code> is preserved throughout the code.</p>
<p>Adobe then has done a lot of work towards implementing generics, but the <code>Vector</code> implementation was a specific workaround. As we are probably all aware, there&#8217;s a huge difference between a workaround and a truly flexible feature.</p>
<h2>haXe</h2>
<p>If I like generics, why not start using haXe, since <a href="http://haxe.org/ref/type_params">haXe has generics already built in</a>?</p>
<p>There are a few reasons why I&#8217;m reluctant to go down the haXe road at the moment.</p>
<ul>
<li>Firstly, there&#8217;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.</li>
<li>Then, there&#8217;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&#8217;ll adopt haXe, but if I&#8217;m doing this in spare time, it is a daunting task.</li>
<li>Then there&#8217;s the lack of haXe support in <a href="http://www.fdt.powerflasher.com/">FDT</a>. 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.</li>
</ul>
<p>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&#8217;t iterate closer to haXe and soon, there may be no option but to go down the haXe road in the next few months.</p>
<h2>Issues</h2>
<p>With generics there are certain complications that should be addressed. The most subtle of these is something I highlighted in my article <a href="http://alecmce.com/as3/the-problem-with-vector">The Problem with Vector&lt;T&gt;</a>. I incorrectly argued that the following should be ok:</p>
<pre class="brush: as3; title: ; notranslate">
public interface Fruit;
public class Apple implements Fruit;

var fruits:Vector.&lt;Fruit&gt;;
var apples:Vector.&lt;Apple&gt; = new Vector.&lt;Apple&gt;();

fruits = apples;
</pre>
<p>The problem was really that perhaps I had a <code>makeSmoothie(Vector.&lt;Fruit&gt;)</code> method somewhere that expected <code>Vector.&lt;Fruit&gt;</code>, I would have to construct a new <code>Vector.&lt;Fruit&gt;</code> and pass in each member from <code>Vector.&lt;Apple&gt;</code> before then passing that newly constructed object into <code>makeSmoothie</code>. This seemed like an expensive overhead to me.</p>
<p>My brother Ewan pointed out that this is not straightforward. He wrote three articles on this:</p>
<ul>
<li><a href="http://www.ewanmce.co.uk/blog/post/Why-Isne28099t-List3cApple3e-A-Subtype-Of-List3cFruit3e.aspx">the first</a> exploring the problem of trying to add an <code>Orange</code> to the <code>fruits</code> vector, and the consequences surrounding that;</li>
<li><a href="http://www.ewanmce.co.uk/blog/post/Why-Isne28099t-List3cApple3e-A-Subtype-Of-List3cFruit3e-2.aspx">the second</a> 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 <code>Vector.&lt;Fruit, Apple&gt;</code>, where essentially the first type is the exposed type (what you get if you reference an index in the <code>Vector</code>), while the second type is the required type (what type is allowable to be set as a reference for an index).</li>
<li><a href="http://www.ewanmce.co.uk/blog/post/Covariance-and-Contravariance.aspx">and finally</a> an article which explains the concepts behind the C# 4.0 implementation from it&#8217;s core concepts of <em>covariance</em> and <em>contravariance</em>.</li>
</ul>
<h2>Conclusions</h2>
<p>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&#8242;s complexity over AS2, I doubt anyone can seriously argue that AS3 wasn&#8217;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&#8217;s great in my opinion, it allows people like me to spend more time developing more interesting stuff that can&#8217;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.</p>
<p>The ActionScript developer community is a huge asset for Adobe. We are the heart of the Flash Platform. Right now, it&#8217;s much stronger than most people give it credit. For example, Microsoft&#8217;s new <a href="http://www.kin.com/">KIN website</a> 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.</p>
<p>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&#8217;s power-base dissolves with it.</p>
<p>ActionScript needs to evolve. It could do worse than evolving to support generics.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/why-we-need-generics-in-as3/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		</item>
		<item>
		<title>3-Party Swingometer</title>
		<link>http://alecmce.com/as3/historical-uk-election-visualisation</link>
		<comments>http://alecmce.com/as3/historical-uk-election-visualisation#comments</comments>
		<pubDate>Thu, 08 Apr 2010 06:09:59 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[project]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=814</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>The BBC coverage of UK elections is well-known for its use of the <a href="http://en.wikipedia.org/wiki/Swingometer">Swingometer</a>. The Swingometer represents parliamentary constituencies as points on a line. A central point represents equality between the two major parties: the <a href="http://en.wikipedia.org/wiki/Labour_Party_(UK)">Labour Party</a> (red, politically centre-left) and the <a href="http://en.wikipedia.org/wiki/Conservative_Party_(UK)">Conservative Party</a> (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&#8217;s hands.</p>
<p>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 <a href="http://en.wikipedia.org/wiki/Liberal_democrats">Liberal Democrats</a> hold a position in UK politics far stronger than any other party that would be considered &#8216;others&#8217; (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 &#8211; as the polls have been predicting &#8211; the UK experiences a hung-parliament.</p>
<p>This small application was the product of a day or so prototyping, using Bit 101&#8242;s <a href="www.minimalcomps.com/">Minimal Components</a> and <a href="http://www.robotlegs.org/">RobotLegs</a> to see if I could come up with something a bit more interesting than the<a href="bit.ly/c5ujAv">BBC&#8217;s online Swingometer</a>. It lacks the BBC&#8217;s finesse (which is unsurprising for a very quick prototype), but I think it is rather more fair to the Liberal Democrats.</p>
<div style="text-align: center; margin: 0px auto;">

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_1" width="600" height="640">
      <param name="movie" value="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/04/Main21.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://www.alecmce.com.php5-16.dfw1-1.websitetestlink.com/wp-content/uploads/2010/04/Main21.swf" width="600" height="640">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

</div>
<h2>Political Notes</h2>
<p>Several smaller parties exist, notably the <a href="http://en.wikipedia.org/wiki/Scottish_National_Party">Scottish National Party</a> and <a href="http://en.wikipedia.org/wiki/Plaid_Cymru">Plaid Cymru</a>, 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.</p>
<p>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.</p>
<p>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&#8217; power grew in the seventies, and reintroduced it as it waned in the eighties and nineties. Now, the <a href="http://bit.ly/c5ujAv">current implementation</a> on their website has three swingometers that can be tabbed between. It is strange then that they haven&#8217;t chosen to adopt a more sophisticated representation.</p>
<p>The source data that I used for this application can be found at <a href="http://www.pippanorris.com">pippanorris.com</a>. 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.</p>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/historical-uk-election-visualisation/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Ifs and Buts and Strings</title>
		<link>http://alecmce.com/as3/ifs-and-buts-and-strings</link>
		<comments>http://alecmce.com/as3/ifs-and-buts-and-strings#comments</comments>
		<pubDate>Fri, 19 Mar 2010 19:13:52 +0000</pubDate>
		<dc:creator>alecmce</dc:creator>
				<category><![CDATA[as3]]></category>
		<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://alecmce.com/?p=801</guid>
		<description><![CDATA[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&#8217;s both Bad and Wrong. Luv, K #dodgylibraries To support the argument, David put this [...]]]></description>
			<content:encoded><![CDATA[<p>It has been a fun morning in the twitterverse. @kaeladan (aka David Wagner, my replacement at Yomego, and friend) <a href="http://bit.ly/9HogvP">tweeted</a> that:</p>
<blockquote><p>
Dear Flash programmers, stop using if( foo ) or if( !foo ) to check if an object is null. It&#8217;s both Bad and Wrong. Luv, K #dodgylibraries
</p></blockquote>
<p>To support the argument, David put <a href="http://gist.github.com/337512">this gist on github</a>:</p>
<pre class="brush: as3; title: ; notranslate">
var iAmAStringInstance :String = &quot;&quot;;
var iAmANullString :String = null;

if(iAmAStringInstance)
    trace(&quot;iAmAStringInstance: That there is an instance!&quot;);
else
    trace(&quot;iAmAStringInstance: That there is a null object!&quot;);

if(iAmANullString)
    trace(&quot;iAmANullString: That there is an instance!&quot;);
else
    trace(&quot;iAmANullString: That there is a null object!&quot;);
</pre>
<p>It took me a while to understand what I had trouble with in David&#8217;s tweet, but the gist helps. The trick is that the semantic label that David has applied to the <code>if (foo)</code> conditional is not correct in the context of a String. If we use <code>if (foo)</code> we are not in fact testing for existence. We are testing for existence and non-triviality. The implication that all we&#8217;re doing is testing for existence versus nullity comes from the trace statements within the conditionals. These are well-meant, but misleading.</p>
<p>That David used a <code>String</code> for this example is significant. A typed object reference can only resolve to false if it is null. <code>String</code> is one of the few ambiguous cases, like a <code>Number</code> or an <code>Object</code> (which is ambiguous because it could be a <code>String</code> or a <code>Number</code>).</p>
<p>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&#8217;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&#8217;s a over-the-top to argue as <a href="http://bit.ly/aSlooF">DavidArno does</a> that:</p>
<blockquote><p>
@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.
</p></blockquote>
<p>That&#8217;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.</p>
<p>I often want to test whether something is <em>substantive</em>. Take a URL for example &#8211; 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&#8217;s been filled in, so I can use <code>if (url)</code> to test for that. It would be as annoying in this brave new paradigm to have to write <code>if (url != "")</code> as it would to have to write <code>if (url == null)</code> in the current one.</p>
<p>To go back to the example then, we need to be careful to be clear about what our code actually means:</p>
<pre class="brush: as3; title: ; notranslate">
if(iAmAStringInstance)
    trace(&quot;iAmAStringInstance is neither null nor empty&quot;);
else
    trace(&quot;iAmAStringInstance is either null or empty&quot;);

if(iAmANullString)
    trace(&quot;iAmANullString is neither null nor empty&quot;);
else
    trace(&quot;iAmANullString is either null or empty&quot;);
</pre>
<p>In one sense then, I agree with David, though not in the sense he intended. It goes over Twitter&#8217;s character limit, and it&#8217;s rather less pithy, but perhaps he might have tweeted:</p>
<blockquote><p>
Dear Flash programmers, stop using if( foo ) or if( !foo ) to check if an <em>untyped</em> object<em>, string or number</em> is null. It&#8217;s Bad and Wrong <em>in these particular contexts, if what you really are trying to do is to check for existence, rather than substance.</em>.
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://alecmce.com/as3/ifs-and-buts-and-strings/feed</wfw:commentRss>
		<slash:comments>10</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>alecmce</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: Anatoly [...]]]></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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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>&#8216;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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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>18</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>alecmce</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 [...]]]></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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">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; title: ; notranslate">
[Inject]
public var mechanism:DragMechanism;
</pre>
<h3>injector.mapSingletonOf</h3>
<pre class="brush: as3; title: ; notranslate">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; title: ; notranslate">
[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; title: ; notranslate">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; title: ; notranslate">
[Inject]
public var model:BatGeometry;
</pre>
<h2>Mediators and Components</h2>
<pre class="brush: as3; title: ; notranslate">
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; title: ; notranslate">
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; title: ; notranslate">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; title: ; notranslate">
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>18</slash:comments>
		</item>
	</channel>
</rss>

