<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Technical Tidbits</title>
	<atom:link href="http://dodgybits.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://dodgybits.org</link>
	<description></description>
	<lastBuildDate>Wed, 20 Jan 2010 22:44:23 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='dodgybits.org' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/916bbaa2593573e4854495809fb5c7ac?s=96&#038;d=http://s2.wp.com/i/buttonw-com.png</url>
		<title>Technical Tidbits</title>
		<link>http://dodgybits.org</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://dodgybits.org/osd.xml" title="Technical Tidbits" />
	<atom:link rel='hub' href='http://dodgybits.org/?pushpress=hub'/>
		<item>
		<title>ActionScript Puzzlers Answers</title>
		<link>http://dodgybits.org/2010/01/20/actionscript-puzzlers-answers/</link>
		<comments>http://dodgybits.org/2010/01/20/actionscript-puzzlers-answers/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 22:38:35 +0000</pubDate>
		<dc:creator>andybryant</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dodgybits.org/?p=78</guid>
		<description><![CDATA[In ActionScript Puzzlers I presented a list of 10 puzzlers meant to test your knowledge of the language. Without starting there, this post isn&#8217;t going to make a lot of sense. I also encourage you to try running the puzzler code yourself before coming back here. If it doesn&#8217;t do what you expect, try stepping through [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=78&subd=andybryant&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>In <a href="http://dodgybits.org/2010/01/17/actionscript-puzzlers/">ActionScript Puzzlers</a> I presented a list of 10 puzzlers meant to test your knowledge of the language. Without starting there, this post isn&#8217;t going to make a lot of sense. I also encourage you to try running the puzzler code yourself before coming back here. If it doesn&#8217;t do what you expect, try stepping through or modifying the code until you understand what&#8217;s going on.</p>
<p>In this post I&#8217;ll reveal the answers to each puzzler, and ways to avoid similar pitfalls in your own coding.</p>
<h3>Puzzle 1: Looping</h3>
<p>Here&#8217;s the output of a call to <code>loopy()</code>:<br />
<code>BEE,BOP,BOP,BOO</code></p>
<p>Why the extra <code>BOP</code>? This code demonstrates the lack of block scope in ActionScript. Although it appears that <code>caps</code> is defined only within the for loop, it is actually defined at the scope of the function. Therefore for the second <code>null</code> in the array, <code>caps</code> was not overwritten, but instead retained its value from the previous iteration of the loop.</p>
<p>The ActionScript compiler effectively shifts all the variable declarations to the top of the method before running your code. This explains why the compiler doesn&#8217;t complain when you use a variable before declaring it, or why it gives you a warning when you declare the same variable in two separate loops. This can be especially confusing for programmers with a C# or Java background.</p>
<p>The same issue holds true for JavaScript. Yahoo&#8217;s JavaScript architect <a href="http://www.amazon.co.uk/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742/">Douglas Crockford advocates</a> declaring all your local variables at the start of your functions. This avoids any ambiguity about the scope of your local variables. This advice holds true for ActionScript as well.</p>
<p>For the somewhat contrived puzzler example, the following rewrite produces just the one <code>BOP</code>.</p>
<pre class="brush: jscript;">
private function loopy() : String {
	var names : Array = [ null, &quot;bee&quot;, &quot;bop&quot;, null, &quot;boo&quot; ];
	var name : String;
	var result : Array = [];
	var caps : String;

	for each (name in names) {
		caps = null;

		if (name != null) {
			caps = name.toUpperCase();
		}
		if (caps != null) {
			result.push(caps);
		}
	}
	return result.join(',');
}
</pre>
<p>You could further reduce the for loop as follows&#8230;</p>
<pre class="brush: jscript;">
	for each (name in names) {
		if (name != null) {
			caps = name.toUpperCase();
			result.push(caps);
		}
	}
</pre>
<h3>Puzzle 2: Sorted</h3>
<p>Here&#8217;s the output of a call to <code>sorted()</code>:<br />
<code>[ -22, -5, 1, 1, 22, 33, 4, 71 ] (length=8)</code></p>
<p>By default, <code>Array.sort()</code> sorts using Unicode values, so 4 appears after 22 and 33. To search numerically replace line 3 with:<br />
<code>var sorted : Array = values.sort(Array.NUMERIC);</code><br />
This produces <code>[ -22, -5, 1, 1, 4, 22, 33, 71 ] (length=8)</code></p>
<p>A cursory look at the API, may make you think <code>values.sort(Array.NUMERIC | Array. UNIQUESORT);</code> would eliminate the duplicate 1. In actual fact, that call does something far less useful &#8211; it returns <code>0</code> to indicate the array contains a duplicate.</p>
<p>The new <code>Vector</code> class has an almost identical list of methods to <code>Array</code>, except they wisely chose to replace the confusing sort methods with one that simply takes a typed compare function.</p>
<h3>Puzzle 3: Delimiters</h3>
<p>Here&#8217;s the output of a call to <code>delimiters()</code>:<br />
<code>[ 1, 2, 3 ] (length=3)<br />
[ 1, 2, 3 ] (length=3)<br />
[ 1, 2, 3,  ] (length=4)<br />
[ , 1, 2, 3 ] (length=4)<br />
[ , , 1, 2, 3,  ] (length=6)<br />
</code></p>
<p>ActionScript is inconsistent in how it handles delimiters in array literals. A trailing comma is ignored. A leading comma, or whitespace followed by a comma within the list results in a <code>undefined</code> element added to the <code>Array</code>.</p>
<h3>Puzzle 4: Indecisive</h3>
<p>Here&#8217;s the output of a call to <code>responseOrError(indecisive)</code>:<br />
<code>finally wins</code></p>
<p>In fact finally always &#8216;wins&#8217; with any combination of try, catch or finally blocks throwing exceptions or returning values. It does make for confusing reading though. It&#8217;s generally best to only have a single return call in any function and for it to be the last statement. This may feel like a step backwards, but there&#8217;s almost always an elegant way of doing this.</p>
<h3>Puzzle 5: Illusive dates</h3>
<p>Here&#8217;s the output of a call to <code>dates()</code>: <code>start=2009 08 31 finish=2010 03 15</code></p>
<p>Much like Java, the ActionScript <code>Date</code> class is nasty.</p>
<ol>
<li>day of the month is 1-indexed , but month is 0-indexed</li>
<li>there&#8217;s no static constants for days of the week or months of the year to aid readability</li>
<li>confusing property names: <code>date</code> is day of the month, <code>time</code> is milliseconds since epoch</li>
<li><code>timezoneOffset</code> is read-only so it&#8217;s impossible to cleanly represent timezones other than the local timezone</li>
</ol>
<p>At first glance, the start date looks like 31st July, but it&#8217;s actually 31st August due to month being 0-indexed. <code>finish</code> was messed up because we applied the new date incrementally. See the comments added below for the value of date after each statement.</p>
<pre class="brush: jscript;">
private function dates() : String {
	var formatter : DateFormatter = new DateFormatter();
	formatter.formatString = &quot;YYYY MM DD&quot;;

	var date : Date = new Date( 2009, 7, 31); // 31st Aug 2009
	var result : String = &quot;start=&quot; + formatter.format(date);

	date.fullYear = 2010; // 31st Aug 2010
	date.month = 1;       //  3rd Mar 2010
	date.date = 15;       // 15th Mar 2010
	result += &quot; finish=&quot; + formatter.format(date);

	return result;
}
</pre>
<p>When setting the month, the day of the month is too big to match any valid day in February. It&#8217;s over by 3, so the date is rolled ahead by this amount into March. Finally the day of the month is overwritten with 15.</p>
<p>To avoid surprises like this in your code, add constants for the months, and make your date changes atomically. </p>
<pre class="brush: jscript;">
public static const JANUARY : int = 0;
public static const FEBRUARY : int = 1;
public static const MARCH : int = 2;
public static const APRIL : int = 3;
public static const MAY : int = 4;
public static const JUNE : int = 5;
public static const JULY : int = 6;
public static const AUGUST : int = 7;
public static const SEPTEMBER : int = 8;
public static const OCTOBER : int = 9;
public static const NOVEMBER : int = 10;
public static const DECEMBER : int = 11;

private function dates() : String {
	var formatter : DateFormatter = new DateFormatter();
	formatter.formatString = &quot;YYYY MM DD&quot;;
	var date : Date = new Date( 2009, AUGUST, 31);
	var result : String = &quot;start=&quot; + formatter.format(date);
	date.setFullYear(2010, FEBRUARY, 15);
	result += &quot; finish=&quot; + formatter.format(date);
	return result;
}
</pre>
<p>The updated function call now returns: <code>start=2009 08 31 finish=2010 02 15</code></p>
<h3>Puzzle 6: Sparsity</h3>
<p>Here&#8217;s the output of a call to <code>sparse()</code>:<br />
<code>Array: length=101 count=3 Vector: length=101 count=101 ArrayCollection: length=101 count=101</code></p>
<p><code>Arrays</code> can be sparse, as in this example, where setting a value at a high index does not fill in all the values in between. Effectively <code>Array</code> is just like a normal <code>Object</code>, except:<br />
a) it has a bunch of handy collection orientated methods you have at your disposal<br />
b) it supports the very handy array literal format</p>
<p><code>Vectors</code>, in contrast, are typed, are not sparse, and do not support the addition of properties with names other than positive integers (this is enforced at runtime, not compiler time). These limitations make live much easier for the VM. Lookups should now be constant time operations.</p>
<p>Even though <code>ArrayCollection</code> wraps an <code>Array</code>, it does not retain the appearance of being sparse. When you loop through the collection, it &#8216;fills in&#8217; the gaps with <code>null</code> values.</p>
<h3>Puzzle 7: Mixed up</h3>
<p>If you ran the following code, you would find that <code>mixedUp()</code> did not return anything at all, but instead throws the following error:<br />
<code>TypeError: Error #1010: A term is undefined and has no properties.</code></p>
<p>What&#8217;s gone wrong? Despite first appearances, the <code>objectLiteral()</code> function does not in fact return an <code>Object</code>, but instead returns <code>undefined</code>. This is due to ActionScript repeating the mistake made in JavaScript; making semicolons optional at the end of statements. Here the compiler interpreted the code as an empty return statement, following by a block containing two labels. I was actually a little bit sneaky here, as that is not even a valid object literal, since I missed out the comma.</p>
<p>To avoid this happening in your code, whenever splitting a statement over multiple lines always finish any line with a symbol that couldn&#8217;t possibly be the end of a statement. For instance: <code>|| &amp;&amp; , + - * / .</code><br />
You should also consider using the C/Java style syntax for blocks having the { at the end of the previous line, rather than on a line on its own. I&#8217;ve used this style in all my examples.</p>
<p>Here&#8217;s the code after fixing the <code>objectLiteral()</code> function:</p>
<pre class="brush: jscript;">
private function objectLiteral() : * {
	return {
		a : 123,
		b : &quot;888&quot;
	};
}		

private function mixedUp() : String {
	var lit : * = objectLiteral();
	return lit.a + lit.b;
}
</pre>
<p>This amended code now outputs the following:<br />
<code>123888</code></p>
<p>If you&#8217;re wondering why it doesn&#8217;t output 1011, the + operator uses string concatenation if either argument is a <code>String</code>.</p>
<h3>Puzzle 8: Unicoder</h3>
<p>Clued up readers will recognize this example from the Java Puzzlers book (Puzzle 14). The reason I included it, is that it&#8217;s one of the examples that produces quite different results in ActionScript.</p>
<p>\u0022 is unicode for <code>"</code> (double quote). In Java, Unicode characters are given first class treatment, with the compiler seeing it as no different from an actual double quote. In this case the statement becomes the equivalent of:<br />
<code>return "a".length + "b".length; // returns 2</code></p>
<p>Here&#8217;s the output of a call to <code>escaped()</code> in ActionScript:<br />
<code>14</code></p>
<p>ActionScript recognizes the characters as Unicode, but it doesn&#8217;t translate them into symbols until <em>after</em> the parser has translated the source into tokens. It treats the Unicode as if it were escaped characters. The following code produces identical results.</p>
<pre class="brush: jscript;">
private function escaped() : int {
	return &quot;a\&quot;.length + \&quot;b&quot;.length;
}
</pre>
<h3>Puzzle 9: Constantly confused</h3>
<p>Create the following two classes:</p>
<pre class="brush: jscript;">
package
{
	public class A
	{
		protected const FOO : String = &quot;foo&quot;;
	}
}
</pre>
<pre class="brush: jscript;">
package
{
	public class B extends A
	{
		public var result : String;

		public function B()
		{
			result = 'before: ' + FOO;
			super();
			result += ' after: ' + FOO;
		}
	}
}
</pre>
<p>Then try running the following:</p>
<pre class="brush: jscript;">
private function superDuper() : String {
	return new B().result;
}
</pre>
<p>Calling <code>superDuper()</code> will return the following result:<br />
<code>before: null after: foo</code></p>
<p>Unlike Java, ActionScript lets you position a call to <code>super()</code> anywhere you like in your constructor. If you don&#8217;t include a call to <code>super()</code> yourself, the compiler will add one at the start of your constructor. This flexibility comes with extra responsibility. Constructor code before <code>super()</code> must not rely on member variables or constants in any superclass. In this case, changing the <code>FOO</code> constant to be static will result in it always being properly initialized.</p>
<h3>Puzzle 10: Extended Array</h3>
<p>If you attempted to run <code>arrayMax()</code> any number of things could happen.</p>
<p>Under Flex 3.4 I get the following result:<br />
<code>len=3 max=NaN</code></p>
<p>Under Flex 4.0, I generally get the same as Flex 3.4, but if I chose to display the results in a Spark TextArea, I get the following error:<br />
<code>TypeError: Error #1034: Type Coercion failed: cannot convert Function-9 to flashx.textLayout.container.ContainerController.</code></p>
<p>What is going wrong here? Our fancy new <code>max()</code> function is now being returned when iterating through <em>any</em> Array! Even though the length of <code>numbers</code> is correctly reported as 3, if you were to iterate through the items using <code>for each</code>, you would find there are in fact 4 values.</p>
<p>To prevent this from happening, you need to indicate that this function should not be included in iterators, using the <code>setPropertyIsEnumerable</code> method.</p>
<p>Here&#8217;s an updated version of <code>arrayMax()</code> that now produces the expected result: <code>len=3 max=10</code></p>
<pre class="brush: jscript;">
private function arrayMax() : String {
	Array.prototype.max = function() : Number {
		var array : Array = this;
		var result : Number = Number.MIN_VALUE;
		for each ( var item : Number in array ) {
			result = Math.max( result, item );
		}
		return result;
	};
	Array.prototype.setPropertyIsEnumerable(&quot;max&quot;, false );

	var numbers : Array = [ 1, 2, 10];
	return StringUtil.substitute('len={0} max={1}',
		numbers.length, numbers.max());
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andybryant.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andybryant.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/andybryant.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/andybryant.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/andybryant.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/andybryant.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/andybryant.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/andybryant.wordpress.com/78/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/andybryant.wordpress.com/78/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/andybryant.wordpress.com/78/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=78&subd=andybryant&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://dodgybits.org/2010/01/20/actionscript-puzzlers-answers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6e9e2e4e81e9644d14c460d45866b451?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybryant</media:title>
		</media:content>
	</item>
		<item>
		<title>ActionScript Puzzlers</title>
		<link>http://dodgybits.org/2010/01/17/actionscript-puzzlers/</link>
		<comments>http://dodgybits.org/2010/01/17/actionscript-puzzlers/#comments</comments>
		<pubDate>Sun, 17 Jan 2010 18:56:43 +0000</pubDate>
		<dc:creator>andybryant</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://dodgybits.org/?p=60</guid>
		<description><![CDATA[Joshua Bloch is well known for his work on several Java APIs and the excellent book Effective Java. He is also co-author of Java Puzzlers, a catalogue of the less well traveled quirks and corner cases of the language. This is invaluable reading for enthusiastic Java specification pedants, and sadistic job interviewers. If you are not caught [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=60&subd=andybryant&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Joshua Bloch is well known for his work on several Java APIs and the excellent book <a href="http://www.amazon.co.uk/Effective-Java-Second-Joshua-Bloch/dp/0321356683/">Effective Java</a>. He is also co-author of <a href="http://www.amazon.co.uk/Java-Puzzlers-Traps-Pitfalls-Corner/dp/032133678X">Java Puzzlers</a>, a catalogue of the less well traveled quirks and corner cases of the language. This is invaluable reading for enthusiastic Java specification pedants, and sadistic job interviewers. If you are not caught out by at least a handful of these puzzlers, you no doubt design JVMs in your spare time.</p>
<p>In homage to this book, I&#8217;ve collected a small collection of oddities specific to Actionscript 3 (AS3). ActionScript has its roots in ECMAScript, but moved away from prototypal inheritance with AS3 favouring strong typing and class-based inheritance. I have the good fortune of being able to draw on three sources for my collection of puzzlers:</p>
<ol>
<li><strong>JavaScript</strong> &#8211; There is no shortage of verbiage on the interwebs on the shortcomings of JavaScript. With its shared roots, ActionScript inherits both the good and also some, but not all, of the bad parts.</li>
<li><strong>Java</strong> &#8211; A number of the Java Puzzlers are directly applicable to AS3. Rather than repeating these here, I&#8217;ve listed the puzzlers that also apply to AS3 and suggest you get the book and try them out yourself, if you&#8217;re interested (see footnote).</li>
<li><strong>ActionScript</strong> &#8211; A few puzzlers exist due to features unique to ActionScript.</li>
</ol>
<p>Without further ado, let&#8217;s get to the puzzlers.</p>
<h3>Puzzle 1: Looping</h3>
<p>What does a call to <code>loopy()</code> return?</p>
<pre class="brush: jscript;">
private function loopy() : String {
  var names : Array = [ null, &quot;bee&quot;, &quot;bop&quot;, null, &quot;boo&quot; ];
  var result : Array = [];

  for each (var name : String in names) {
    var caps : String;

    if (name != null) {
      caps = name.toUpperCase();
    }
    if (caps != null) {
      result.push(caps);
    }
  }
  return result.join(',');
}
</pre>
<h3>Puzzle 2: Sorted</h3>
<p>What does a call to <code>sorted()</code> return?</p>
<pre class="brush: jscript;">
private function sorted() : String {
	var values : Array = [ 22, 33, 71, 1, 4, -5, -22, 1 ];
	var sorted : Array = values.sort();
	return arrayToString( sorted );
}

public static function arrayToString( a : Array ) : String {
	return StringUtil.substitute(
		&quot;[ {0} ] (length={1})&quot;,
		a.join(', '), a.length);
}
</pre>
<h3>Puzzle 3: Delimiters</h3>
<p>What does a call to <code>delimiters()</code> return?</p>
<pre class="brush: jscript;">
private function delimiters() : String {
	var result : String = &quot;&quot;;
	result += arrayToString( [ 1, 2, 3 ] ) + '\n';
	result += arrayToString( [ 1, 2, 3, ] ) + '\n';
	result += arrayToString( [ 1, 2, 3, , ] ) + '\n';
	result += arrayToString( [ , 1, 2, 3, ] ) + '\n';
	result += arrayToString( [ , ,1, 2, 3, , ] ) + '\n';
	return result;
}

public static function arrayToString( a : Array ) : String {
	return StringUtil.substitute(
		&quot;[ {0} ] (length={1})&quot;,
		a.join(', '), a.length);
}
</pre>
<h3>Puzzle 4: Indecisive</h3>
<p>What does a call to <code>responseOrError(indecisive)</code> return?</p>
<pre class="brush: jscript;">
private function responseOrError( myFunction : Function ) : String {
	var response : String;
	try {
		response = myFunction();
	} catch ( e : Error ) {
		response = e.message;
	}
	return response;
}

private function indecisive() : String {
	try {
		throw new Error(&quot;try wins&quot;);
	} catch (e : Error ) {
		throw new Error(&quot;catch wins&quot;);
	} finally {
		return &quot;finally wins&quot;;
	}
}
</pre>
<h3>Puzzle 5: Illusive dates</h3>
<p>What does a call to <code>dates()</code> return?</p>
<pre class="brush: jscript;">
private function dates() : String {
	var formatter : DateFormatter = new DateFormatter();
	formatter.formatString = &quot;YYYY MM DD&quot;;

	var date : Date = new Date(2009, 7, 31);
	var result : String = &quot;start=&quot; + formatter.format(date);

	date.fullYear = 2010;
	date.month = 1;
	date.date = 15;
	result += &quot; finish=&quot; + formatter.format(date);

	return result;
}
</pre>
<h3>Puzzle 6: Sparsity</h3>
<p>What does a call to <code>sparse()</code> return?</p>
<pre class="brush: jscript;">
private function sparse() : String {
	var values : Array = [ 1, 2 ];
	var valuesAC : ArrayCollection;
	var valuesVector : Vector.&lt;int&gt;;
	var count : int = 0;
	var value : int;
	var result : String = '';
	values[ 100 ] = 3;
	for each (value in values) {
		count++;
	}
	result = StringUtil.substitute(&quot;Array: length={0} count={1} &quot;,
		values.length, count );

	valuesVector = Vector.&lt;int&gt;(values);
	count = 0;
	for each (value in valuesVector) {
		count++;
	}
	result += StringUtil.substitute(&quot;Vector: length={0} count={1} &quot;,
		valuesVector.length, count );

	valuesAC = new ArrayCollection(values);
	count = 0;
	for each (value in valuesAC) {
		count++;
	}
	result += StringUtil.substitute(&quot;ArrayCollection: length={0} count={1}&quot;,
		valuesAC.length, count );

	return result;
}
</pre>
<h3>Puzzle 7: Mixed up</h3>
<p>What does a call to <code>mixedUp()</code> return?</p>
<pre class="brush: jscript;">
private function objectLiteral() : * {
	return
	{
		a : 123
		b : &quot;888&quot;
	};
}

private function mixedUp() : String {
	var lit : * = objectLiteral();
	return lit.a + lit.b;
}
</pre>
<h3>Puzzle 8: Unicoder</h3>
<p>What does a call to <code>escaped()</code> return?</p>
<pre class="brush: jscript;">
private function escaped() : int {
	return &quot;a\u0022.length + \u0022b&quot;.length;
}
</pre>
<h3>Puzzle 9: Constantly confused</h3>
<p>Demonstrate a <code>const</code> having two different values within the same function call.</p>
<h3>Puzzle 10: Extended Array</h3>
<p>The <code>Array</code> class includes a number of methods that encourage functional style programming. For instance, the following line takes a list of tweets, filters down to those created today, extracts the body them adds these to a blotter.</p>
<p><code>allTweets.filter(createdToday).map(body).forEach(appendToBlotter);</code></p>
<p>This syntax is very readable, avoids out-by-one errors and encourages you to break up your code into short well defined methods. Since <code>Array</code> is a dynamic class, you can extend it to add your own methods, however this would limit its usefulness since it would only work on instances of your subclass, and not regular Arrays. Although prototypal inheritance is generally discouraged, it comes in very handy in this circumstance. By adding methods to the <code>Array</code> prototype, they will become available to <em>all</em> <code>Array</code> instances.</p>
<p>Here&#8217;s an example of using prototype inheritance on the <code>Array</code> class. What does a call to <code>arrayMax()</code>return?</p>
<pre class="brush: jscript;">
private function arrayMax() : String {
	Array.prototype.max = function() : Number {
		var array : Array = this;
		var result : Number = Number.MIN_VALUE;
		for each ( var item : Number in array ) {
			result = Math.max( result, item );
		}
		return result;
	};

	var numbers : Array = [1, 2, 10];
	return StringUtil.substitute('len={0} max={1}',
		numbers.length, numbers.max());
}
</pre>
<p><strong>Answers are now available <a href="http://dodgybits.org/2010/01/20/actionscript-puzzlers-answers/">here</a>.</strong></p>
<p><strong><span id="more-60"></span></strong></p>
<p><strong><a href="http://www.amazon.co.uk/Java-Puzzlers-Traps-Pitfalls-Corner/dp/032133678X/">Java Puzzlers</a> that apply to ActionScript</strong></p>
<ul>
<li>Puzzle 1: Oddity</li>
<li>Puzzle 2: Time for a Change</li>
<li>Puzzle 7: Swap Meat</li>
<li>Puzzle 13: Animal Farm (if you substitute <code>===</code> for <code>==</code>)</li>
<li>Puzzle 22: Dupe of URL</li>
<li>Puzzle 25: Inclement Increment</li>
<li>Puzzle 26: In the loop</li>
<li>Puzzle 27: Shifty i&#8217;s</li>
<li>Puzzle 28: Looper</li>
<li>Puzzle 29: Bride of Looper</li>
<li>Puzzle 30: Son of Looper</li>
<li>Puzzle 36: Indecision</li>
<li>Puzzle 40: The Reluctant Constructor</li>
</ul>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andybryant.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andybryant.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/andybryant.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/andybryant.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/andybryant.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/andybryant.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/andybryant.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/andybryant.wordpress.com/60/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/andybryant.wordpress.com/60/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/andybryant.wordpress.com/60/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=60&subd=andybryant&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://dodgybits.org/2010/01/17/actionscript-puzzlers/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6e9e2e4e81e9644d14c460d45866b451?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybryant</media:title>
		</media:content>
	</item>
		<item>
		<title>Flex data binding pitfalls</title>
		<link>http://dodgybits.org/2009/04/12/flex-data-binding-pitfalls/</link>
		<comments>http://dodgybits.org/2009/04/12/flex-data-binding-pitfalls/#comments</comments>
		<pubDate>Sun, 12 Apr 2009 22:54:23 +0000</pubDate>
		<dc:creator>andybryant</dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[Data Binding]]></category>

		<guid isPermaLink="false">http://dodgybits.org/?p=24</guid>
		<description><![CDATA[Flex data binding provides a powerful mechanism for reacting to data changes, but it can be exceptionally tricky to debug when it goes wrong. This post is an accumulation of advice gleaned from colleagues, blogs and painful personal experience into how to avoid some of the nastiest of binding woes.
The best place to start is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=24&subd=andybryant&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p>Flex data binding provides a powerful mechanism for reacting to data changes, but it can be exceptionally tricky to debug when it goes wrong. This post is an accumulation of advice gleaned from colleagues, blogs and painful personal experience into how to avoid some of the nastiest of binding woes.</p>
<p>The best place to start is to read Chapter 40 (Data Binding) of the <a href="http://livedocs.adobe.com/flex/3/devguide_flex3.pdf">Adobe Flex 3 developer guide</a>; a great introduction to the topic. I&#8217;m taking this as assumed reading, so won&#8217;t be covering the many tips contained therein.</p>
<p>Let&#8217;s jump straight into the gory details&#8230;</p>
<p>1) <strong>Don&#8217;t use constants as Bindable event names</strong>.</p>
<pre class="brush: jscript;">
public static const ASK_PRICE_CHANGE : String =
   &quot;ASK_PRICE_CHANGE&quot;;

// DON'T DO THIS!!!!!

[Bindable(event=ASK_PRICE_CHANGE)]
public function get askPrice():Number
{
	return _askPrice;
}
public function set askPrice(value : Number) : void
{
	if (value != _askPrice) {
		_askPrice = value;
		dispatchEvent(new Event(ASK_PRICE_CHANGE));
	}
}
</pre>
<p>It&#8217;s a great idea in theory, but it doesn&#8217;t work. It looks like you&#8217;re using the constant here, but it&#8217;s just a literal string. If you change the constant value, the binding will not fire.</p>
<p>2) <strong>Don&#8217;t rely on the execution order of bindings</strong>.<br />
You can&#8217;t rely on the order staying the same, even if it works for you now. A refactoring of your source file, or changes to the behaviour of future Flex compilers could cause your assumption to fail in future. Here&#8217;s a good example:</p>
<pre class="brush: xml;">
&lt;mx:Panel id=&quot;foo&quot;
   visible=&quot;{model.canViewFoo}&quot;
   includeInLayout=&quot;{foo.visible}&quot;&gt;
...
&lt;/mx:Panel&gt;
</pre>
<p>This worked most of the time in Flex 3.0, but fails very frequently in Flex 3.3. The right way to do it is:</p>
<pre class="brush: xml;">
&lt;mx:Panel id=&quot;foo&quot;
   visible=&quot;{model.canViewFoo}&quot;
   includeInLayout=&quot;{model.canViewFoo}&quot;&gt;
...
&lt;/mx:Panel&gt;
</pre>
<p>3) <strong>Be wary of swallowed exceptions</strong><br />
Exceptions thrown in binding expressions, or in functions called within binding expressions are <a href="http://blog.criticalpile.com/2008/07/18/alex-uhlmann-using-binding-securely/">silently captured</a> by the binding framework.</p>
<p>4) <strong>[Bindable("propertyChange")] is not the same as [Bindable]</strong><br />
Even though behind the scenes, the default event name is &#8220;propertyChange&#8221;, if you explicitly refer to it in your <code>[Bindable]</code> tag, the compiler assumes you will be generating the event yourself. If other properties in the same class are bindable, their updates will not trigger a binding update on your property too. Worse yet, if you try and use <code>dispatchEvent(new Event("propertyChange"))</code> in your setter, you will end up with type coercion errors as the binding framework expects events with the name &#8220;propertyChange&#8221; to actually be of type <code>PropertyChangeEvent</code>. If you actually dispatch a <code>PropertyChangeEvent</code> event, all will be well, however you might as well of just labelled the property <code>[Bindable]</code> in the first place and let the code generator handle the donkey work.</p>
<p>5) <strong>Take extra care when using interfaces in binding expression</strong><br />
If you refer to your bindable class via an interface in a binding expression, you need to be aware of the following limitations:</p>
<ol>
<li> If the <code>[Bindable]</code> event name in your interface is different from the <code>[Bindable]</code> event name in your class, binding events <em>will not</em> fire.
</li>
<li>If you have both a getter and setter for a property and no <code>[Bindable]</code> tag in your interface, binding events <em>will not</em> fire.</li>
<li>If you have only a getter for your property and no <code>[Bindable]</code> tag in your interface, binding events <em>will</em> fire. This is just a weird artifact and shouldn&#8217;t be relied upon in future.</li>
<li>Be extra extra careful with <a href="http://bugs.adobe.com/jira/browse/SDK-16307">nested interfaces</a>.</li>
</ol>
<p>If you wish to refer to your domain objects using interfaces in classes that use bindings, make sure the bindings metadata exactly matches. If you have multiple implements of an interface with different <code>[Bindable]</code> tags, don&#8217;t use the interface for binding expressions, as chances are, it won&#8217;t work. Instead, use <code>Object</code> and all your different binding implementations will work as expected.</p>
<p><strong>Debugging bindings</strong><br />
When bindings do go wrong, what&#8217;s the easiest way to debug them? You can view the <a href="http://blog.flexexamples.com/2008/08/02/viewing-a-flex-applications-generated-source-code/">generated source</a>, but don&#8217;t expect it to be especially enlightening. About the only useful thing you will glean from perusing the source, is to marvel at just how much of it there is.<br />
A more constructive way to debug is to use the undocumented <code>BindingManager</code> class. This shows you when each of your bindings fire. Add the following line to your Application&#8230;</p>
<pre class="brush: jscript;">
BindingDebugger.debugComponent(this);
</pre>
<p>&#8230;and include the following class&#8230;</p>
<pre class="brush: jscript;">
package
{
  import mx.binding.BindingManager;
  import mx.binding.IBindingClient;
  import mx.core.UIComponent;
  import mx.core.mx_internal;

  use namespace mx_internal;

  // Kudos to Cathal Golden for coming up with this technique
  public class BindingDebugger
  {

    private static const BINDINGS_PROPERTY : String =
      &quot;_bindingsByDestination&quot;;

    public static function debugComponent (
      displayObject : Object, recursive : Boolean = true) : void
    {
      if (displayObject is IBindingClient)
      {
        var bindings : Object = displayObject[ BINDINGS_PROPERTY ];
        for ( var binding : String in bindings )
        {
          BindingManager.debugBinding(binding);
        }
      }

      if (recursive &amp;&amp; displayObject is UIComponent)
      {
        var component : UIComponent = UIComponent( displayObject );
        for (var i : int = 0; i &lt; component.numChildren; i++)
        {
          debugComponent(component.getChildAt(i), true);
        }
      }
    }
  }
}
</pre>
<p>&#8230;and you should see all your binding expressions traced out to the console with output like this:</p>
<pre>
Binding: destString = bid.text, srcFunc result = Bid $15.31
Binding: destString = calcSpread.text, srcFunc result = Calc Spread $2.79
Binding: destString = ask.text, srcFunc result = Ask $18.12
</pre>
<p>Next post, I&#8217;ll look at ways to optimize data binding when dealing with low latency streaming data.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andybryant.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andybryant.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/andybryant.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/andybryant.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/andybryant.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/andybryant.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/andybryant.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/andybryant.wordpress.com/24/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/andybryant.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/andybryant.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=24&subd=andybryant&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://dodgybits.org/2009/04/12/flex-data-binding-pitfalls/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6e9e2e4e81e9644d14c460d45866b451?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybryant</media:title>
		</media:content>
	</item>
		<item>
		<title>Shuffle released on Android Market</title>
		<link>http://dodgybits.org/2009/04/11/shuffle-released-on-android-market/</link>
		<comments>http://dodgybits.org/2009/04/11/shuffle-released-on-android-market/#comments</comments>
		<pubDate>Sat, 11 Apr 2009 09:59:49 +0000</pubDate>
		<dc:creator>andybryant</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Shuffle]]></category>

		<guid isPermaLink="false">http://dodgybits.org/?p=7</guid>
		<description><![CDATA[
It&#8217;s been a long time coming, but I finally managed to get Shuffle out the door and into users hands. I started work in 2007 as an entry in the Android Developer Challenge mostly for the draw of the prize pool, but also as a chance to learn what looked like a great mobile OS. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=7&subd=andybryant&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/dodgy/3429748362/in/set-72157616592352788/"><img class="alignleft" style="border:5px solid white;" title="Shuffle" src="http://farm4.static.flickr.com/3354/3429748362_0f96e9f3db_m.jpg" alt="" width="162" height="240" /></a></p>
<p>It&#8217;s been a long time coming, but I <em>finally</em> managed to get <a title="Shuffle" href="http://code.google.com/p/android-shuffle/" target="_blank">Shuffle</a> out the door and into <a href="http://www.cyrket.com/package/org.dodgybits.android.shuffle">users hands</a>. I started work in 2007 as an entry in the Android Developer Challenge mostly for the draw of the prize pool, but also as a chance to learn what looked like a great mobile OS. After <a href="http://android-developers.blogspot.com/search/label/Android%20Developer%20Challenge">not winning</a> I didn&#8217;t touch the code for several months. I did feel validated in my design decisions however when a month after posting the original <a href="http://code.google.com/p/android-shuffle/wiki/OldScreenShots">screenshots</a> OmniGroup published it&#8217;s first glimpse of <a href="http://www.omnigroup.com/applications/omnifocus/iphone/">OmniFocus on iPhone</a>. Since they both follow the <a href="http://en.wikipedia.org/wiki/Getting_Things_Done">GTD mantra</a> fairly closely, this isn&#8217;t too surprising.</p>
<p>I started working on Shuffle again in earnest a couple of months ago when I secured an <a href="http://developer.android.com/guide/developing/device.html">Android Dev phone</a>. Using the app on a real device was a huge leap forward. I made a ton of changes based on my experience using it every day.</p>
<p>I plan on stepping back a little now, but I don&#8217;t plan on abandoning the project entirely. One current idea is to setup a Shuffle GWT website running on the promising <a href="http://code.google.com/appengine/docs/java/overview.html">Java Google App Engine</a>. I plan on kicking the App Engine tires soon, so should have a better idea then.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/andybryant.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/andybryant.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/andybryant.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/andybryant.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/andybryant.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/andybryant.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/andybryant.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/andybryant.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/andybryant.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/andybryant.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=dodgybits.org&blog=7151330&post=7&subd=andybryant&ref=&feed=1" />]]></content:encoded>
			<wfw:commentRss>http://dodgybits.org/2009/04/11/shuffle-released-on-android-market/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6e9e2e4e81e9644d14c460d45866b451?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">andybryant</media:title>
		</media:content>

		<media:content url="http://farm4.static.flickr.com/3354/3429748362_0f96e9f3db_m.jpg" medium="image">
			<media:title type="html">Shuffle</media:title>
		</media:content>
	</item>
	</channel>
</rss>