<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>I am Zef</title>
	
	<link>http://zef.me</link>
	<description>Technology, Me, You.</description>
	<lastBuildDate>Mon, 08 Mar 2010 20:08:51 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<atom:link rel="hub" href="http://zef.me/?pushpress=hub" />
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/zefme" /><feedburner:info uri="zefme" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Pubsubhub-frickin’-bub</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/hngM_5poijA/pubsubhub-frickin-bub</link>
		<comments>http://zef.me/2980/pubsubhub-frickin-bub#comments</comments>
		<pubDate>Mon, 08 Mar 2010 20:08:51 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[feed]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[pubsubhubbub]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2980</guid>
		<description><![CDATA[pubsubhubbub &#8212; I&#8217;m not kidding &#8212; is an actual existing thing. Yeah, I too would have killed to be a fly on the wall when they decided to call it that, but there you go. So let&#8217;s dissect this piece of art of a name:


pubsub, i.e. pub/sub, i.e. publish/subscribe, which is a common pattern in, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://code.google.com/p/pubsubhubbub/">pubsubhubbub</a> &#8212; I&#8217;m not kidding &#8212; is an actual existing thing. Yeah, I too would have killed to be a fly on the wall when they decided to call it that, but there you go. So let&#8217;s dissect this piece of art of a name:</p>

<ul>
<li><code>pubsub</code>, i.e. pub/sub, i.e. <a href="http://en.wikipedia.org/wiki/Publish/subscribe">publish/subscribe</a>, which is a common pattern in, well, the world, where multiple parties <em>subscribe</em> to one or more <em>publishers</em>, to receive notifications on updates.</li>
<li><code>hub</code>, is a center of communication, often used for efficiency purposes, like an <a href="http://en.wikipedia.org/wiki/Ethernet_hub">ethernet hub</a>.</li>
<li><code>bub</code>, you tell me. I haven&#8217;t a clue.</li>
</ul>

<p>So what is it, really? It&#8217;s a <em>protocol</em> to enable near real-time update notifications among pubsubhubbub-supporting parties. Whereas RSS and Atom feeds required polling to receive updates, pubsubhubbub pushes information to parties. Currently various Google properties are have pubsubhubbub-support, such as <a href="http://www.google.com/reader">Google Reader</a> and <a href="http://buzz.google.com">Google Buzz</a>. So, when you install a <a href="http://en.blog.wordpress.com/2010/03/03/rub-a-dub-dub-in-the-pubsubhubbub/">pubsubhubbub plug-in for a wordpress blog</a>, like I have and I push the publish button on a post, it will almost instantaneously appear in all of your Google Readers and your Google Buzz, whereas before, it may have taken a few minutes or hours to appear.</p>

<p>Want to learn more about the details? Check out these slides, or the <a href="http://code.google.com/p/pubsubhubbub/">website</a>:</p>

<iframe src="http://docs.google.com/present/embed?id=ajd8t6gk4mh2_34dvbpchfs&#038;size=m" frameborder="0" width="555" height="451"></iframe>
<img src="http://feeds.feedburner.com/~r/zefme/~4/hngM_5poijA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2980/pubsubhub-frickin-bub/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://zef.me/2980/pubsubhub-frickin-bub</feedburner:origLink></item>
		<item>
		<title>10 Things You Hadn’t Expected HTML/Javascript Would Do</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/RXLNBwTQ84Y/10-things-you-hadnt-expected-htmljavascript-could-do</link>
		<comments>http://zef.me/2950/10-things-you-hadnt-expected-htmljavascript-could-do#comments</comments>
		<pubDate>Thu, 04 Mar 2010 06:39:14 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2950</guid>
		<description><![CDATA[About 14-15 years ago my uncle took me to the university at which he was studying at the time. He had something to show me. He sat me behind a computer in the computer room and started a program called &#8220;Netscape&#8221;. He typed in an internet address ending with .au. I saw my first website [...]]]></description>
			<content:encoded><![CDATA[<p>About 14-15 years ago my uncle took me to the university at which he was studying at the time. He had something to show me. He sat me behind a computer in the computer room and started a program called &#8220;Netscape&#8221;. He typed in an internet address ending with <code>.au</code>. I saw my first website and it came all the way from the other side of the world. It looked like crap, loaded incredibly slow, but it was <em>cool</em>.</p>

<p>I could have never have guessed that HTTP, HTML, CSS and Javascript would once not become the main way to access information, but also replace a lot of desktop applications. The abilities of the new <a href="http://dev.w3.org/html5/spec/Overview.html">HTML5</a> and other web technologies like <a href="http://www.w3.org/Graphics/SVG/">SVG</a> never cease to amaze me.</p>

<p>Here are 10 things I had not expected these open web technologies would be able to, but can in 2010:</p>

<ol>
<li><a href="http://www.andrew-hoyer.com/experiments/cloth">Interactively render physics of a cloth</a>
<img src="http://zef.me/wp-content/uploads/2010/03/cloth.png" alt="" title="cloth" width="150" height="150" class="alignnone size-full wp-image-2959" /></li>
<li><a href="http://htmlfive.appspot.com/static/tracker1.html">Live motion tracking</a>
<img src="http://zef.me/wp-content/uploads/2010/03/motion-tracking.png" alt="" title="motion-tracking" width="180" height="125" class="alignnone size-full wp-image-2960" /></li>
<li><a href="http://www.youtube.com/html5">Play YouTube videos without Flash</a>
<img src="http://zef.me/wp-content/uploads/2010/03/youtube.png" alt="" title="youtube" width="283" height="215" class="alignnone size-full wp-image-2961" /></li>
<li><a href="https://bespin.mozillalabs.com/">Collaboratively edit source code in a browser IDE</a>
<img src="http://zef.me/wp-content/uploads/2010/03/bespin.png" alt="" title="bespin" width="336" height="184" class="alignnone size-full wp-image-2963" /></li>
<li><a href="http://9elements.com/io/projects/html5/canvas/">Do weird interactive stuff like this</a>
<img src="http://zef.me/wp-content/uploads/2010/03/weird.png" alt="" title="weird" width="306" height="237" class="alignnone size-full wp-image-2964" /></li>
<li><a href="http://sebleedelisle.com/demos/html5landscape.html">Animate simple 3D landscapes</a>
<img src="http://zef.me/wp-content/uploads/2010/03/landscapes.png" alt="" title="landscapes" width="315" height="265" class="alignnone size-full wp-image-2969" /></li>
<li><a href="http://m.ibisreader.com/">Read books in a mobile browser</a>, <em>while disconnected from the internet</em>
<img src="http://zef.me/wp-content/uploads/2010/03/ebook-e1267653528515.png" alt="" title="ebook" width="150" height="180" class="alignnone size-full wp-image-2956" /></li>
<li><a href="http://devfiles.myopera.com/articles/650/step_4_enemies.htm">Play Wolfenstein 3D</a>
<img src="http://zef.me/wp-content/uploads/2010/03/wolfenstein.png" alt="" title="wolfenstein" width="325" height="207" class="alignnone size-full wp-image-2965" /></li>
<li><a href="http://www.nihilogic.dk/labs/mariokart/">Play MarioKart</a>
<img src="http://zef.me/wp-content/uploads/2010/03/mariokart.png" alt="" title="mariokart" width="322" height="139" class="alignnone size-full wp-image-2966" /></li>
<li><a href="http://paulirish.com/work/gordon/demos/">Render flash files using Javascript/SVG</a>
<img src="http://zef.me/wp-content/uploads/2010/03/flash.png" alt="" title="flash" width="324" height="265" class="alignnone size-full wp-image-2967" /></li>
</ol>
<img src="http://feeds.feedburner.com/~r/zefme/~4/RXLNBwTQ84Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2950/10-things-you-hadnt-expected-htmljavascript-could-do/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://zef.me/2950/10-things-you-hadnt-expected-htmljavascript-could-do</feedburner:origLink></item>
		<item>
		<title>Javascript: OOP Style Performance</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/LcfjiOr2AkM/javascript-oop-style-performance</link>
		<comments>http://zef.me/2913/javascript-oop-style-performance#comments</comments>
		<pubDate>Tue, 02 Mar 2010 10:51:08 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2913</guid>
		<description><![CDATA[I have been watching parts of Douglas Crockford&#8217;s talks on the history and future of Javascript. In his third talk Douglas talks about functions. If you are somewhat familiar with Javascript you know that functions are, somewhat oddly, used to create new objects. The original &#8220;intended&#8221; way (which Douglas calls the pseudo-classical way) of doing [...]]]></description>
			<content:encoded><![CDATA[<p>I have been watching parts of <a href="http://yuiblog.com/crockford/">Douglas Crockford&#8217;s talks on the history and future of Javascript</a>. In his third talk Douglas talks about functions. If you are somewhat familiar with Javascript you know that functions are, somewhat oddly, used to create new objects. The original &#8220;intended&#8221; way (which Douglas calls the <em>pseudo-classical</em> way) of doing this is as follows:</p>

<pre><code>function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype.getNameAndAge = function() {
  return "Name: " + this.name + " and age: " + this.age;
};

var p = new Person("Zef Hemel", 26);
console.log(p.getNameAndAge());
</code></pre>

<p>What we do here is define a constructor function <code>Person</code>, which starts with a capital P, to indicate that it should be used in conjunction with the <code>new</code> operator, as demonstrated in the second last line. The second statement adds a method to the <code>Person</code> prototype, which in practice makes that method available to all <code>Person</code> objects (including ones already created). The last two statements instantiate a <code>Person</code> object and calls the <code>getNameAndAge</code> method.</p>

<p>Using this mechanism you can also implement inheritance. Let&#8217;s introduce a <code>LivingBeing</code> &#8220;super class&#8221;, which has an <code>age</code> property:</p>

<pre><code>function LivingBeing(age) {
  this.age = age;
}

LivingBeing.prototype.getAge = function() {
  return this.age;
};
</code></pre>

<p>Alright, now we&#8217;ll define the <code>Person</code> contructor again, but assign a new instance of <code>LivingBeing</code> to its prototype, which will add all fields and methods available in <code>LivingBeing</code> to all <code>Person</code> objects (again, including existing ones). Then, we add an additional method to <code>Person</code> objects: <code>getNameAndAge</code>:</p>

<pre><code>function Person(name, age) {
  this.name = name;
  this.age = age;
}

Person.prototype = new LivingBeing();

Person.prototype.getNameAndAge = function() {
  return "Name: " + this.name + " and age: "
         + this.getAge();
};

var p = new Person("Zef Hemel", 26);
console.log(p.getNameAndAge());
</code></pre>

<p>For more information on how inheritance and prototypes work, read <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Details_of_the_Object_Model">this excellent page in the Mozilla documentation</a>.</p>

<p>Now, Crockford suggests that there is a nicer, cleaner and more natural way to do object-oriented programming and inheritance in Javascript, which he calls <em>functional inheritance</em>. The functional-inheritance style version of the above program looks as follows:</p>

<pre><code>function livingBeing(age) {
  return {
    getAge: function() {
      return age;
    }
  };
}

function person(name, age) {
  var that = livingBeing(age);
  that.getNameAndAge = function() {
    return "Name: " + name + " and age: " + that.getAge();
  };
  return that;
}

var p = person("Zef Hemel", 26);
console.log(p.getNameAndAge());
</code></pre>

<p>Note that the invocation style of the constructors changed here too, no <code>new</code> keyword should be used. I agree that this is a nice style, although it makes extending existing objects with additional methods/fields hard, but one could argue this is a bad idea anyway. Although clean, it also seems more expensive to execute, because you&#8217;re basically composing an object from scratch every time &#8212; you start out with an empty object and that push in all its methods and fields &#8212; while with the pseudo-classical approach you create one prototype object with all the methods, and then simply point to that object. Theoretically <em>calling</em> a method would then be more expensive, because at invocation-time the prototype hierarchy has to be traversed. But maybe Javascript engines have a clever solution to all of this and in practice it doesn&#8217;t matter. I decided to investigate.</p>

<p>I benchmarked two things:</p>

<ol>
<li>The performance of object creation, by creating 10x 1,000,000 objects</li>
<li>The performance of method calling on a single object, by invoking a method 10x 1,000,000 times</li>
</ol>

<p>I did each 10 times, so that I can take an average time on each. I executed this benchmark on four browsers running on my Mac (Macbook Pro):</p>

<ul>
<li>Firefox 3.5</li>
<li>Chrome 5 (dev)</li>
<li>Safari 4</li>
<li>Opera 10.50b</li>
</ul>

<p><strong>Disclaimer 1:</strong> The reason I executed these on these four browsers is not to compare their performance, <em>this is not a good way to compare browser performance</em>, but mainly to check that the results in different browsers do not diverge too much.</p>

<p><strong>Disclaimer 2:</strong> What I&#8217;m testing is not representative for real programs. If one approach is going to be twice as fast as the other, this does not imply that your programs are going to be twice as fast, it means that <em>object creation</em> is twice as fast, or method invocation is twice as fast. Whether that matters to you depends on the amount of objects you create or methods you call.</p>

<h2>Benchmark 1: Object creation</h2>

<p>This benchmark creates 1,000,000 objects. First using the pseudo-classical style and then through the functional style. The <a href="http://gist.github.com/318662">code to this benchmark can be found here</a>. The times reported are in milliseconds for 1,000,000 objects being created. As mentioned, every test is performed 10 times of which I took the average:</p>

<p><strong>Update:</strong> The previous version of the benchmark script contained a major flaw that increased the execution time of the functional style considerably. This has now been adjusted in the graph. Thanks Adrian for noticing this.</p>

<p><img src="http://zef.me/wp-content/uploads/2010/03/small-object-creation-revised.png" alt="" title="small-object-creation-revised" width="515" height="434" class="alignnone size-full wp-image-2947" /></p>

<p>This chart clearly shows that creating objects using the pseudo-classical style is cheaper in all browsers. This varies from about 35% cheaper (Chrome) up around three times as cheap (Firefox). If you create huge amounts of objects in your code, you may want to take this into consideration.</p>

<h2>Benchmark 2: Method invocation</h2>

<p>This benchmark creates one object and then invokes the same method on it 1,000,000 times. First using the pseudo-classical style and then through the functional style. The <a href="http://gist.github.com/318662">code to this benchmark can be found here</a>. The results are as follows:</p>

<p><img src="http://zef.me/wp-content/uploads/2010/03/method-invocation.png" alt="" title="method-invocation" width="472" height="286" class="alignnone size-full wp-image-2933" /></p>

<p>I would have expected that method invocation would have been cheaper in the functional style of object creation, but it turns out it&#8217;s not. The differences here are almost negligible, so I&#8217;d say that in practice it doesn&#8217;t really matter what style you choose if your application is heavy on method calls.</p>

<p>Still, I felt that the functional style must be cheaper especially if you use inheritance. So I <a href="http://gist.github.com/319415">adapted my benchmark script</a> to introduce a level of inheritance (like the <code>LivingBeing</code> &#8220;super class&#8221;). However, method calls using the pseudo-classical style are still cheaper, although less so. Perhaps, if you use 4+ levels in your object hierarchy, the functional style method calls may start to become cheaper (although I expect <em>creating</em> those objects will be much more expensive).</p>

<p><img src="http://zef.me/wp-content/uploads/2010/03/method-invocation-inheritance.png" alt="" title="method-invocation-inheritance" width="473" height="287" class="alignnone size-full wp-image-2937" /></p>

<p>It seems that method invocation on objects created using the functional style are roughly as expensive as using the pseudo-classical style.</p>

<h2>Conclusion</h2>

<p>There are two properties to take into account when deciding what object-creation style you&#8217;re going to use in your code.</p>

<ol>
<li>Which style produces clearer code? This depends on the taste of both on the developers of the code, but if you&#8217;re developing a library for others, possibly also on the expectations of your audience. Scanning through some Javascript libraries it seems the pseudo-classical approach is much more popular. Consequently, your audience is likely going to expect and be more comfortable with this approach. That&#8217;s something to take into account.</li>
<li>Is the code CPU/memory intensive, does it create lots of objects? If so, the pseudo-classical approach is superior.</li>
</ol>
<img src="http://feeds.feedburner.com/~r/zefme/~4/LcfjiOr2AkM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2913/javascript-oop-style-performance/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://zef.me/2913/javascript-oop-style-performance</feedburner:origLink></item>
		<item>
		<title>Markdown in Wordpress</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/DatFyG3th_M/markdown-in-wordpress</link>
		<comments>http://zef.me/2902/markdown-in-wordpress#comments</comments>
		<pubDate>Sat, 27 Feb 2010 12:08:42 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[markdown]]></category>
		<category><![CDATA[meta]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2902</guid>
		<description><![CDATA[Alright, after using various WYSIWYG editors in WordPress (which I use to to write this blog), I got fed up and decided to switch to Markdown. There are a couple of plug-ins to make this happen, in fact I&#8217;m using three, together they make using Markdown pretty nice in wordpress.


&#8220;Markdown for WordPress and bbPress&#8221;, this [...]]]></description>
			<content:encoded><![CDATA[<p>Alright, after using various WYSIWYG editors in <a href="http://www.wordpress.org">WordPress</a> (which I use to to write this blog), I got fed up and decided to switch to <a href="http://daringfireball.net/projects/markdown/">Markdown</a>. There are a couple of plug-ins to make this happen, in fact I&#8217;m using three, together they make using Markdown pretty nice in wordpress.</p>

<ul>
<li>&#8220;Markdown for WordPress and bbPress&#8221;, this plug-in (just search for it through the wordpress plugin manager) contains the <a href="http://michelf.com/projects/php-markdown/">PHP Markdown</a> parser, which supports the whole of Markdown, plus a few <a href="http://michelf.com/projects/php-markdown/extra/">extras</a> such as footnotes<sup id="fnref:1"><a href="#fn:1" rel="footnote">1</a></sup>. It parses every post as Markdown, including the old ones, which wasn&#8217;t a problem for me because the HTML of previous posts is also Markdown and seems to look OK.</li>
<li>&#8220;WP MarkItUp&#8221;, this plug-in contains a reasonable editor for editing Markdown, it doesn&#8217;t do much, but has some buttons for common Markdown markup (hahaha), such as headings, <strong>bold</strong>, <em>italic</em> and so on. The plugin is based on <a href="http://markitup.jaysalvat.com/home/">MarkItUp</a>.</li>
<li><a href="http://softwaremaniacs.org/soft/highlight/en/">&#8220;highlight.js&#8221;</a>, is a pure-javascript syntax highlighter that automatically detects the language of code blocks, which is exactly what you need in Markdown, because there&#8217;s no way to mark a code block with a language name. You cannot install this plugin through the plugin manager, as far as I&#8217;m aware, so you have to download it and install it yourself (see the README of the download). Example of syntax highlighting (of Javascript):</li>
</ul>

<pre><code>for(var i = 0; i &lt; ar.length; i++) {
  console.log(i);
}
</code></pre>

<p>Now let&#8217;s see how this works in practice.</p>

<div class="footnotes">
<hr />
<ol>

<li id="fn:1">
<p>Which look like this, in case you were wondering.&#160;<a href="#fnref:1" rev="footnote">&#8617;</a></p>
</li>

</ol>
</div>
<img src="http://feeds.feedburner.com/~r/zefme/~4/DatFyG3th_M" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2902/markdown-in-wordpress/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://zef.me/2902/markdown-in-wordpress</feedburner:origLink></item>
		<item>
		<title>Waddup Buzz?</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/f7OkG1jxJHU/waddup-buzz</link>
		<comments>http://zef.me/2878/waddup-buzz#comments</comments>
		<pubDate>Fri, 26 Feb 2010 10:11:49 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[buzz]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2878</guid>
		<description><![CDATA[Google seems to be working hard at Buzz. Increasingly it seems to group buzz updates together, like so:



On twitter we long had this problem with the same links and retweets showing up in our streams every so often. It would have been nice if those had&#160;automatically been grouped together like in the Buzz timeline, but [...]]]></description>
			<content:encoded><![CDATA[<p>Google seems to be working hard at <a href="http://buzz.google.com">Buzz</a>. Increasingly it seems to group buzz updates together, like so:</p>

<p><img alt="" title="buzz-grouping" width="500" height="105" class="alignnone size-full wp-image-2879" src="http://zef.me/wp-content/uploads/2010/02/buzz-grouping-e1267178008733.png" /></p>

<p>On twitter we long had this problem with the same links and retweets showing up in our streams every so often. It would have been nice if those had&nbsp;automatically been grouped together like in the Buzz timeline, but they weren&#8217;t. Twitter fixed this problem by implementing native retweet functionality, which sort of solves the issue. So, the question is: why did Buzz group these particular updates together? To Let&#8217;s step into the algorithmic brain of the Google and try to figure this out. Let&#8217;s ungroup the updates:</p>

<p><img alt="" title="buzz-ungrouping" width="500" height="287" class="alignnone size-full wp-image-2880" src="http://zef.me/wp-content/uploads/2010/02/buzz-ungrouping-e1267178064635.png" /></p>

<p>Those with eye to detail will notice the number of updates here. How many were there when they were grouped? 1, 2, 3, 4, 5. Right? And when expanded? 1, 2, 3, 4&#8230; huh?</p>

<p>Anyway.</p>

<p>Let&#8217;s see if we can discover the reason behind the grouping. Is it content-based aggregation? Probably not, unless Google aggregates programming related content here, which I doubt. Did it summarize the four updates into one? Not at all, the javascript framework update has absolutely nothing to do with the other updates. So what is it then, that made Google feel the other updates were somehow less important than the Javascript one? And why would this be useful to me? The only answer I can come up with is that they were all posted by me around the same time. Except they&#8217;re really not posted all at 10:47am, they were posted in the course of about an hour, but Google only polls twitter every few hours or so (it seems). Is time-based aggregation really a useful thing, though?</p>

<p>Google, I think, or at least hope, you can do better than this.</p>

<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/f7OkG1jxJHU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2878/waddup-buzz/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://zef.me/2878/waddup-buzz</feedburner:origLink></item>
		<item>
		<title>An Intro to Distributed Version Control</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/ST9lbM0e4UE/an-intro-to-distributed-version-control</link>
		<comments>http://zef.me/2871/an-intro-to-distributed-version-control#comments</comments>
		<pubDate>Wed, 24 Feb 2010 20:37:09 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[mercurial]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2871</guid>
		<description><![CDATA[There are a multitude of reasons why distributed version control systems (like Mercurial and Git) are potentially preferable to centralized systems such as CVS and Subversion. One is that branching is cheaper and merging works much better. I only have anecdotal evidence of this. Frankly, I use Git only for personal projects&#160;(in the sense that [...]]]></description>
			<content:encoded><![CDATA[<p><img title="joelspolsky" width="140" height="196" class="alignnone size-full wp-image-2875" align="right" alt="" src="http://zef.me/wp-content/uploads/2010/02/joelspolsky-e1267043797618.jpg" />There are a multitude of reasons why distributed version control systems (like <a href="http://mercurial.selenic.com/">Mercurial</a> and <a href="http://git-scm.com/">Git</a>) are potentially preferable to centralized systems such as CVS and <a href="http://subversion.tigris.org/">Subversion</a>. One is that branching is cheaper and merging works much better. I only have anecdotal evidence of this. Frankly, I use Git only for <a href="http://github.com/zefhemel">personal projects</a>&nbsp;(in the sense that I&#8217;m the only one working on them). For WebDSL (which I work on with a couple of other people) we use subversion and there we hardly ever branch, because &quot;merging works so badly&quot;. Which, I suppose is true, but I&#8217;m hardly a subversion expert.</p>

<p>Quite out of the blue, Joel Spolsky (of <a href="http://www.joelonsoftware.com">Joel on Software</a> and <a href="http://www.stackoverflow.com">StackOverflow</a> fame) has <a href="http://hginit.com">published a Mercurial tutorial online</a>. And even if you don&#8217;t give a rat&#8217;s ass about Mercurial, I suggest you do read at least the first &quot;chapter&quot;: <a href="http://hginit.com/00.html">Subversion re-education</a>, which points out the differences between the subversion and mercurial/git mindset:</p>

<p>&nbsp;</p>

<blockquote>
<p>Want to know something funny? Almost every Subversion team I&rsquo;ve spoken to has told me some variation on the very same story. This story is so common I should just name it &ldquo;Subversion Story #1.&rdquo; The story is this: at some point, they tried to branch their code, usually so that the shipping version which they gave their customers can be branched off separately from the version that the developers are playing with. And every team has told me that when they tried this, it worked fine, until they had to merge, and then it was a nightmare. What should have been a five minute process ended up with six programmers around a single computer working for two weeks trying to manually reapply every single bug fix from the stable build back into the development build.</p>
<p>And almost every Subversion team told me that they vowed &ldquo;never again,&rdquo; and they swore off branches. And now what they do is this: each new feature is in a big #ifdef block. So they can work in one single trunk, while customers never see the new code until it&rsquo;s debugged, and frankly, that&rsquo;s ridiculous.</p>
<p>Keeping stable and dev code separate is precisely what source code control is supposed to let you do.</p>
</blockquote>

<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/ST9lbM0e4UE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2871/an-intro-to-distributed-version-control/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://zef.me/2871/an-intro-to-distributed-version-control</feedburner:origLink></item>
		<item>
		<title>Javascript: A Language in Search of a Standard Library and Module System</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/cOeSWFYV-gA/javascript-a-language-in-search-of-a-standard-library-and-module-system</link>
		<comments>http://zef.me/2856/javascript-a-language-in-search-of-a-standard-library-and-module-system#comments</comments>
		<pubDate>Wed, 24 Feb 2010 10:01:10 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2856</guid>
		<description><![CDATA[
    Array
    Boolean
    Date
    Error
    EvalError
    Function
    Math
    Number
    Object
    RangeError
    ReferenceError
    RegExp
    String
   [...]]]></description>
			<content:encoded><![CDATA[<ol>
    <li>Array</li>
    <li>Boolean</li>
    <li>Date</li>
    <li>Error</li>
    <li>EvalError</li>
    <li>Function</li>
    <li>Math</li>
    <li>Number</li>
    <li>Object</li>
    <li>RangeError</li>
    <li>ReferenceError</li>
    <li>RegExp</li>
    <li>String</li>
    <li>SyntaxError</li>
    <li>TypeError</li>
    <li>URIError</li>
</ol>

<p>Recognize that? Yes indeed, it&#8217;s the complete list of <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference">standard Javascript objects</a>&nbsp;of Javascript 1.5. 16 objects, of which 7 are error objects. Of course, this is just the Javascript language by itself. In practice Javascript executes inside a browser, which gives it access to additional objects like the DOM, and all kinds of fancy HTML5 and non-standard browser-specific features.</p>

<p>When Javascript was just a little language that people would use to do simple mouse-over events, this was not a problem. However, now, more and more applications are written in Javascript in the browser and Javascript is used in <a href="http://www.mongodb.org">more</a> and <a href="http://couchdb.apache.org/">more</a> <a href="http://nodejs.org/">places</a> other than the browser. Better yet I dare to bet you that in a few years time Javascript is going to be one of the most used programming languages in a growing number of domains. The growing body of Javascript code also means Javascript needs more than just those 16 objects. It needs a larger standard API and it needs a standardized way to modularize code.</p>

<p>At the very least it needs a de-facto standard way of doing object-oriented programming, having the choice between <a href="http://javascript.crockford.com/inheritance.html">classical</a>, <a href="http://javascript.crockford.com/prototypal.html">prototypal</a>, or, sure, why not <a href="http://ajaxpatterns.org/Lazy_Inheritance">lazy inheritance</a> is not doing it for me. Different libraries use different styles. Worse yet, different libraries develop their <a href="http://api.prototypejs.org/language/class.html">own utility objects to produce classes</a>, and if they&#8217;d at least agree on a common way of doing that, but no, there are a few dozen different way of implementing exactly the kind of inheritance you like. I&#8217;m not the biggest fan of Java, but at least they made a decision on this at the language level.</p>

<p>But I&#8217;m getting side tracked. The main two things Javascript needs to be a proper language that we can apply &quot;grown-up&quot; software engineering principles to:</p>

<ol>
    <li>A standard library</li>
    <li>A module system</li>
</ol>

<p>First, the standard library. Those 16 objects are no longer sufficient. So, what happens is that programmers step in to build a larger, more extensive library of objects. It would be great if they all teamed up to come with the one framework that everybody uses, but of course they didn&#8217;t, so we now have <a href="http://www.prototypejs.org">Prototype</a>, <a href="http://mootools.net/">MooTools</a>, <a href="http://jquery.com">jQuery</a>, <a href="http://mochikit.com/">MochiKit</a>, <a href="http://www.extjs.com/">ExtJS</a>, <a href="http://developer.yahoo.com/yui/index.html">YUI</a>, <a href="http://code.google.com/closure/library/">Google Closure</a>, and I&#8217;m probably forgetting about a dozen. This divides the Javascript world into different camps. Either you&#8217;re a jQuery guy or a Prototype guy, a ExtJS guy or a MochKit guy. There&#8217;s a YUI-y way of doing things and a Prototype way of doing things. There&#8217;s a <a href="http://marcgrabanski.com/pages/code/jquery-ui-datepicker">jQuery calendar</a>, an <a href="http://www.extjs.com/learn/Extension:Calendar">ExtJS calendar</a>, and a <a href="http://scal.fieldguidetoprogrammers.com/">Prototype calendar</a>. Of course, once you picked a framework you stick to it, because if I want to use a prototype calendar from my jQuery application, I have to pull in <em>x</em> kilobytes of additional code that essentially duplicates jQuery functionality. A lot of effort is wasted because of this.</p>

<p>What Javascript&#8217;s standard library should contain is pretty tough thing to determine. First thing that comes to mind is a set of standard data structures. Of course Javascript has arrays and objects. Objects are typically also used as maps (although the keys can only be strings, and not even all strings) and sometimes even as set (where the property names represent values).</p>

<p>A better library of data structures is required, including a proper map and set implementation.&nbsp;Additionally, APIs for other common tasks such as:</p>

<ul>
    <li>JSON parsing and serialization</li>
    <li>Testing</li>
    <li>Cryptography</li>
    <li>Date handling</li>
    <li>DOM querying (I think most libraries agree that CSS selectors are a good way, right?)</li>
</ul>

<p>Some stuff like DOM traversals, querying and widgets will be hard to agree on probably, but would be nice to have.</p>

<p>Because Javascript is increasingly being used as a non-browser language, for instance on servers, it will also need non-browser stuff like IO, inter-process communication, sockets etc. The <a href="http://wiki.commonjs.org/wiki/CommonJS">CommonJS</a> initiative is working on these. CommonJS is an initiative, mostly among Javascript server vendors, to agree upon certain standard interfaces to, e.g. IO, threads, sockets etc. Its main contribution to date, however, is <a href="http://wiki.commonjs.org/wiki/Modules/1.1">its module system</a>.</p>

<p>Javascript does not have namespaces, but you can use objects for this purpose. That&#8217;s fine. In the past, some frameworks have built their own module system around this. Dojo and Google Closure offer a remarkably similar API to export and load modules:</p>

<p><code>dojo.require('dijit.widget.Editor');<br />
dojo.require('myproj.Something');<br />
dojo.provide('myproj.MyObj');<br />
<br />
myproj.MyObj = function() { };<br />
myproj.MyObj.prototype.initialize = function() { ... };</code></p>

<p>Replace &#8216;dojo&#8217; by &#8216;goog&#8217; and you basically have the Google Closure version. Quite nice and reasonably clean. However, there&#8217;s also <a href="http://openjsan.org/doc/c/cw/cwest/JSAN/0.10/lib/JSAN.html">JSAN&#8217;s module system</a>. CommonJS&#8217;s module system is really nice, however according to some reports&nbsp;<a href="http://tagneto.blogspot.com/2009/11/javascript-module-loading-browser-and.html">cannot be implemented in the browser properly</a>. There&#8217;s an <a href="http://github.com/jrburke/requirejs">asynchronous version of the CommonJS module system called RequireJS,</a> but, well, it&#8217;s not the CommonJS standard. There&#8217;s a <a href="http://wiki.commonjs.org/wiki/Modules/Transport/C">proposal to standardize the RequireJS system as part of CommonJS</a>, but it&#8217;s not entirely clear what the status is of that proposal.</p>

<p>I feel these issues have to be resolved and the good thing is that it does not require any changes in the Javascript language itself, nor its browser support. If the different framework vendors would just agree on a single base library that they all use, because, let&#8217;s face it, everybody needs a function to trim strings and a proper set implementation, a clean way of doing inheritance, plus a module system to go with that, be it dojo/Google&#8217;s system or a CommonJS variant, I don&#8217;t care.</p>

<p>It would be oh-so-nice to have a de-facto standard library for this stuff.</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/cOeSWFYV-gA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2856/javascript-a-language-in-search-of-a-standard-library-and-module-system/feed</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://zef.me/2856/javascript-a-language-in-search-of-a-standard-library-and-module-system</feedburner:origLink></item>
		<item>
		<title>Javascript: The Scope Pitfall</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/zBpj_H0i-CE/javascript-the-scope-pitfall</link>
		<comments>http://zef.me/2843/javascript-the-scope-pitfall#comments</comments>
		<pubDate>Tue, 16 Feb 2010 13:13:33 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2843</guid>
		<description><![CDATA[For the past few weeks I&#8217;ve been programming almost exclusively in Javascript. And to be quite honest it&#8217;s not as bad as you may think. In fact, Javascript is quite a nice language, as long as you are aware of its quirks. One quirk that bit me in the ass a few times already is [...]]]></description>
			<content:encoded><![CDATA[<p>For the past few weeks I&#8217;ve been programming almost exclusively in Javascript. And to be quite honest it&#8217;s not as bad as you may think. In fact, Javascript is quite a nice language, as long as you are aware of its quirks. One quirk that bit me in the ass a few times already is its lack of block scopes. To make the problem clear, let&#8217;s look at a code fragment:</p>

<p><strong><code>var</code></strong><code> elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];<br />
<strong>for</strong>(<strong>var</strong> i = 0; i &lt; elements.length; i++) {<br />
&nbsp;&nbsp;<strong>var</strong> el = elements[i];<br />
&nbsp;&nbsp;console.log(el);<br />
}</code></p>

<p>What does this code fragment print? Of course, it prints each of the elements in the array, so first 0, 1, 2, 3 etc. Easy enough. Now let&#8217;s adapt that a little bit:</p>

<p><strong><code>var</code></strong><code> elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];<br />
<strong>var</strong> fns = [];<br />
<br />
<strong>for</strong>(<strong>var</strong> i = 0; i &lt; elements.length; i++) {<br />
&nbsp;&nbsp;<strong>var</strong> el = elements[i];<br />
&nbsp;&nbsp;fns.push(<strong>function</strong>() {<br />
&nbsp;&nbsp; &nbsp; &nbsp;console.log(el);<br />
&nbsp;&nbsp; &nbsp;});<br />
}<br />
fns[2]();</code></p>

<p>This code fragment uses a powerful feature of Javascript: first order functions. Functions are values that can be put in a variable, including arrays as this code demonstrates. In this fragment, the for-loop builds up an array called <code>fns</code>&nbsp;with functions that print an element of the list. Later on we can then pick one of the functions from that array and invoke it. The last line demonstrates this, it executes the 3rd function in the array. So what will that print?</p>

<p>If you&#8217;re a C/Java/C# programmer you&#8217;ll probably be guessing that it would print 2. In every iteration a variable <code>el</code> is declared that contains the current element from the array. The function that is generated on the fly contains a reference to <code>el</code> and will therefore be part of its <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">closure</a>. Logically, this means that in the first function captures the value 0 for <code>el</code>, the second function value 1 etc. Sadly, this is not the case. Javascript only has function scopes, not block scopes (for constructs like the for-loop). In effect, what you&#8217;re actually executing here is the following:</p>

<p><strong><code>var</code></strong><code> elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];<br />
<strong>var</strong> fns = [];<br />
<strong>var</strong> el;<br />
<strong>for</strong>(<strong>var</strong> i = 0; i &lt; elements.length; i++) {<br />
&nbsp;&nbsp;el = elements[i];<br />
&nbsp;&nbsp;fns.push(<strong>function</strong>() {<br />
&nbsp;&nbsp; &nbsp; &nbsp;console.log(el);<br />
&nbsp;&nbsp; &nbsp;});<br />
}<br />
fns[2]();</code></p>

<p>Alright, fine. Why is that a problem?&nbsp;You have to realize that the closure of the generated functions contain pointers to variables, not a snapshot of the values at the point of definition, meaning that if variables change, these changes are visible from within the function. This is a very powerful feature, but also a potentially very confusing one. Since there is only one variable <code>el</code>, to which a new value is assigned every iteration, and each function points to this same variable, every function in the array will produce the same value: 9 (the last value assigned to <code>el</code> in the for-loop).</p>

<p>If you have problems getting your head around that, don&#8217;t feel bad, it took me a while too.</p>

<p>So, how can we fix this? Well, we can artificially introduce scopes by creating new functions and immediately invoking them:&nbsp;</p>

<p><strong><code>var</code></strong><code> elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];<br />
<strong>var</strong> fns = [];<br />
<br />
<strong>for</strong>(<strong>var</strong> i = 0; i &lt; elements.length; i++) {<br />
&nbsp;&nbsp;(<strong>function</strong>() {<br />
&nbsp;&nbsp; &nbsp;<strong>var</strong> el = elements[i];<br />
&nbsp;&nbsp; &nbsp;fns.push(<strong>function</strong>() {<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;console.log(el);<br />
&nbsp;&nbsp; &nbsp; &nbsp;});<br />
&nbsp;&nbsp;}());<br />
}<br />
<br />
fns[2]();</code></p>

<div>So what&#8217;s new here is the <code>(<strong>function</strong>() { </code>bit and the <code>}());</code> at the end. What this simple trick does is define an anonymous function and immediately invoke it. What&#8217;s different than before is that a new scope is used for each iteration of the for loop, containing a fresh variable <code>el.&nbsp;</code>The functions that are generated now each refer to a different <code>el</code>. Thus, the <code>fn[2]()</code> call will now produce 2, as you would expect.</div>
<img src="http://feeds.feedburner.com/~r/zefme/~4/zBpj_H0i-CE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2843/javascript-the-scope-pitfall/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://zef.me/2843/javascript-the-scope-pitfall</feedburner:origLink></item>
		<item>
		<title>On Buzz</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/hSBUrNuBE5A/on-buzz</link>
		<comments>http://zef.me/2838/on-buzz#comments</comments>
		<pubDate>Mon, 15 Feb 2010 15:42:10 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[buzz]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2838</guid>
		<description><![CDATA[I&#8217;m not sure what to think about Google Buzz. On one hand it&#8217;s yet another place to post stuff (links, pictures, thoughts etc.), on the other hand it is quite a bit richer than Twitter, which I currently use for this purpose. Sure, it doesn&#8217;t have what&#8217;s one of twitter&#8217;s strengths I think: the 140 [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m not sure what to think about <a href="http://buzz.google.com">Google Buzz</a>. On one hand it&#8217;s yet another place to post stuff (links, pictures, thoughts etc.), on the other hand it is quite a bit richer than Twitter, which I currently use for this purpose. Sure, it doesn&#8217;t have what&#8217;s one of twitter&#8217;s strengths I think: the 140 character limit, but it does have other stuff like a photo upload, location, a commenting system, the ability to &quot;like&quot; stuff, which provides the system with valuable information that can be used to filter, or at least prioritize future buzzes (or whatever they&#8217;re called).</p>

<p>Incidentally, if you&#8217;re not already <a href="http://www.google.com/profiles/zefhemel">following me on Buzz, do so now</a>!</p>

<p>What Buzz is definitely not good for right now is following popular people; people that get loads of comments on every buzz, meaning these buzzes jump to the top all the time. But I&#8217;m sure that will be fixed.</p>

<p>Buzz is likely to go a bit more mainstream than Twitter, which will mean that my wife, mom and dad are likely to start using at some point. Should they really be following me though. I&#8217;m likely to push out stuff that they really do not care about (like work related things). Currently this is why I use both facebook and twitter. Facebook is for personal things. Twitter for work/hobby. What should I use Buzz for, if anything? Time will tell.</p>

<p>Anyway, my point is: <a href="http://www.google.com/profiles/zefhemel">follow me on buzz</a>.</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/hSBUrNuBE5A" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2838/on-buzz/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://zef.me/2838/on-buzz</feedburner:origLink></item>
		<item>
		<title>Who needs native phone apps anyway?</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/d4OpJLmORWM/who-needs-native-phone-apps-anyway</link>
		<comments>http://zef.me/2831/who-needs-native-phone-apps-anyway#comments</comments>
		<pubDate>Wed, 10 Feb 2010 10:22:31 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[webapps]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2831</guid>
		<description><![CDATA[&#160;

&#160;
]]></description>
			<content:encoded><![CDATA[<p><img alt="" title="IMG_0316" width="250" height="375" class="alignnone size-full wp-image-2824" src="http://zef.me/wp-content/uploads/2010/02/IMG_0316.jpg" />&nbsp;<img alt="" title="IMG_0311" width="250" height="375" class="alignnone size-full wp-image-2829" src="http://zef.me/wp-content/uploads/2010/02/IMG_0311.jpg" /><img alt="" title="IMG_0312" width="250" height="375" class="alignnone size-full wp-image-2828" src="http://zef.me/wp-content/uploads/2010/02/IMG_0312.jpg" /><img alt="" title="IMG_0313" width="250" height="375" class="alignnone size-full wp-image-2827" src="http://zef.me/wp-content/uploads/2010/02/IMG_0313.jpg" /><img alt="" title="IMG_0317" width="250" height="375" class="alignnone size-full wp-image-2830" src="http://zef.me/wp-content/uploads/2010/02/IMG_03171.jpg" /><img alt="" title="IMG_0315" width="250" height="375" class="alignnone size-full wp-image-2825" src="http://zef.me/wp-content/uploads/2010/02/IMG_0315.jpg" /><img alt="" title="IMG_0318" width="250" height="375" class="alignnone size-full wp-image-2834" src="http://zef.me/wp-content/uploads/2010/02/IMG_0318.jpg" /></p>

<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/d4OpJLmORWM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2831/who-needs-native-phone-apps-anyway/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://zef.me/2831/who-needs-native-phone-apps-anyway</feedburner:origLink></item>
		<item>
		<title>On Language Design: Making Expensive Actions Hard</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/i85wmw6xdFw/on-language-design-making-expensive-actions-hard</link>
		<comments>http://zef.me/2805/on-language-design-making-expensive-actions-hard#comments</comments>
		<pubDate>Mon, 08 Feb 2010 09:45:31 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[persistence.js]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2805</guid>
		<description><![CDATA[While abstraction is a great thing,&#160;some abstractions are completely unpredictable. For instance, object-relational mappers are very convenient to get started, but if performance is important these frameworks can get very unpredictable performance characteristics. Let&#8217;s take Hibernate as an example. Java does not support properties, instead there&#8217;s a convention of using getter and setter methods for [...]]]></description>
			<content:encoded><![CDATA[<p>While abstraction is a great thing,&nbsp;some abstractions are completely unpredictable. For instance, object-relational mappers are very convenient to get started, but if performance is important these frameworks can get very unpredictable performance characteristics. Let&#8217;s take Hibernate as an example. Java does not support properties, instead there&#8217;s a convention of using getter and setter methods for this purpose. The general assumption is that calling these methods has little overhead:</p>

<p style="margin-left: 40px; "><code>Person p = em.find(Person.class, &quot;somePersonId&quot;);<br />
println(p.getName());<br />
println(p.getFather().getName());</code></p>

<p>Easy enough. But hang on, what did that third line&nbsp;do? I turns out that it had to execute a SQL query to fetch <code>p</code>&#8217;s fatherly <code>Person</code> object. Not a big deal, you&#8217;d say. But what if you have code like this in a for loop iterating over 200 person objects? At the face of it, this should be cheap, you&#8217;re just doing simple property access, right? However, behind the scenes it executes another query for every iteration, making this simple loop quite expensive at 201 required queries. Sure, you can tell Hibernate to prefetch the father property, and you should, but if you forget you may not notice what&#8217;s hogging the database until you start inspecting query logs.</p>

<p><strong>In Java, it is difficult to predict which statements are going to be expensive to execute by inspecting the code.</strong></p>

<p>This is true for practically every programming language, but it&#8217;s also a shame. It may be useful to have some kind of syntactical overhead for performing expensive operations. If expensive operations are inconvenient to write, will that not encourage programmers to write more efficient code?</p>

<p>It turns out Javascript has a mechanism for this. Javascript environments are typically single threaded. If you only have a single thread available in an interactive environment like the browser you want to block it as little as possible. Therefore, in Javascript, expensive operations are performed asynchronously. I <a href="http://zef.me/2726/on-asynchronous-programming">complained about asynchronous programming before</a>, but it has the nice property of making explicit what operations are going to be expensive.</p>

<p>Let&#8217;s see how this affected <a href="http://zef.me/2774/persistence-js-an-asynchronous-javascript-orm-for-html5gears">persistence.js, my asynchronous Javascript ORM</a>:&nbsp;</p>

<p style="margin-left: 40px; "><code>persistence.transaction(<strong>function</strong>(tx) {<br />
&nbsp;&nbsp;Person.load(tx, &quot;somePersonId&quot;, <strong>function</strong>(p) {<br />
&nbsp;&nbsp; &nbsp;println(p.name);<br />
&nbsp;&nbsp; &nbsp;p.fetch(tx, 'father', <strong>function</strong>(father) {<br />
&nbsp;&nbsp; &nbsp; &nbsp;println(father.name);<br />
&nbsp;&nbsp; &nbsp;});<br />
&nbsp;&nbsp;});<br />
});</code></p>

<p>That&#8217;s one piece of annoying code to write, right? Indeed it is, because it&#8217;s quite expensive to execute too. As you can see there are three callback functions, which is also the number of database operations that are required to execute this code. One to start a transaction, one to load the person object and one to load its <code>father</code> object.</p>

<p>So how does this work in loops? We can use the <code>each</code> method on query collections:</p>

<p style="margin-left: 40px; "><code>persistence.transaction(<strong>function</strong>(tx) {<br />
&nbsp;&nbsp;Person.all().each(tx, <strong>function</strong>(p) {<br />
&nbsp;&nbsp; &nbsp;println(p.name);<br />
&nbsp;&nbsp; &nbsp;println(p.father.name);<br />
&nbsp;&nbsp;});<br />
});</code></p>

<p>Again two defined callback functions, which gives you a feeling of how expensive this code is. One callback for starting the transaction and another one that iterates over the query result. However, if we execute this code we will get exceptions:</p>

<blockquote>
<p>Property &#8216;father&#8217; with id: 0BEEC2CB6AF64A72A7647DF09BCD62C3 not fetched, either prefetch it or fetch it manually.</p>
</blockquote>

<p>Rather than lazy loading the <code>father</code> property in each iteration, <a href="http://github.com/zefhemel/persistencejs">persistence.js</a> simply throws an exception, it does not support lazy loading without syntactical overhead. However, as the error explains, we can fix the problem by prefetching the <code>father</code> property, so we will:</p>

<p style="margin-left: 40px; "><code>Person.all().prefetch(&quot;father&quot;).each(tx,&nbsp;<strong>function</strong>(p) {<br />
&nbsp;&nbsp;println(p.name);<br />
&nbsp;&nbsp;println(p.father.name);<br />
});</code></p>

<p>Which results in an efficient predictable performance in terms of number of queries executed (1 query for this piece of code).</p>

<p>Kind of nice, right?</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/i85wmw6xdFw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2805/on-language-design-making-expensive-actions-hard/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://zef.me/2805/on-language-design-making-expensive-actions-hard</feedburner:origLink></item>
		<item>
		<title>persistence.js: An Asynchronous Javascript ORM for HTML5/Gears</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/7uEBpZalrpg/persistence-js-an-asynchronous-javascript-orm-for-html5gears</link>
		<comments>http://zef.me/2774/persistence-js-an-asynchronous-javascript-orm-for-html5gears#comments</comments>
		<pubDate>Fri, 05 Feb 2010 14:18:38 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[persistence.js]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2774</guid>
		<description><![CDATA[The past week or two I have been developing an asynchronous object-relational mapper in Javascript, called persistence.js. Its main use-case, right now, is to simplify the database component of offline-capable web applications, like the mobile web applications that I&#8217;m working on. But with some tweaking it should also be usable in server-side applications, like node.js [...]]]></description>
			<content:encoded><![CDATA[<p>The past week or two I have been developing an asynchronous object-relational mapper in Javascript, called <a href="http://github.com/zefhemel/persistencejs">persistence.js</a>. Its main use-case, right now, is to simplify the database component of offline-capable web applications, like the <a href="http://zef.me/2693/lets-build-a-dsl">mobile web applications that I&#8217;m working on</a>. But with some tweaking it should also be usable in server-side applications, like <a href="http://nodejs.org">node.js</a> servers. It uses the SQLite database that is available in modern Webkit-based browsers (like Safari 4 and Google Chrome), or the <a href="http://gears.google.com">Google Gears</a> datastore that is available in any browser that runs the Google Gears browser extension (like Firefox). It also runs on iPhone (OS 3+) and Android browsers. In its current state it does not run on IE (although I haven&#8217;t tested it).</p>

<p>There is one other asynchronous Javascript ORM framework that I know of (<a href="http://impel.simulacre.org/">Impel</a>), but it has a dependency on <a href="http://mootools.net/">MooTools</a>, which would be yet another framework you need to pull into your web application.&nbsp;<a href="http://github.com/zefhemel/persistencejs">persistence.js</a>&nbsp;has no dependency on any Javascript framework (other than a tiny Google Gears initialization script in case you want to use Gears).</p>

<p><a href="http://github.com/zefhemel/persistencejs">persistence.js</a>&nbsp;is an asynchronous framework, which means that operations that can take some time, are provided with a callback function that will be invoked when the operation has completed. This asynchronous nature makes <a href="http://github.com/zefhemel/persistencejs">persistence.js</a> harder to use than synchronous frameworks like e.g. <a href="http://activerecordjs.org/record.html">ActiveRecord.js</a>, but the fact is that if you want to take advantage of the new HTML5 database capabilities, you have no other choice than to do it asynchronously. <a href="http://github.com/zefhemel/persistencejs">persistence.js</a> tries to make it as easy for you as possible.</p>

<p>The <a href="http://github.com/zefhemel/persistencejs/blob/master/persistence.js">code is fairly well documented</a> (for my doing anyway), and the <a href="http://github.com/zefhemel/persistencejs/blob/master/README.md">README</a> explains how to use it and gives some code examples as well. To give you flavor, the following code opens a database connection, defines two entities (Task and Category), and synchronizes the definition with the database (creates the tables etc.):</p>

<blockquote>
<p><code>persistence.connect('testdbnm', 'My test db', 5 * 1024 * 1024);<br />
<br />
<strong>var</strong> Task = persistence.define('Task', {<br />
&nbsp;&nbsp; &nbsp;name: &quot;TEXT&quot;,<br />
&nbsp;&nbsp; &nbsp;description: &quot;TEXT&quot;,<br />
&nbsp;&nbsp; &nbsp;done: &quot;BOOL&quot;<br />
});<br />
<br />
<strong>var</strong> Category = persistence.define('Category', {<br />
&nbsp;&nbsp; &nbsp;name: &quot;TEXT&quot;<br />
});<br />
<br />
Category.hasMany('tasks', Task, 'category');<br />
<br />
persistence.schemaSync(<strong>null</strong>, <strong>function</strong>(tx) {<br />
&nbsp;&nbsp;alert('Successfully synchronized the schema!');<br />
});</code></p>
</blockquote>

<p>Instances of the defined entities can then be created in a natural way, and subsequently marked to be persisted:</p>

<blockquote>
<p><code><strong>var</strong> task = <strong>new</strong> Task();<br />
task.name = &quot;My new task&quot;;<br />
<strong>var</strong> category =<br />
<strong>&nbsp;&nbsp; &nbsp;new</strong> Category({name: &quot;My category&quot;});<br />
persistence.add(task);<br />
persistence.add(category);</code></p>
</blockquote>

<p>One-to-many and many-to-many relationships can be used as collections:</p>

<p style="margin-left: 40px; "><code>category.tasks.add(task);</code></p>

<p>When modifications to objects have been made, these have to be flushed to the database:</p>

<blockquote>
<p><code>persistence.flush(<strong>null</strong>, <strong>function</strong>() {<br />
&nbsp;&nbsp;alert('All objects flushed!');<br />
});</code></p>
</blockquote>

<p>A nice feature of <a href="http://github.com/zefhemel/persistencejs">persistence.js</a> is QueryCollections, which are virtual collections that can&nbsp;prefetch relations, can&nbsp;easily be filtered and sorted (and in the future paginated):&nbsp;</p>

<blockquote>
<p><code>Task.all().filter(&quot;done&quot;, '=', true)<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.prefetch(&quot;category&quot;)<br />
</code><code>&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.order(&quot;name&quot;, <strong>false</strong>)<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.list(<strong>null</strong>, <strong>function</strong> (results) {<br />
&nbsp;&nbsp; &nbsp;results.forEach(<strong>function</strong> (t) {<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;console.log('[' + t.category.name + '] '<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;+ t.name);<br />
&nbsp;&nbsp; &nbsp;});<br />
});</code></p>
</blockquote>

<p>In the future I intend to add synchronization support to it so that the local database can transparently be synchronized with a (view on) a remote database, which is a typical use case of applications like these.</p>

<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/7uEBpZalrpg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2774/persistence-js-an-asynchronous-javascript-orm-for-html5gears/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://zef.me/2774/persistence-js-an-asynchronous-javascript-orm-for-html5gears</feedburner:origLink></item>
		<item>
		<title>Using Screen Estate</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/6JEMTLMys5s/using-screen-estate</link>
		<comments>http://zef.me/2760/using-screen-estate#comments</comments>
		<pubDate>Mon, 01 Feb 2010 09:13:53 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2760</guid>
		<description><![CDATA[One of the more interesting UI features that the iPad exposes is its use of screen orientation. A good example of this is in the e-mail application. In Portrait mode your screen is long and narrow, so you see one e-mail. This is convenient for reading longer pieces of text:



However, when you&#8217;re more in a [...]]]></description>
			<content:encoded><![CDATA[<p>One of the more interesting UI features that the <a href="http://www.apple.com/ipad">iPad</a> exposes is its use of screen orientation. A good example of this is in the e-mail application. In Portrait mode your screen is long and narrow, so you see one e-mail. This is convenient for reading longer pieces of text:</p>

<p><img alt="" title="ipadPortrait" width="420" height="477" class="alignnone size-full wp-image-2763" src="http://zef.me/wp-content/uploads/2010/02/ipadPortrait.png" /></p>

<p>However, when you&#8217;re more in a browsing mode &quot;let&#8217;s see what e-mail we got today&quot;, you flip the device around and get a view with a message list on the left and e-mail at the right:</p>

<p><img alt="" title="ipadLandscape" width="503" height="380" class="alignnone size-full wp-image-2764" src="http://zef.me/wp-content/uploads/2010/02/ipadLandscape.png" /></p>

<p>If find this a rather fascinating user interface idea and wonder if we can not apply it more iPhone applications as well. There&#8217;s one iPhone application that I know of that really uses this, and that&#8217;s the Calculator application, which in portrait mode looks like this:</p>

<p>&nbsp;<img alt="" title="calculator1" width="224" height="336" class="alignnone size-full wp-image-2761" src="http://zef.me/wp-content/uploads/2010/02/calculator1.png" /></p>

<p>And when you flip it:</p>

<p><img alt="" title="calculator2" width="336" height="224" class="alignnone size-full wp-image-2762" src="http://zef.me/wp-content/uploads/2010/02/calculator2.png" /></p>

<p>In the framework for the development of mobile web applications that I&#8217;m developing, I have support for orientation events. Here&#8217;s a <a href="http://zef.me/zodo/">simple todo application I&#8217;m working on</a>&nbsp;(looks best on an iPhone or desktop webkit browser) that takes advantage of this feature. I&#8217;m not entirely sure this is the best way to use the feature, but it&#8217;s cool nonetheless. In portrait mode the application looks as follows:</p>

<p><img alt="" title="zodo-portrait" width="233" height="350" class="alignnone size-full wp-image-2768" src="http://zef.me/wp-content/uploads/2010/02/zodo-portrait.png" /></p>

<p>You can swipe any of the items to show a delete button:</p>

<p><img alt="" title="delete-task" width="315" height="84" class="alignnone size-full wp-image-2769" src="http://zef.me/wp-content/uploads/2010/02/delete-task.png" /></p>

<p>However, if you&#8217;re in a destructive mode you can also flip the device around and switch to edit mode, in which all items become immediately deletable:</p>

<p><img alt="" title="zodo-landscape" width="352" height="234" class="alignnone size-full wp-image-2770" src="http://zef.me/wp-content/uploads/2010/02/zodo-landscape.png" /></p>

<p>(You can emulate this behavior in a desktop browser by resizing the window, making it wider than it is long or vice versa).</p>

<p>A user interface design concept to think about.</p>

<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/6JEMTLMys5s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2760/using-screen-estate/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://zef.me/2760/using-screen-estate</feedburner:origLink></item>
		<item>
		<title>Task Switching and Open Development on the Apple iPad</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/FCxX4XsU_-Y/task-switching-and-open-development-on-the-apple-ipad</link>
		<comments>http://zef.me/2748/task-switching-and-open-development-on-the-apple-ipad#comments</comments>
		<pubDate>Thu, 28 Jan 2010 12:26:45 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2748</guid>
		<description><![CDATA[In case you missed it, Apple launched the iPad yesterday. Essentially it&#8217;s a beautiful looking giant iPod Touch running the iPhone/iPod OS, slightly adapted to take better advantage of the bigger 10&#34; screen. It&#8217;s available at a remarkably (for Apply, and the hardware you get) low price starting at $499. Not only does it look [...]]]></description>
			<content:encoded><![CDATA[<p>In case you missed it, Apple launched the <a href="http://www.apple.com/ipad">iPad</a> yesterday. Essentially it&#8217;s a beautiful looking giant iPod Touch running the iPhone/iPod OS, slightly adapted to take better advantage of the bigger 10&quot; screen. It&#8217;s available at a remarkably (for Apply, and the hardware you get) low price starting at $499. Not only does it look like a bigger iPod and runs its software, it also comes with the usual suspects: an App Store, synchronization through iTunes etc.</p>

<p><img alt="" title="iPad" width="301" height="202" class="alignnone size-full wp-image-2749" src="http://zef.me/wp-content/uploads/2010/01/iPad.png" /></p>

<p>With that come the usual restrictions: only install software through the App Store and no multi-tasking. Although I truly believe the no multi-tasking support limitation is going to be resolved in June, when Apple usually releases new iPhones and iPod touches (and an operating system to go with that), there is a way around both these problems:</p>

<p>The iPad, like the iPhone and iPod touch comes with an <strong>excellent, fast&nbsp;</strong><strong>browser</strong>.</p>

<p>If you build iPad web applications, you can build whatever you like, it doesn&#8217;t have to be approved by Apple and you can roll out updates instantly. In addition, web applications, like on the iPhone/iPod touch are the only type of application that &quot;keep running&quot; (in the sense of not being killed) when switching applications. You can have several web apps open in safari, and they&#8217;re still there, in the same state, after you exit Mobile Safari and return to it. Although the applications do not run simultaneously, you can easily switch between them, in a kind of <em>task switcher</em> inside Safari, which is its ability to switch between &quot;tabs&quot;:</p>

<p><img alt="" title="iphone-app-switching" width="320" height="480" class="alignnone size-full wp-image-2750" src="http://zef.me/wp-content/uploads/2010/01/iphone-app-switching.png" /></p>

<p>And yes, indeed. This exactly the direction in which I&#8217;m heading with my <a href="http://zef.me/2693/lets-build-a-dsl">DSL for mobile applications</a> (which may actually include the iPad as a target).</p>

<p>By the way, I&#8217;m trying to come up with a new name for the DSL, now that MobiDSL is apparently taken. Name suggestions? It does not have to include the word DSL at all, preferably not. I&#8217;m thinking about something with &quot;Touch&quot; in it, or possibly something completely different. Any ideas?</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/FCxX4XsU_-Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2748/task-switching-and-open-development-on-the-apple-ipad/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://zef.me/2748/task-switching-and-open-development-on-the-apple-ipad</feedburner:origLink></item>
		<item>
		<title>On Asynchronous Programming</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/n1kWPUQDTiQ/on-asynchronous-programming</link>
		<comments>http://zef.me/2726/on-asynchronous-programming#comments</comments>
		<pubDate>Tue, 26 Jan 2010 20:13:40 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2726</guid>
		<description><![CDATA[MSDN:


Asynchronous operations are typically used to perform tasks that might take a long time to complete, such as opening large files, connecting to remote computers, or querying a database. An asynchronous operation executes in a thread separate from the main application thread. When an application calls methods to perform an operation asynchronously, the application can [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://msdn.microsoft.com/en-us/library/ms228969.aspx">MSDN</a>:</p>

<blockquote>
<p>Asynchronous operations are typically used to perform tasks that might take a long time to complete, such as opening large files, connecting to remote computers, or querying a database. An asynchronous operation executes in a thread separate from the main application thread. When an application calls methods to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.</p>
</blockquote>

<p>Asynchronous programming clearly has performance benefits, as mentioned in the explanation I just quoted. What I have <a href="http://zef.me/2570/event-programming-the-highway-to-concurrency">complained about before</a> is the programming model that follows from it. In Javascript this becomes painfully clear. In Javascript you do not have threading (<a href="http://www.whatwg.org/specs/web-workers/current-work/">although it&#8217;s coming</a>), therefore, anything that is not going to be instantaneous, needs to be executed asynchronously or it will freeze the browser. The typical example of this is Ajax (<strong>Asynchronous</strong> Javascript and XML, a term that is way too general, when you think of it), but you get the same things when you start interacting with local databases. In a previous post I showed the following code:</p>

<p><img alt="" title="async-js" width="500" height="179" class="alignnone size-full wp-image-2717" src="http://zef.me/wp-content/uploads/2010/01/async-js.png" /></p>

<p>What I do in this code is attempting to implement simple sequential execution of</p>

<ol>
    <li>opening a database connection</li>
    <li>starting a transaction</li>
    <li>creating a table</li>
    <li>inserting a task</li>
    <li>inserting another task</li>
    <li>selecting all tasks in the table</li>
    <li>render list items for them</li>
</ol>

<p>In a synchronous programming model this would roughly be:</p>

<p style="margin-left: 40px; "><strong><code>var</code></strong><code> db = db.openDatabase(...);<br />
db.startTransaction();<br />
db.executeSql(&quot;CREATE ...&quot;);<br />
db.executeSql(&quot;INSERT INTO ...&quot;);<br />
db.executeSql(&quot;INSERT INTO ...&quot;);<br />
<strong>var</strong> results = db.executeSql(&quot;SELECT * FROM ...&quot;);<br />
<strong>for</strong>(<strong>var</strong> i = 0; i &lt; results.length; i++) {<br />
&nbsp;&nbsp;...<br />
}</code></p>

<p>I think you will agree that this is much more legible than the asynchronous counterpart, except that you should never run it like this in Javascript, because it will completely block the UI thread for the duration of the code (which could be several seconds).</p>

<p>I looked at the <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> because I hoped they had solved this problem, but it turns out they even made it worse, because now you have to deal with the Java overhead of implementing interfaces:</p>

<p><img alt="" title="asynchronous-java" width="495" height="113" class="alignnone size-full wp-image-2734" src="http://zef.me/wp-content/uploads/2010/01/asynchronous-java-e1264511017205.png" /></p>

<p>(Nothing bad about GWT by the way, using it makes a lot of sense in many larger projects.)</p>

<p>Getting back to my point: would it be possible to automatically rewrite synchronous code to asynchronous code? I&#8217;m starting to feel that&#8217;s very possible indeed. Let&#8217;s take a simple example. Let&#8217;s say we managed to implement an <em>adder</em> function that is extremely slow (maybe by executing it on a server far, far away):</p>

<p style="margin-left: 40px; "><code>console.log(adder(3, 4));</code></p>

<p>This code would block for several seconds, possibly, while the adder function is adding the numbers 3 and 4. In an asynchronous manner this would be written as:</p>

<p style="margin-left: 40px; "><code>adder(3, 4, <strong>function</strong>(result) {<br />
&nbsp;&nbsp; &nbsp;console.log(result);<br />
});</code></p>

<p>Asynchronous functions always provide a <em>callback function</em>, that is passed the result of the computation once it completes. The result of the computation is what we call a <em>return value</em> in synchronous programming. So, what if we sequence a number of synchronous statements:</p>

<p style="margin-left: 40px; "><strong><code>var</code></strong><code> a = 0;<br />
a++;<br />
<strong>var</strong> n = adder(3, a);<br />
<strong>var</strong> m = adder(n, 4);<br />
console.log(m);</code></p>

<p>What would that look like in asynchronous code?</p>

<p style="margin-left: 40px; "><strong><code>var</code></strong><code> a = 0;<br />
a++;<br />
adder(3, a, <strong>function</strong>(n) {<br />
&nbsp;&nbsp;adder(n, 4, <strong>function</strong>(m) {<br />
&nbsp;&nbsp; &nbsp;console.log(m);<br />
&nbsp;&nbsp;});<br />
});</code></p>

<p>As you can see, this transformation is not complicated. It could easily be automated, so that in the DSL that we&#8217;re designing you could write synchronous code, and it would be translated to asynchronous code automatically.</p>

<p>However, there is one thing that worries me about this approach. The advantage here is that you can write simpler code, which does indeed run asynchronously. However, we miss out on the opportunity to parallelize things. For instance, the two INSERT queries in my first example can easily be executed in parallel. There is no reason why I should execute them sequentially (when we look at just the two INSERTs). This may be a lot faster even. In this particular case I did this, because I wanted to make sure that both INSERTs had taken place before I did the SELECT. If I would have parellized the two INSERTs, I would to somehow track when both INSERTs had happened so I could do the SELECT. That&#8217;s kind of cumbersome. In the general case, however, there may in fact be many things that may be easily parallelized, and although I want to provide the user with a synchronous model because it&#8217;s so much more convenient to write, I also don&#8217;t want to lose the parallelizability of asynchronous code.</p>

<p>Maybe it would be possible to analyze the code for any dependencies. In the last example, for instance, the second adder call cannot be executed in parallel to the first adder call, because it depends on the result of the first, but in other cases there may be no such dependency. But I&#8217;m afraid to open up the world of hurt that is called concurrent programming here, so maybe I should stay out of that kind of stuff.</p>

<p>Any ideas or experiences with this?</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/n1kWPUQDTiQ" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2726/on-asynchronous-programming/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://zef.me/2726/on-asynchronous-programming</feedburner:origLink></item>
		<item>
		<title>Let’s Build a DSL: Platform Research</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/Lwc0eMX-8j8/lets-build-a-dsl-platform-research</link>
		<comments>http://zef.me/2722/lets-build-a-dsl-platform-research#comments</comments>
		<pubDate>Tue, 26 Jan 2010 07:39:09 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2722</guid>
		<description><![CDATA[Now that we decided on a domain and target platform of our DSL, it is time to explore our target platform. Although I have used HTML, CSS and Javascript for many years, I never looked that seriously into the possibilities of especially CSS and Javascript. To help me with that I&#8217;ve been reading a few [...]]]></description>
			<content:encoded><![CDATA[<p>Now that we decided on <a href="http://zef.me/2693/lets-build-a-dsl">a domain and target platform of our DSL</a>, it is time to explore our target platform. Although I have used HTML, CSS and Javascript for many years, I never looked that seriously into the possibilities of especially CSS and Javascript. To help me with that I&#8217;ve been reading a few books:</p>

<ul>
    <li><a href="http://oreilly.com/catalog/9780596517748">Javascript: The Good Parts</a>, excellent book about Javascript, helping you avoid all that bad parts</li>
    <li><a href="http://www.manning.com/bibeault/">jQuery in Action</a>, good book about <a href="http://www.jquery.com">jQuery</a></li>
    <li><a href="http://building-iphone-apps.labs.oreilly.com/index.html">Building iPhone Apps with HTML, CSS and Javascript</a>, free online book from O&#8217;Reilly</li>
</ul>

<p>In addition there are a number of great blog posts and libraries helping to develop native-looking web applications for the iPhone:</p>

<ul>
    <li><a href="http://lipidity.com/apple/iphone-webkit-css-3">Make the most of the iPhone SDK</a></li>
    <li><a href="http://code.google.com/p/iphone-universal/">Universal iPhone UI library</a>, many nice CSS tricks</li>
    <li><a href="http://jqtouch.com/">QTouch, jQuery extensions for iPhone web apps</a></li>
    <li><a href="http://ajaxian.com/archives/iphone-native-looking-skin">iPhone Native looking skin</a></li>
</ul>

<p>And a number of performance related posts from Google (from the Gmail team that developed the excellent Gmail mobile application):</p>

<ul>
    <li><a href="http://googlecode.blogspot.com/2009/04/html5-and-webkit-pave-way-for-mobile.html">HTML5 and Webkit pave the way for mobile web applications</a></li>
    <li><a href="http://googlecode.blogspot.com/2009/06/gmail-for-mobile-html5-series.html">Suggestions for better performance</a></li>
    <li><a title="Using AppCache to launch offline - Part 1" href="http://google-code-updates.blogspot.com/2009/04/gmail-for-mobile-html5-series-using.html" id="ye:o">Using AppCache to launch offline &#8211; Part 1</a></li>
    <li><a title="Using AppCache to launch offline - Part 1" href="http://google-code-updates.blogspot.com/2009/05/gmail-for-mobile-html5-series-part-2.html" id="b52e">Using AppCache to launch offline &#8211; Part 2</a></li>
    <li><a title="Using AppCache to launch offline - Part 1" href="http://google-code-updates.blogspot.com/2009/05/gmail-for-mobile-html5-series-part-3.html" id="moyw">Using AppCache to launch offline &#8211; Part 3</a></li>
    <li><a href="http://googlecode.blogspot.com/2009/06/gmail-for-mobile-html5-series-cache.html">Cache patterns for offline HTML5 applications</a></li>
    <li><a href="http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series.html">Auto-growing textareas</a></li>
    <li><a href="http://googlecode.blogspot.com/2009/05/gmail-for-mobile-html5-series-common.html">A Common API for web storage</a></li>
</ul>

<p>Because eventually I want to add automatic data synchronization support to our DSL, I&#8217;m also looking into synchronization strategies. <a href="http://blog.deeje.tv/musings/2009/06/notes-on-writing-a-history-driven-client-server-synchronization-engine.html">I found a nice post about that</a>. Of course, <a href="http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007256-CH1-SW1">Apple&#8217;s own iPhone web app documentation</a> is also very useful.</p>

<p>&nbsp;</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/Lwc0eMX-8j8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2722/lets-build-a-dsl-platform-research/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://zef.me/2722/lets-build-a-dsl-platform-research</feedburner:origLink></item>
		<item>
		<title>Let’s build a DSL</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/LvljerBXbV4/lets-build-a-dsl</link>
		<comments>http://zef.me/2693/lets-build-a-dsl#comments</comments>
		<pubDate>Sun, 24 Jan 2010 15:54:08 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[mobidsl]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2693</guid>
		<description><![CDATA[Greetings surfer of the Internets. We meet at an exciting time, you and I. We stand at the birth of a new language, a language of the domain-specific kind. What domain is that, you ask? It is the mobile domain. Applications as frequently found on devices of the iPhone and Android sort, but not graphical [...]]]></description>
			<content:encoded><![CDATA[<p>Greetings surfer of the Internets. We meet at an exciting time, you and I. We stand at the birth of a new language, a language of the domain-specific kind. What domain is that, you ask? It is the mobile domain. Applications as frequently found on devices of the iPhone and Android sort, but not graphical games. No&#8230; serious applications. Todo apps. Tip calculators. Transportation planners. Personal little database applications. Todo applications, and&#8230; tip calculators.</p>

<p>You may say: &quot;but Zef, that is absurd. The mobile domain is huge. There are so many phone platforms out there!&quot; But I say, no. I recently investigated the importance of the iPhone and Android platforms compared to the rest and found that people care mostly about iPhone and Android and not so much about anything else. That&#8217;s right. <em>Anything</em>. The following graph proves this:</p>

<p><img alt="" title="schientific-graph2" width="369" height="281" class="alignnone size-full wp-image-2703" src="http://zef.me/wp-content/uploads/2010/01/schientific-graph2.png" /></p>

<p>So we shall not worry about this issue.</p>

<p>Now that we decided on a domain (mobile applications) and target platforms (iPhone and Android phones), the next essential step for success is choosing a good name. But, do not worry, I already decided what it is going to be. The name of our language shall be: MobiDSL, which is pronounced<em> Mobi Diesel</em>. It&#8217;s fuel for your phone, which is just what we need with the sucky battery life that the phones that matter have these days. So MobiDSL is the name, at least until I can come up with something better. And do not worry, I registered <a href="http://www.mobidsl.org">MobiDSL.org</a> already, which redirects to this very post. Is it coincidence? I will leave that for you to figure out.</p>

<p>But, you will ask, if we are going to target both iPhone and Android, what kind of code are we going to generate? If we generated Objective-C code, it will only run on iPhone, and Java will only run on Android. Are we going to generate both? My answer to this question isseth &quot;no&quot;.</p>

<p>My original thought was to use <a href="http://zef.me/2218/on-the-pil">PIL</a>, the universal platform-independent super language, which I would let generate the Objective-C and Java code for me. But then I came up with something much more radical, something much more forward thinking, my friends, a solution that may just hand me some other mobile platforms for free (not that they matter).</p>

<p>We are going to build applications the way Steve intended them to be built, back in 2007 at the launch of the iPhone. I was <a href="http://zef.me/1365/ajax-reality-check">entusiastic about this idea from the very beginning</a>:</p>

<blockquote>
<p>Thanks Steve! &quot;Yeah, we have this new amazing modern way of developing applications for your phone, it&rsquo;s called a website!&quot; Awesome. &quot;It integrates great with all the iPhone features. For example you can create a &quot;call:0123223222&quot; link to call somebody!&quot; Great. Except you always need an internet connection to use it, it&rsquo;s slow, you can&rsquo;t create an icon for it in the menu. And&hellip; oh yeah&hellip; it&rsquo;s a frickin&rsquo; website! Apparently this was done for &quot;security reasons&quot;. What about Java, Steve? Every frickin&rsquo; phone supports Java. It all runs in a sandbox, it&rsquo;s all secure. It even runs without an internet connection and it&rsquo;s responsive (yes, that has become a feature in the web 2.0 day and age). Why no Java on the iPhone, explain it to me.</p>
</blockquote>

<p>Yes indeed. We are going to mobile web applications. But not to worry, web applications on mobile phones have advanced far beyond the killer &quot;click to call&quot; feature mentioned. Heck, the <a href="http://www.google.com/phone">Google Nexus One</a> has the same clock speed as my wife&#8217;s iBook.&nbsp;<a href="http://en.wikipedia.org/wiki/HTML5">HTML 5</a>&nbsp;gives us access to this power by offering:</p>

<ul>
    <li><a href="http://developer.apple.com/safari/library/documentation/iPhone/Conceptual/SafariJSDatabaseGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007256-CH1-SW1">Local databases</a> (SQLite, in the browser)</li>
    <li><a href="http://smithsrus.com/gps-geolocation-in-safari-on-iphone-os-3-0/">Location information</a> (GPS coordinates)</li>
    <li><a href="http://dev.w3.org/html5/workers/">Threading</a> (WebWorkers)</li>
    <li><a href="http://rabblerule.blogspot.com/2009/08/detecting-swipe-in-webkit.html">Gestures</a> (swipes, mostly)</li>
    <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html">Canvas</a>, for some pretty drawing</li>
    <li><a href="http://www.w3.org/TR/offline-webapps/">Offline support</a>, the entire application is cached on the phone and is fully functional even without internet connection</li>
    <li>The application can have an icon in the phone&#8217;s menu</li>
    <li>Full-screen mode, applications can run without the location and browser navigation bars (on iPhone at least)</li>
    <li>One platform to rule them all: simply generate HTML, CSS and Javascript and run on both platforms</li>
</ul>

<p>In addition we work around the App Store which can be seen as both an advantage and disadvantage. Advantage is that we can build whatever application we like and Apple does not need to like or approve it. Rolling out updates is also much faster. The disadvantage is that web applications don&#8217;t appear on the App Store, which is a great promotion tool, but then, tools like <a href="http://phonegap.com/">PhoneGap</a> can generate wrappers around web apps that can be submitted to the Android marketplace and iTunes App Store.</p>

<p>As I said, we meet in exciting times. I spent most of last week playing around with Javascript and <a href="http://jquery.com/">jQuery</a> and applying them to mobile applications. I managed to build a functional todo application that stores all of its data locally on the phone and looks very much native to the iPhone (some CSS trickery can probably make it Android-like too). The application can be used without an internet connection in full-screen and has a icon on the iPhone menu. I currently work on a few jQuery extensions to make writing such applications simpler. Then, when that&#8217;s done I shall proceed to build a nice, easy to use and analyze DSL on top of it. Isn&#8217;t HTML, CSS and Javascript easy to use, you ask? Well, I don&#8217;t know about you, but Javascript&#8217;s asynchronous coding is not always ideal in my opinion:</p>

<p><img alt="" title="async-js" width="500" height="179" class="alignnone size-full wp-image-2717" src="http://zef.me/wp-content/uploads/2010/01/async-js.png" /></p>

<p>Trust me. It will be great.</p>

<p>Therefore, I shall declare 2010 as the year of the mobile web application.</p>

<p>I shall keep you informed, my valued surfer of the Internets.</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/LvljerBXbV4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2693/lets-build-a-dsl/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://zef.me/2693/lets-build-a-dsl</feedburner:origLink></item>
		<item>
		<title>The Point of WebDSL</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/hDhrl0tZ1Po/the-point-of-webdsl</link>
		<comments>http://zef.me/2683/the-point-of-webdsl#comments</comments>
		<pubDate>Wed, 13 Jan 2010 15:49:27 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[webdsl]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2683</guid>
		<description><![CDATA[&#160;Jay asks in the comments:


I don&#8217;t mean to be mean, because I really like your blog and I read it all the time&#8230; but could you just explain to me the point of WebDSL? I honestly don&#8217;t mean it in any kind of negative way, I&#8217;m just wondering why you&#8217;re dedicating your valuable time to [...]]]></description>
			<content:encoded><![CDATA[<p>&nbsp;Jay <a href="http://zef.me/2600/adia-a-week-with-clojure-and-mongodb#comment-28381384">asks in the comments</a>:</p>

<blockquote>
<p>I don&#8217;t mean to be mean, because I really like your blog and I read it all the time&#8230; but could you just explain to me the point of WebDSL? I honestly don&#8217;t mean it in any kind of negative way, I&#8217;m just wondering why you&#8217;re dedicating your valuable time to building something like that when RoR, php, et al. already exist.</p>
<p>Just from a cursory look, it seems like the syntax is halfway between Visual Basic (yikes!) and C. Why do you prefer that type of syntax to the Lisp-style syntax of Clojure/Compojure?</p>
</blockquote>

<p>Good questions!</p>

<p><a href="http://www.webdsl.org">WebDSL</a> was started about 3 years ago by <a href="http://www.eelcovisser.org">Eelco Visser</a>&nbsp;as an exercise the the design and implementation of domain-specific languages. His focus up to then had been on <a href="http://strategoxt.org/Sdf/WebHome">parsing</a> and <a href="http://www.strategoxt.org">meta-programming</a>, but it was time to focus on a new domain: the web. When he started Eelco had never built a web application. He investigated a number of Java frameworks as a basis and eventually decided to use <a href="http://www.jboss.com/products/seam/">JBoss Seam</a> as a target.</p>

<p>The goal of WebDSL is to get rid of the boilerplate code you would have to write when building a Java application and raise the level abstraction. The vision was to have simple, domain-specific sub-languages that allow a programmer to specify a certain aspect of the application and the WebDSL compiler would generate all the implementation code for that aspect. Initially there were three sub-languages: a data modeling language, a user interface language and a simple action language to specify logic. As others joined the project (including myself), we added more sub-languages and more features: access control, workflow, data validation, ajax support and more recently search. Work is also done in the area of data evolution (i.e. migrating databases as you change your data model).</p>

<p>Although WebDSL is mainly <a href="http://swerl.tudelft.nl/">a research project</a>, we are increasingly working to make it useable by anybody with some programming experience. We currently have a few websites in production built using WebDSL (<a href="http://researchr.org">researchr</a>, <a href="http://tweetview.net">tweetview</a>, <a href="http://www.webdsl.org">webdsl.org</a> and <a href="http://pil-lang.org/">pil-lang.org</a>) and the <a href="http://webdsl.org/indexpage/Manual">manual</a> is growing.</p>

<p>The idea of building abstractions for the web itself is hardly novel. As Jay mentions, there are many web frameworks that already do this: Rails, Django and so on. There are a few things that we do differently in WebDSL, compared to existing frameworks:</p>

<ul>
    <li>We create our own <em>custom syntax</em>. Whereas Rails and Django are struggling to express everything using Ruby and Python, respectively, we designed our own clean syntax. Whether you like this syntax is a matter of taste. Personally I like it, although, indeed, it inconsistent here and there.</li>
    <li>WebDSL <em>is a statically typed and checked language</em>. I <a href="http://zef.me/2308/when-rails-fails">wrote</a> <a href="http://zef.me/2355/a-when-rails-fails-follow-up">a</a> <a href="http://zef.me/2333/when-jboss-seam-fails">number</a> <a href="http://zef.me/2371/when-scala-dsls-fail">of</a> <a href="http://zef.me/2409/static-verification-an-external-dsl-advantage">posts</a> about this issue and its advantages.</li>
    <li>WebDSL compiles to low-level Java code, which has <em>good performance characteristics</em>. The code we generate does not rely on run-time meta-programming and reflection features of the language which are typically rather slow.</li>
    <li>WebDSL <em>is platform independent</em>. We generate Java code now, but it can be ported relatively easily to .NET, Python or PHP. We have prototypes of this utilizing the <a href="http://zef.me/2218/on-the-pil">PIL language that I developed</a>.</li>
    <li>Within the next few months WebDSL will have <a href="http://blog.eelcovisser.net/uploads/webdsl-editor.png"><em>excellent IDE support</em></a> for Eclipse, built using <a href="http://strategoxt.org/Stratego/Spoofax-IMP">Spoofax/IMP</a>. My colleagues are working on this. It will feature syntax highlighting, as-you-type error reporting, code completion and eventually refactoring support.</li>
</ul>

<p>A drawback that WebDSL has today is that it&#8217;s not trivial to install, but with the IDE plug-in and Java-version that should become a lot easier soon.</p>

<p>So, why am I putting so much effort into this? As you may be aware I&#8217;m doing a Ph.D. in the area of domain-specific languages, so we investigate how to best build them. WebDSL is a case study for us. Soon I intend to work on another DSL, in the domain of mobile applications (yes, a DSL to build iPhone and Android applications, people!). It&#8217;s interesting from a research perspective to see how to best do this.</p>

<p>In addition I regularly experiment with alternative ways of creating DSLs, like <a href="http://zef.me/2600/adia-a-week-with-clojure-and-mongodb">in Clojure</a>&nbsp;and <a href="http://zef.me/2371/when-scala-dsls-fail">Scala</a>. I&#8217;d like to see how far you can push these languages to build the DSLs you like. Clojure allows you to define your own custom syntax, in some sense, as long as you adhere to the rule of the parenthesis. Static error checking is much more problematic. Clojure is also rather tied to one platform, sure, there&#8217;s also <a href="http://github.com/richhickey/clojure-clr">ClojureCLR</a>, but to write programs that work on both CLR and JVM is, well, challenging. IDE support for a Clojure DSL is also non-trivial.</p>

<p>On the other hand, the flexibility of a DSL like WebDSL also has its downsides. Basically you can design the language any way you like, both its syntax and semantics, you don&#8217;t get much for free. Whereas an internal DSL built on Clojure or Scala gets a lot for free: some error reporting, support for namespaces (something we still don&#8217;t have in WebDSL), a type system (in Scala&#8217;s case), an escape to a powerful language (Clojure or Scala) and a rich set of libraries you can use. In WebDSL we have to design all of this from scratch.</p>

<p>So in the end both approaches have their advantages and disadvantages. I intend to continue to explore them both.</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/hDhrl0tZ1Po" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2683/the-point-of-webdsl/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://zef.me/2683/the-point-of-webdsl</feedburner:origLink></item>
		<item>
		<title>On Language Design: Magic Variables in Compojure</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/XU_bKEgD0No/on-language-design-magic-variables-in-compojure</link>
		<comments>http://zef.me/2650/on-language-design-magic-variables-in-compojure#comments</comments>
		<pubDate>Tue, 05 Jan 2010 16:02:18 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[Language Design]]></category>
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2650</guid>
		<description><![CDATA[The Perl language is riddled with special variables. Consider the following example:

open(FILE, &#34;bla.txt&#34;);
while(&#60;FILE&#62;) { print; }

In case you don&#8217;t speak Perl, this is equivalent to:

open(FILE, &#34;bla.txt&#34;);
while(&#60;FILE&#62;) { print $_; }

Still unclear? Alright, once more:

open(FILE, &#34;bla.txt&#34;);
while($line = &#60;FILE&#62;) { print $line; }

Perl is developed by linguist Larry Wall, who likes to put all kinds of natural [...]]]></description>
			<content:encoded><![CDATA[<p>The Perl language is riddled with special variables. Consider the following example:</p>

<p style="margin-left: 40px; "><code>open(FILE, &quot;bla.txt&quot;);<br />
while(&lt;FILE&gt;) { print; }</code></p>

<p>In case you don&#8217;t speak Perl, this is equivalent to:</p>

<p style="margin-left: 40px; "><code>open(FILE, &quot;bla.txt&quot;);<br />
while(&lt;FILE&gt;) { print $_; }</code></p>

<p>Still unclear? Alright, once more:</p>

<p style="margin-left: 40px; "><code>open(FILE, &quot;bla.txt&quot;);<br />
while($line = &lt;FILE&gt;) { print $line; }</code></p>

<p>Perl is developed by linguist Larry Wall, who likes to put all kinds of natural language things into Perl. <code>$_</code> refers to the subject of the sentence, it&#8217;s &quot;it&quot; as it were. <code>print</code> <code>$_</code>, or simply <code>print</code> means &quot;print it&quot;. How do we know this variable exists? We don&#8217;t. Unless we read the manual. Although they might be useful, magic variables like these are generally bad practice, it&#8217;s one of many reasons that Perl code is often called write only code.</p>

<p>PHP also has some magic variables whose behavior do not adhere to any usual rules, they are called super globals. In particular there are <code>$_POST</code> and <code>$_GET</code>. They do not adhere to the scoping rules defined in PHP.</p>

<p>I don&#8217;t know about you, but I like to see my variables declared. I like to see where they come from, are they local variables, parameters, or imported from a module that I can lookup? Magic variables are confusing, because they have different behavior than other variables in a language, they do not adhere to the usual rules.</p>

<p>As part of <a href="http://zef.me/2600/adia-a-week-with-clojure-and-mongodb">Adia</a>, I played around with Compojure, a Clojure web framework. Generally,&nbsp;<a href="http://www.compojure.org">Compojure</a> is a well-designed framework, but I came across one&nbsp;instance where it uses magic variables: in the <code>defroutes</code> macro. An example:</p>

<p style="margin-left: 40px; "><code>(defroutes&nbsp;webservice<br />
&nbsp;&nbsp;(GET &quot;/&quot;<br />
&nbsp;&nbsp; &nbsp; &nbsp; (str &quot;Hello, &quot;<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; (:name (:query-params request)))))</code></p>

<p>This defines a mapping from the &quot;/&quot; URI, to code to be executed when that URI is requested. As you can see, I use the variable&nbsp;<code>request</code>&nbsp;in this example. Upon inspection, it not clear where it comes from. At first, you may assume it&#8217;s a global that is dynamically bound (Clojure has dynamically scoped variables). But some refactoring of the code shows that this is not the case:</p>

<blockquote>
<p><code>(defn say-hello []<br />
&nbsp;&nbsp;(str &quot;Hello, &quot; (:name (:query-params request))))<br />
<br />
(defroutes&nbsp;webservice<br />
&nbsp;&nbsp;(GET &quot;/&quot;<br />
&nbsp;&nbsp; &nbsp; &nbsp; (say-hello)))</code></p>
</blockquote>

<p>This results in a &quot;symbol cannot be resolved&quot; error for the <code>request</code> variable. So clearly, <code>request</code> is not a dynamically bound variable either. So what is it, and where does it come from? I had to dig into the Compojure source code to find it, it is defined in the <code>with-request-bindings</code> macro, which defines some magic symbols: <code>params</code>, <code>cookies</code>, <code>session</code> and <code>flash</code> that are only accessible from inside the macro&#8217;s body:</p>

<p style="margin-left: 40px; "><code>(defmacro with-request-bindings<br />
&nbsp;&nbsp;&quot;Add shortcut bindings for the keys in a request map.&quot;<br />
&nbsp;&nbsp;[request &amp; body]<br />
&nbsp;&nbsp;`(let [~'request ~request<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ~'params &nbsp;(:params &nbsp;~'request)<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ~'cookies (:cookies ~'request)<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ~'session (:session ~'request)<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ~'flash &nbsp; (:flash &nbsp; ~'request)]<br />
&nbsp;&nbsp; &nbsp; ~@body))</code></p>

<p>I find this confusing and therefore bad practice. So, what is the alternative? It turns out there&#8217;s no perfect solution here, it&#8217;s all about trade-offs.</p>

<p>The problem magic variables try to solve is enabling quick access to data that is otherwise not accessible in a concise manner. In this case it could have been solved by declaring the request and other variables somewhere, for instance as parameters to&nbsp;<code>defroutes</code>:</p>

<p style="margin-left: 40px; "><code>(defroutes webservice [request params cookies session flash]<br />
&nbsp;&nbsp;...)</code></p>

<p>A reason not to go with this solution is likely to be its verbosity, nobody likes to write functions with a large number of arguments. A second alternative is only passing the <code>request</code> parameter and letting the user pull out the other from that map every time they need it. A reason not to go with that solution is user inconvenience, users likely want quick access to all five of these values and don&#8217;t want to look them up in the <code>request</code> map every time. A third alternative is using dynamically bound global variables. In Clojure these can be bound to a new value only for a certain thread within a certain code execution path:</p>

<blockquote>
<p><code>(def request nil) ; root binding is nil<br />
</code><code><br />
(defn print-request []<br />
&nbsp;&nbsp;(println request))<br />
<br />
...<br />
(binding [request (build-request ...)] ; rebind<br />
&nbsp;&nbsp;(print-request) ; prints request<br />
&nbsp;&nbsp;...))</code></p>
</blockquote>

<p>I use them in <a href="http://github.com/zefhemel/adia">Adia</a> for access to the request, post and get parameters. For this I declare 3 variables in the <code>adia.web</code> module:</p>

<p style="margin-left: 40px; "><code>(def *request* nil)<br />
(def *form* nil)<br />
(def *query* nil)</code></p>

<p>Values have been dynamically bound to their respective values by the time they are used within a webfn:</p>

<p style="margin-left: 40px; "><code>(defwebfn say-hello []<br />
&nbsp;&nbsp;(str &quot;Hello, &quot; (:name *query*)))</code></p>

<p>My thinking is that by using the <code>*name*</code> convention, it is at least clear these are not normal locally defined variables, they are different. Secondly, they are only available if you import the <code>adia.web</code> module and are part of that module&#8217;s interface, i.e. you can look up their declaration. What is still not clear is where their value comes from, but I suppose the user will have to abstract from that. The alternative to this approach would be to pass these variables as parameters to every webfn, but I decided against this because it would make writing webfn defintions too verbose. It was also not very clear what the syntax should have been:&nbsp;<code>(defwebfn fn-name request form query [arg1 type arg2 type] ...)</code>?<code> (defwebfn fn-name [request form query] [arg1 type arg2] ...)</code>? Neither of these options seemed very elegant to me, which is why I decided to be pragmatic and go with dynamically scoped globals.</p>

<p>I think this is an acceptable compromise. While the five globals are essentially still input parameters, they do not have to be passed around all the time. However, if you invoke a webfn outside a path where values are bound to the <code>*request*</code>, <code>*form*</code> and <code>*query*</code> variables, you are likely to receive <code>NullPointerException</code>s.</p>

<p><em>As a general rule:</em> to keep programs readable and comprehensible, it should be easy to see where your variables and symbols come from. Are they local variables, parameters, globals? Magic variables should be avoided if possible.</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/XU_bKEgD0No" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2650/on-language-design-magic-variables-in-compojure/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		<feedburner:origLink>http://zef.me/2650/on-language-design-magic-variables-in-compojure</feedburner:origLink></item>
		<item>
		<title>On Language Design: My Problem With ClojureQL</title>
		<link>http://feedproxy.google.com/~r/zefme/~3/7j9ovrJOktE/on-language-design-my-problem-with-clojureql</link>
		<comments>http://zef.me/2637/on-language-design-my-problem-with-clojureql#comments</comments>
		<pubDate>Mon, 04 Jan 2010 10:10:36 +0000</pubDate>
		<dc:creator>Zef</dc:creator>
				<category><![CDATA[Language Design]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[dsl]]></category>
		<category><![CDATA[objective-c]]></category>

		<guid isPermaLink="false">http://zef.me/?p=2637</guid>
		<description><![CDATA[Every programming language comes with a certain syntax, a certain feel for what feels like native use of that syntax, and the semantics of the syntax. Escapes and mixing with a completely different feeling language are generally not a good idea. My favorite example of this is Objective-C, which is a really strange mixture of [...]]]></description>
			<content:encoded><![CDATA[<p>Every programming language comes with a certain syntax, a certain <em>feel</em> for what feels like native use of that syntax, and the semantics of the syntax. Escapes and mixing with a completely different feeling language are generally not a good idea. My favorite example of this is Objective-C, which is a really strange mixture of C and Smalltalk. C as you will know is a curly brace language, it has a way of doing things. It&#8217;s a low-level system programming language. Smalltalk is a high-level programming language that feels very different and looks very different.</p>

<p>Objective-C is C with some Smalltalk bolted on to it, which gives it a strange feel:</p>

<p style="margin-left: 40px; "><code>MyObject* o = [[MyObject alloc] initWithNum:&nbsp;20                  andString:&nbsp;@&quot;Hello world!&quot;];</code></p>

<p>In C, a function call has the syntax <code>function_name(arg1, arg2)</code>. However, when moving into Objective-C object land, a method call looks like:&nbsp;<code>[object aMethodCall: arg1 andArg: arg2]</code>. Alien, if you ask me.</p>

<p>In Lisp land, an example of this is the common-lisp loop macro:</p>

<p><code>(loop for x in '(a b c d e)<br />
</code><code>&nbsp;&nbsp; &nbsp; &nbsp;for y from 1<br />
&nbsp;&nbsp; &nbsp; &nbsp;if (&gt; y 1)       do<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;(format t &quot;, ~A&quot; x)<br />
&nbsp;&nbsp; &nbsp; &nbsp;else do<br />
&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;(format t &quot;~A&quot; x))</code></p>

<p>If you&#8217;ve ever written any Lisp code, you&#8217;ll see that although this is very readable and concise, like Objective-C, by the way, it feels completely weird in a Lisp-style language.</p>

<p>I have a similar problem with <a href="http://www.bestinclass.dk/index.php/2009/12/clojureql-where-are-we-going/">ClojureQL</a>, a query language for <a href="http://www.clojure.org">Clojure</a>. Queries expressed in ClojureQL change the meaning of Clojure in a way that I feel is bad language design because it it breaks assumptions that hold true for the rest of Clojure.</p>

<p>Consider the following snippet of code:</p>

<p style="margin-left: 40px; "><code>(let [first-name &quot;zef&quot;]<br />
&nbsp;&nbsp; ...<br />
&nbsp;&nbsp; (= first-name &quot;zef&quot;) ...)</code></p>

<p>This piece of code binds the value &quot;zef&quot; to the symbol <code>first-name</code>. The programmer&#8217;s expectation is that when the <code>first-name</code> symbol is used anywhere within the <code>let</code>, its value will be &quot;zef&quot;, unless it is rebound to something else with another <code>let</code>. However, this assumption breaks when using ClojureQL:</p>

<p style="margin-left: 40px; "><code>(let [first-name &quot;zef&quot;]<br />
&nbsp;&nbsp;(query users * (= fname first-name)))</code></p>

<p>This is legal in ClojureQL, although it is a bit unclear where <code>fname</code> would come from, it comes from the <code>*</code> there, we can make this more explicit:</p>

<p style="margin-left: 40px; "><code>(let [first-name &quot;zef&quot;]<br />
&nbsp;&nbsp;(query users [fname lname] (= fname first-name)))</code></p>

<p>This is perfectly valid ClojureQL code, except it doesn&#8217;t do what you would expect it to do. It does not find all users with first name &quot;zef&quot;, no, it will throw an SQL exception saying that the table users does not have a field &quot;first-name&quot;. Huh?</p>

<p>It turns that when we use the query macro, we step into a different world, a world where we have to let our previous assumptions go. When <code>first-name</code> is used, it no longer refers to the value bound to it before, instead it&#8217;s simply a name referring to a column in a table. It is still possible to escape to &quot;normal&quot; Clojure semantics by escaping back into the Clojure world with a ~ prefix:</p>

<p style="margin-left: 40px; "><code>(let [first-name &quot;zef&quot;]<br />
&nbsp;&nbsp;(query users [fname lname] (= fname ~first-name)))</code></p>

<p>I&#8217;m not very fond of this type of language design. It would probably be better if a ~ would not be necessary, in that case you could read the query as a kind for loop where each result row is destructured and bound to [fname lname], which are then used in the body expression. However, still, intuitively in this interpretation the names of <code>fname</code> and <code>lname</code> should not refer to column names in the users table, but instead are only to be used for binding in the code, referring to the first and second column in the result set. Still confusing.</p>

<p>A syntax that is more Clojuresque, if you will, albeit more verbose would be:</p>

<p style="margin-left: 40px; "><code>(let [first-name &quot;zef&quot;]<br />
&nbsp;&nbsp;(query [u users] (= (:fname u) first-name)))</code></p>

<p>Intuitively, the query iterates over all users binding each user to <code>u</code> and filtering on the value of the <code>:fname</code> key of each user entry. I&#8217;m still not confortable with the use of <code>users</code> there, which seems some type of magic symbol, but I suppose that could be fixed too. Maybe of having a <code>(deftable users)</code> statement somewhere else in the code, or replacing with with <code>(table :users)</code>, which, again, would make it slightly more verbose:</p>

<p style="margin-left: 40px; "><code>(let [first-name &quot;zef&quot;]<br />
&nbsp;&nbsp;(query [u (table :users)] (= (:fname u) first-name)))</code></p>

<p>The point is that <strong>with great power comes great responsibility</strong>. The macro facilities of Lisps give you enormous power to create your own language extensions, which is great. It makes experimenting with languages very easy. However, it turns out that language design is very difficult. The language syntax is the user interface of your language. Whereas typical languages like Java and C# evolve very slowly and are designed by experienced language designers, in a Lisp anybody can do it, which can result in very confusing abstractions.</p>

<p>Abstractions like these have to be designed very, very carefully.</p>
<img src="http://feeds.feedburner.com/~r/zefme/~4/7j9ovrJOktE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://zef.me/2637/on-language-design-my-problem-with-clojureql/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://zef.me/2637/on-language-design-my-problem-with-clojureql</feedburner:origLink></item>
	</channel>
</rss><!-- WP Super Cache is installed but broken. The path to wp-cache-phase1.php in wp-content/advanced-cache.php must be fixed! -->
