<?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>ILoggable</title>
	
	<link>http://www.claassen.net/geek/blog</link>
	<description>A place to keep my thoughts on programming</description>
	<lastBuildDate>Sun, 11 Mar 2012 05:05:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/Iloggable" /><feedburner:info uri="iloggable" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Ducks Unlimited</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/tUJG1nzSrhA/ducks-unlimited.html</link>
		<comments>http://www.claassen.net/geek/blog/2012/03/ducks-unlimited.html#comments</comments>
		<pubDate>Sun, 11 Mar 2012 05:05:11 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1565</guid>
		<description><![CDATA[Most complaints levied against static type systems come down to verbosity and complexity required to express intent, all of which are usually the fault of the language not of type system. Type inference, parametric types, etc. are all refinements to make type systems more fluid and, err, dynamic. One language capability that reduces a lof [...]]]></description>
			<content:encoded><![CDATA[<p>Most complaints levied against static type systems come down to verbosity and complexity required to express intent, all of which are usually the fault of the language not of type system. Type inference, parametric types, etc. are all refinements to make type systems more fluid and, <em>err</em>, dynamic.</p>
<p>One language capability that reduces a lof of ceremony is statically verifiable <em>duck-typing</em>. While interfaces are the usual approach to letting independent implementations serve the same role,&nbsp;it always bugs me that <a href="http://www.claassen.net/geek/blog/2009/06/interfaces-put-contract-at-wrong-end-of.html" target="_blank">interfaces put the contract at the wrong end of the dependency</a>, i.e. I have to implement your interface in order for you to recognize that I can <em>quack!</em></p>
<p>I had hoped that C# 4.0&#39;s dynamic keyword would fix this, but this is the best you can do:</p>
<pre class="brush: csharp">public class AVerySpecialDuck {
  public void Quack() {
    Console.Writeline(&quot;quack&quot;);
  }
}

public class DuckFancier {
  public void GimmeADuck(dynamic duck) {
    duck.Quack();
  }
}

new DuckFancier().GimmeADuck(new AVerySpecialDuck());</pre>
<p>Sure, I can now call <code>.Quack()</code>&nbsp;without having to require a concrete type or even an interface, but I also could have provided a rabbit to <code>GimmeADuck</code> without compilation errors. And as the user of <code>GimmeADuck</code> there is no machine discoverable way to determine what it expects.</p>
<p>I solved half of this problem with <a href="http://www.claassen.net/geek/blog/2010/01/duckpond-lightweight-duck-typing-for-c.html" target="_blank">Duckpond</a>:</p>
<pre class="brush: csharp">public interface IQuacker {
  void Quack();
}
</pre>
<pre class="brush: csharp">public class DuckFancier {
  public void GimmeADuck(IQuacker duck) {
    duck.Quack();
  }
}

new DuckFancier().GimmeADuck(new AVerySpecialDuck().AsImplementationOf&lt;IQuacker&gt;<iquacker>());</iquacker></pre>
<p>Yes, this is back to interfaces to give us discoverability, but with <code>AsImplementationOf&lt;T&gt;</code>, any class with <code>Quack()</code> could be turned into that interface without ever knowing about it. However, whether I satisfy that contract is still a runtime check.</p>
<h2>Duck, Duck, <em>go</em></h2>
<p>What I really want is what <em>go</em> does:</p>
<pre class="brush: csharp">type Quacker interface {
  Quick();
}

func GimmeADuck(Quacker duck) {
  duck.Quack();
}
</pre>
<p>I.e. true <em>duck-typing</em>. If the type provided satisfies the contract, it can get passed in and the compiler makes sure. Unfortunately, other than this feature&nbsp;<em>go</em> doesn&#39;t entice me all that much.</p>
<h2>By trait or structure</h2>
<p>A language that&#39;s a bit more after my own heart than <em>go</em>&nbsp;and has even greater flexibility in regards to <em>duck-typing</em> is <em>scala</em>. It&nbsp;actually provides two different approaches to this problem.</p>
<p>The first is a <em>structural type</em>, which uses function literals to define the contract for an expected argument type:</p>
<pre class="brush: csharp">class AVerySpecialDuck {
  def quack() = println(&quot;Quack!&quot;)
}

object DuckFancier {
  type Quacker = { def quack() }
  def GimmeADuck(Quacker duck) = duck.quack()
}

DuckFancier.GimmeADuck(new AVerySpecialDuck())</pre>
<p>A structural type is simply a contract of what methods a type should have in order to satisfy the constraints. In this case the singleton <code>DuckFancier</code> defines the structural type <code>Quacker</code> as any object with a <code>quack</code> method.</p>
<p>The second way we could have achieved this is with a<em> trait</em> bound to an instance:</p>
<pre class="brush: csharp">class AVerySpecialDuck {
  def quack() = println(&quot;Quack!&quot;)
}

trait Quacker {
  def quack : Unit
}

object DuckFancier {
  def GimmeADuck(Quacker duck) = duck.quack()
}

val duck = new AVerySpecialDuck extends Quacker
DuckFancier.GimmeADuck(duck);</pre>
<p>A <em>trait</em> is basically an Interface with an optional implementation (think Interface plus extension methods), but in this case I&#39;m treating it purely as an interface to take advantage of&nbsp;<em>scala</em>&#39;s ability to attach a trait to an instance. This lets me add the contract on when used rather than at class definition.</p>
<p><em>Duck-typing</em> in statically typed languages allows for syntax that can be concise and still statically verifiable and discoverable, avoiding the usual ceremony and coupling that inheritance models impose. It&#39;s a feature I hope more languages adopt and along with type inference is invalidating a lot of the usual gripes levied at static typing.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/tUJG1nzSrhA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2012/03/ducks-unlimited.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2012/03/ducks-unlimited.html</feedburner:origLink></item>
		<item>
		<title>Implicits instead of Extension Methods?</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/gVSQUolPqjg/implicits-instead-of-extension-methods.html</link>
		<comments>http://www.claassen.net/geek/blog/2012/01/implicits-instead-of-extension-methods.html#comments</comments>
		<pubDate>Wed, 11 Jan 2012 02:30:15 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[geek]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1570</guid>
		<description><![CDATA[After the latest round of scala is teh complex, I started thinking a bit more about the similar roles implicit conversions in scala play to extension methods in C#. I can&#39;t objectively comment on whether Extension Methods are simpler (they are still a discoverability issue), but I can comment that the idea of implicit conversion [...]]]></description>
			<content:encoded><![CDATA[<p>After the latest round of <a href="http://yz.mit.edu/wp/true-scala-complexity/"><em>scala is teh complex</em></a>, I started thinking a bit more about the similar roles implicit conversions in scala play to extension methods in C#. I can&#39;t objectively comment on whether Extension Methods are simpler (they are still a discoverability issue), but I can comment that the idea of implicit conversion to attach new functionality to existing code really intrigued me. It does seem less obvious but also a lot more powerful.</p>
<p>Then i thought, <em>wait, <strong>C# has implicit.. Did they just invent extension methods without needing to</strong></em>? I&#39;ve never used implicit conversion in C# for anything but automatic casting, but maybe I was just not imaginative enough. So here goes nothing:</p>
<pre class="brush: csharp">public class RichInt {
  public readonly int Value;

  public static implicit operator RichInt(int i) {
    return new RichInt(i);
  }

  public static implicit operator int(RichInt i) {
    return i.Value;
  }

  private RichInt(int i) {
    Value = i;
  }

  public IEnumerable&lt;int&gt; To(int upper) {
    for(int i = Value;i&lt;=upper;i++) {
      yield return i;
    }
  }
}</pre>
<p>Given the above I was hoping I could mimic&nbsp;<em>scala</em>&#39;s <code>RichInt</code> <code>to()</code> method and write code like this:</p>
<pre class="brush: csharp">foreach(var i in 10.To(20)) {
  Console.WriteLine(i);
}</pre>
<p class="brush: csharp"><em>Alas</em> that won&#39;t compile. Implicit conversion only works on assignment, so i had to write</p>
<pre class="brush: csharp">foreach(var i in ((RichInt)10).To(20)) {
  Console.WriteLine(i);
}</pre>
<p>So I do have to use an extension method to create <code>To()</code> in C#.</p>
<p>And, yes, i&#39;m grossly simplifying what<em> scala</em>&#39;s implicts can accomplish. Also, I wish I could have block scope <code>using</code>&nbsp; statements to import extension methods for just a block the way <em>scala</em>&#39;s import allows you to handle local scope implicits.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/gVSQUolPqjg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2012/01/implicits-instead-of-extension-methods.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2012/01/implicits-instead-of-extension-methods.html</feedburner:origLink></item>
		<item>
		<title>Node 0.6.x &amp; AWS EC2 Micro troubles</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/WBL8ruMNEqU/node-0-6-x-aws-ec2-micro-troubles.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/12/node-0-6-x-aws-ec2-micro-troubles.html#comments</comments>
		<pubDate>Wed, 28 Dec 2011 17:59:14 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[node.js]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1557</guid>
		<description><![CDATA[Tried to upgrade node from 0.4.5 to 0.6.x and my my micro kept falling over dead. I know it&#39;s an edge case, but it&#39;s an annoying set of symptoms that I figured I should post in case someone else runs into the same issue. tl;dr => It&#39;s not a node problem its an AWS kernel [...]]]></description>
			<content:encoded><![CDATA[<p>Tried to upgrade node from 0.4.5 to 0.6.x and my my micro kept falling over dead. I know it&#39;s an edge case, but it&#39;s an annoying set of symptoms that I figured I should post in case someone else runs into the same issue.</p>
<p><strong>tl;dr</strong> => <em>It&#39;s not a node problem its an <a href="https://aws.amazon.com/amazon-linux-ami/latest-release-notes/" target="_blank">AWS kernel issue with old AWS AMIs and Micro instances</a></em></p>
<p>So I have a micro that&#39;s about a year old, i.e. beta AWS-AMI, but i gather the same problem happens with pretty much every AMI prior to 2011.09. I was running node 0.4.5, but had started using 0.6.4 on my dev and some modules were now dependent on it. Since micro instances go into throttle mode when building anything substantial, i hope to use the build from my dev server. The dev machine is centos, so i crossed my fingers, copied the build over and ran make install. No problem. Then i tried <code>npm install -g supervisor</code> and it locked up. Load shot up, the process wouldn&#39;t let itself be killed and i got a syslogd barf all over my console:</p>
<pre>Message from syslogd@ at Wed Dec 28 00:58:19 2011 ...
ip-**-**-**-** klogd: [  440.293407] ------------[ cut here ]------------
ip-**-**-**-** klogd: [  440.293418] invalid opcode: 0000 [#1] SMP
ip-**-**-**-** klogd: [  440.293424] last sysfs file: /sys/kernel/uevent_seqnum
ip-**-**-**-** klogd: [  440.293501] Process node (pid: 1352, ti=e599c000 task=e60371a0 task.ti=e599c000)
ip-**-**-**-** klogd: [  440.293508] Stack:
ip-**-**-**-** klogd: [  440.293545] Call Trace:
ip-**-**-**-** klogd: [  440.293589] Code: ff ff 8b 45 f0 89 ....
ip-**-**-**-** klogd: [  440.293644] EIP: [<c108e4fb>] exit_mmap+0xd5/0xe1 SS:ESP 0069:e599cf08</c108e4fb></pre>
<p>So i killed the instance. Figuring it was config diffs between centos and the AMI, i cloned my live server and fired it up as a small to get decent build perf. Tested 0.6.4, all worked, brought it back up as a micro and, <em>blamo</em>, same death spiral. Back to small instance, tried 0.6.6 and and once again as a small instance it worked, but back as a micro it still had the same problem.</p>
<p>Next up was a brand new AMI, build node 0.6.6 and run as micro. Everything was happy. So it must be something that&#39;s gotten fixed along the way. Back to the clone and <code>yum upgrade</code>. Build node, try to run, death spiral. <em>Argh</em>! So finally i thought i&#39;d file a ticket with node.js, but first looked through existing issues and found this:</p>
<p><a href="https://github.com/joyent/node/issues/2271" target="_blank">Node v0.6.3 crashes EC2 instance</a></p>
<p>which pointed me at the <a href="https://aws.amazon.com/amazon-linux-ami/latest-release-notes/" target="_blank">relevant Amazon release notes</a> which had this bit in it:</p>
<blockquote>
<p><b style="color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">After using&nbsp;<code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">yum</code>&nbsp;to upgrade to Amazon Linux AMI 2011.09, t1.micro 32-bit instances fail to reboot.</b></p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">&nbsp;</p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">There is a bug in PV-Grub that affects the handling of memory pages from Xen on 32bit t1.micro instances. A new release of PV-Grub has been released to fix this problem. Some manual steps need to be performed to have your instance launch with the new PV-Grub.</p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">As of 2011-11-01, the latest version of the PV-Grub Amazon Kernel Images (AKIs) is 1.02. Find the PV-Grub AKI&#39;s for your given region by running:</p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; "><code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">ec2-describe-images -o amazon --filter &quot;manifest-location=*pv-grub-hd0_1.02-i386*&quot; --region REGION</code>.</p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">Currently running instances need to be stopped before replacing the AKI. The following commands point an instance to the new AKI:</p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; "><code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">ec2-stop-instance --region us-east-1 i-#####</code>&nbsp;<br />
		<code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">ec2-modify-instance-attribute --kernel aki-805ea7e9 --region us-east-1 i-#####</code>&nbsp;<br />
		<code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">ec2-start-instance --region us-east-1 i-#####</code>.</p>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">If launching a custom AMI, add a&nbsp;<code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">--kernel</code>&nbsp;parameter to the&nbsp;<code style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: monospace; line-height: 12px; ">ec2-run-instances</code>&nbsp;command or choose the AKI in the kernel drop-down of the console launch widget.</p>
</blockquote>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">Following these instructions finally did the trick and 0.6.6 is happily running on my old micro instance. Hope this helps someone else get this resolved more smoothly.</p>
<blockquote>
<p style="margin-top: 0px; margin-right: 0px; margin-bottom: 1em; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; color: rgb(0, 0, 0); font-family: verdana, arial, helvetica, clean, sans-serif; line-height: 18px; text-align: left; ">&nbsp;</p>
<p>&nbsp;</p>
</blockquote>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/WBL8ruMNEqU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/12/node-0-6-x-aws-ec2-micro-troubles.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/12/node-0-6-x-aws-ec2-micro-troubles.html</feedburner:origLink></item>
		<item>
		<title>Whopper of a javascript extension</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/9HQLhMKMIQ8/whopper-of-a-javascript-extension.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/09/whopper-of-a-javascript-extension.html#comments</comments>
		<pubDate>Wed, 21 Sep 2011 06:11:50 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[lisp]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1537</guid>
		<description><![CDATA[I consider the start of my programming carreer to be when I learned Genera LISP on Symbolics LISP machines. Sure I had coded in Basic, Pascal and C, and unfortunately Fortran, before this, but it had always just been a hobby. With LISP, I got serious about languages, algorithms, etc. Genera LISP had its own [...]]]></description>
			<content:encoded><![CDATA[<p>I consider the start of my programming carreer to be when I learned Genera LISP on <a href="http://en.wikipedia.org/wiki/Symbolics" target="_blank">Symbolics LISP machines</a>. Sure I had coded in Basic, Pascal and C, and unfortunately Fortran, before this, but it had always just been a hobby. With LISP, I got serious about languages, algorithms, etc.</p>
<p>Genera LISP had its own object system called <strong>Flavors</strong>, much of which eventually made it into CLOS, the Common Lisp Object System. <strong>Flavors</strong> had capabilities called <a href="http://www.franz.com/support/documentation/8.1/doc/flavors.htm#12.0%20Wrappers%20and%20whoppers" target="_blank">Wrappers and Whoppers</a>, which provided aspect oriented capabilities before that term was even coined. Both achieved fundamentally the same goals, to wrap a function call with pre and post conditions, including preventing the underlying function call from occuring. <strong>Wrappers</strong> achieved this via LISP macros, i.e. the calls they wrapped were compiled into new calls, each call using the same wrapper sharing zero code. <strong>Whoppers</strong> did the same thing except dynamically, allowing the sharing of whopper code, but also requiring at least two additional function calls at runtime for every whopper.</p>
<p>So what&#39;s all this got to do with javascript? Well, yesterday I got tired of repeating myself in some CPS node coding and just turn my continuation into a new continuation wrapped with my common post condition, and so I wrote the <strong>Whopper</strong> capability for javascript.&nbsp;But first a detour through CPS land and how it can force you to violate DRY.</p>
<h2>CPS means saying the same thing multiple times</h2>
<p>So in a normal synchronous workflow you might have some code like this:</p>
<pre class="brush: javascript">function getManifest(refresh) {
  if(!refresh &#038;&#038; _manifest) {
    return _manifest;
  }
  var manifest = fetchManifest();
  if(!_manifest) {
    var pages = getPages();
    _manifest = buildManifest(pages);
  } else {
    _manifest = manifest;
    if(refresh) {
      var pages = getPages();
      updateManifest(pages);
    }
  }
  saveManifest(manifest);
  return _manifest;
};
</pre>
<p>But with CPS style asynchrony you end up with this instead:</p>
<pre class="brush: javascript">function getManifest(refresh, continuation, err) {
&nbsp; if(!refresh &#038;&#038; _manifest) {
&nbsp;&nbsp;&nbsp; continuation(_manifest);
&nbsp;&nbsp;&nbsp; return;
&nbsp; }
&nbsp; fetchManifest(function(manifest) {
&nbsp;&nbsp;&nbsp; if(!_manifest) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; getPages(function(pages) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _manifest = buildManifest(pages);
&nbsp;&nbsp;&nbsp;&nbsp;    saveManifest(_manifest,function() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     continuation(_manifest);
&nbsp;&nbsp;&nbsp;     });
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }, err);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return;
&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; _manifest = manifest;
&nbsp;&nbsp;&nbsp; if(refresh) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; getPages(function(pages) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; updateManifest(pages);
&nbsp;&nbsp;&nbsp;     saveManifest(_manifest,function() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     continuation(_manifest);
&nbsp;&nbsp;&nbsp;     });
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }, err);
&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;   saveManifest(_manifest,function() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;   continuation(_manifest);
&nbsp;&nbsp;&nbsp;   });
&nbsp;&nbsp;&nbsp; }
&nbsp; }, err);
};
</pre>
<p>Because the linear flow is interrupted by asynchronous calls with callbacks, our branches no longer converge, so the common exit condition, <em>saveManifest &#038; return the manifest</em>, is repeated 3 times.</p>
<p>While I can&#39;t stop the repetition entirely, I could at least reduce it by capturing the common code into a new function. But even better, how about I wrap the original continuation with the additional code so that I can just call the continuation and it runs the save as a precondition:</p>
<pre class="brush: javascript">function getManifest(refresh, continuation, err) {
&nbsp; if(!refresh &#038;&#038; _manifest) {
&nbsp;&nbsp;&nbsp; continuation(_manifest);
&nbsp;&nbsp;&nbsp; return;
&nbsp; }
&nbsp; continuation = continuation.wrap(function(c, manifest) { saveManifest(manifest, c); });
&nbsp; fetchManifest(function(manifest) {
&nbsp;&nbsp;&nbsp; if(!_manifest) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; getPages(function(pages) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; _manifest = buildManifest(pages);
&nbsp;&nbsp;&nbsp;&nbsp;    continuation(_manifest);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }, err);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return;
&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp; _manifest = manifest;
&nbsp;&nbsp;&nbsp; if(refresh) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; getPages(function(pages) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; updateManifest(pages);
&nbsp;&nbsp;&nbsp;     continuation(_manifest);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }, err);
&nbsp;&nbsp;&nbsp; } else {
      continuation(_manifest);
&nbsp;&nbsp;&nbsp; }
&nbsp; }, err);
};</pre>
<h2>Finally! The wrap function&#8230;</h2>
<p>What makes this capture possible is this extension to the Function prototype:</p>
<pre class="brush: javascript">Object.defineProperty(Function.prototype, &quot;wrap&quot;, {
&nbsp; enumerable: false,
&nbsp; value: function(wrapper) {
&nbsp;&nbsp;&nbsp; var func = this;
&nbsp;&nbsp;&nbsp; return function() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var that = this;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var args = arguments;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var argsArray = [].slice.apply(args);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var funcCurry = function() {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; func.apply(that, args);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; };
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; argsArray.unshift(funcCurry);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; wrapper.apply(that, argsArray);
&nbsp;&nbsp;&nbsp; };
&nbsp; }
});
</pre>
<p>It rewrites the function as a new function that when called will call the passed wrapper function with a curried version of the original function and the arguments passed to the function call. This allows us to wrap any pre or post conditions, including pre-conditions that initiate asynchronous calls themselves, and even lets the wrapper function inspect the arguments that the original function will be passsed (assuming the wrapper decides to call it via the curried version.</p>
<pre class="brush: javascript">&nbsp; continuation = continuation.wrap(function(c, manifest) {
&nbsp;&nbsp;&nbsp; saveManifest(manifest, c);
&nbsp; });
</pre>
<p>The above overwrite the original <code>continuation</code> with a wrapper version of itself. The wrapper is passed <code>c</code>, the curried version of the original function and the argument that <code>continuation</code> is called with, which we know will be the manifest. The wrapper in turn calls the async function <code>saveManifest</code> with the passed manifest and passes the curried <code>continuation</code> as its continuation. So when we call <code>continuation(_manifest)</code>, first <code>saveManifest</code> is called which then calls the original continuation with the <code>_manifest</code> argument as well.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/9HQLhMKMIQ8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/09/whopper-of-a-javascript-extension.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/09/whopper-of-a-javascript-extension.html</feedburner:origLink></item>
		<item>
		<title>Building emacs-23 on AWS Linux AMI to get jade-mode</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/GdMms_grP8g/building-emacs-23-on-aws-linux-ami-to-get-jade-mode.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/09/building-emacs-23-on-aws-linux-ami-to-get-jade-mode.html#comments</comments>
		<pubDate>Tue, 13 Sep 2011 06:03:26 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>
		<category><![CDATA[aws]]></category>
		<category><![CDATA[emacs]]></category>
		<category><![CDATA[linux]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1533</guid>
		<description><![CDATA[So there I was trying to get jade-mode running and it kept dropping into fundamental mode. The error it gave in *Messages* was: File mode specification error: (void-function whitespace-mode) Problem was i was running emacs-22.2.3, the latest in centos and thereby the AWS Linux AMI. And whitespace-mode, the major mode that jade-mode and stylus-mode rely [...]]]></description>
			<content:encoded><![CDATA[<p>So there I was trying to get <code>jade-mode</code> running and it kept dropping into fundamental mode. The error it gave in <code>*Messages*</code> was:</p>
<pre>File mode specification error: (void-function whitespace-mode)</pre>
<p>Problem was i was running <em>emacs-22.2.3</em>, the latest in centos and thereby the AWS Linux AMI. And <code>whitespace-mode</code>, the major mode that <code>jade-mode</code> and <code>stylus-mode</code> rely on requires <em>emacs-23</em>. Fine, tell me what repo to add and let me get on with my life. What, no rpm&#39;s?</p>
<p>That&#39;s where i usually draw the line and say to myself that it&#39;s something that i probably don&#39;t need. Over the years, i&#39;ve developed an aversion to building from source, if only because then i have software on my machine that other rpm&#39;s can&#39;t count on as pre-requisites. But this time, that wasn&#39;t gonn fly. I wanted <code>jade-mode</code>!</p>
<p>As my usual build recipies go, this is what i had to do on an existing AWS Linux AMI, so some of the yum deps are missing. Don&#39;t worry, when you run <code>./configure</code> it&#39;ll bitch and it&#39;ll usually be some <code>*-devel</code> package. So here goes building from source:</p>
<pre>yum -y install ncurses-devel
cd /tmp
wget http://ftp.gnu.org/pub/gnu/emacs/emacs-23.3a.tar.gz
tar zxf emacs-23.3a.tar.gz
cd emacs-23.3
./configure --prefix=/usr/local --with-xpm=no
make
make install</pre>
<div>Done!</div>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/GdMms_grP8g" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/09/building-emacs-23-on-aws-linux-ami-to-get-jade-mode.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/09/building-emacs-23-on-aws-linux-ami-to-get-jade-mode.html</feedburner:origLink></item>
		<item>
		<title>Using log4net without requiring it as a dependency</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/Ywvcye-ESeY/using-log4net-without-requiring-it-as-a-dependency.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/08/using-log4net-without-requiring-it-as-a-dependency.html#comments</comments>
		<pubDate>Mon, 15 Aug 2011 18:48:18 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dependency]]></category>
		<category><![CDATA[log4net]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1520</guid>
		<description><![CDATA[Logging, to me, is a basic requirement of any code I write. There&#39;s nothing more useful to track down an odd bug than being able to turn on debug logging in production, potentially filter it down to the area of interest and get some real live data. When that code is causing trouble at a [...]]]></description>
			<content:encoded><![CDATA[<p>Logging, to me, is a basic requirement of any code I write. There&#39;s nothing more useful to track down an odd bug than being able to turn on debug logging in production, potentially filter it down to the area of interest and get some real live data. When that code is causing trouble at a customer location, this capability becomes worth its weight in gold.</p>
<p>And while I am a big Interface abstraction and IoC nut, logging is so fundamental to me that I do use a static logger instance in every class and just have a hard requirement for log4net. I just want this to work and not have people worry about having to inject an ILog into my classes, forcing them to think about a concern of mine. It&#39;s far less obtrusive this way, imho.</p>
<p>But it does mean that no matter how small and compact my code is, i suddenly tack on a ~240KB dll requirement, often several times larger than my own code. And there goes my &quot;i don&#39;t want them to worry about a concern of mine&quot; out the window.</p>
<h2>Depending on log4net only when it&#39;s there</h2>
<p>That got me thinking about how I can avoid this dependency. I knew that if my code path doesn&#39;t hit a code in a referenced DLL, the absense of the DLL does not cause a problem. Of course that means i can&#39;t even reference their interfaces.</p>
<p>Instead I had to create a duplicate of the log4net ILog interface and proxy my calls to it. The result is a single file, Logger.cs with the following wire-up:</p>
<pre class="brush: csharp">internal static class Logger {

  private static readonly bool _loggingIsOff = true;

  static Logger() {
    try {
        Assembly.Load(&quot;log4net&quot;);
        _loggingIsOff = false;
    } catch {}
  }

  public static ILog CreateLog() {
    var frame = new System.Diagnostics.StackFrame(1, false);
    var type = frame.GetMethod().DeclaringType;
    return _loggingIsOff ? (ILog)new NoLog() : new Log4NetLogger(type);
  }
  ...
}
</pre>
<p>(<a href="https://github.com/sdether/DReAM/blob/traum/src/traum/mindtouch.traum.webclient/Logger.cs" target="_blank">Full code is here</a>)</p>
<p>Because it&#39;s not supposed to create a dependency, it&#39;s marked internal. Yes, that means that every assembly has a copy of it, but that&#39;s really not significant in the grand scheme of things. In returns for a couple of redundant bytes, I can now do add a logger to every class simply with:</p>
<pre class="brush: csharp">private static readonly Logger.ILog _log = Logger.CreateLog();</pre>
<p>And if log4net is present and configured, commence the flow of debug statements. Meanwhile I can ship my code without the log4net DLL.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/Ywvcye-ESeY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/08/using-log4net-without-requiring-it-as-a-dependency.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/08/using-log4net-without-requiring-it-as-a-dependency.html</feedburner:origLink></item>
		<item>
		<title>Simple Immutable objects</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/Lm7-Wz1zhyE/simple-immutable-objects.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/07/simple-immutable-objects.html#comments</comments>
		<pubDate>Sat, 23 Jul 2011 21:48:03 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[.net]]></category>
		<category><![CDATA[immutability]]></category>
		<category><![CDATA[monospace]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1515</guid>
		<description><![CDATA[I&#39;m currently at #monospace and over lunch was discussing message passing with @ackenpacken and @briandonahue. I was lamenting that to create an immutable object in C# was just a lot harder than a mutable one. You either have to create a builder of sorts or create very verbose constructors and never mind trying to derive [...]]]></description>
			<content:encoded><![CDATA[<p>I&#39;m currently at <a href="http://monospace.us/" target="_blank">#monospace</a> and over lunch was discussing message passing with <a href="http://twitter.com/#!/ackenpacken" target="_blank">@ackenpacken</a> and <a href="http://twitter.com/#!/briandonahue" target="_blank">@briandonahue</a>. I was lamenting that to create an immutable object in C# was just a lot harder than a mutable one. You either have to create a builder of sorts or create very verbose constructors and never mind trying to derive a new immutable instance with just one field changed. I suggested that if only private setters could be used with object initializers, this would be solved and realized that I could just use anonymous objects as my initializers and so after finishing with talks for the day I coded up a proof of concept.</p>
<pre class="brush: csharp">// create a new data class
public class Person {
  public int Id { get; private set; }
  public string Name { get; private set; }
}</pre>
<p class="brush: csharp">So this is a perfectly good immutable object. So good, we can&#39;t even initialize it. Enter <code>Droog.ImMutie.Immutable</code>:</p>
<pre class="brush: csharp">// create and instance
var person = Immutable.Create&lt;Person&gt;(new {Id = 43, Name = &quot;Bob&quot;});</pre>
<p class="brush: csharp">The argument to <code>Immutable.Create</code> is simply object, so we can pass in an anonymous object with whatever properties we want. Create then provides and instance and copies over values on property name and type match. And if we want to change the Name?</p>
<pre class="brush: csharp">// derive new instance with different name (using extension method)
person = person.With(new {Name = &quot;Robert&quot;});</pre>
<p class="brush: csharp">With let&#39;s you provide a new anonymous object, will clone the previous instance and then overwrite each newly provided field by name/type match.</p>
<p class="brush: csharp">Very simple, no error checking, not the most efficient code, but it works and you can <a href="https://github.com/sdether/ImMutie" target="_blank">get it from github </a> <img src='http://www.claassen.net/geek/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/Lm7-Wz1zhyE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/07/simple-immutable-objects.html/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/07/simple-immutable-objects.html</feedburner:origLink></item>
		<item>
		<title>Implementing “exports” in C#</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/gZeWEfIOIqM/implementing-exports-in-c.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/05/implementing-exports-in-c.html#comments</comments>
		<pubDate>Wed, 25 May 2011 16:00:09 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>
		<category><![CDATA[Promise]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[meta-programming]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1376</guid>
		<description><![CDATA[The other day i was musing about improving readability by liberating verbs from the containing objects that own them. Similar things are accomplished with mix-ins or traits in other languages, but I wanted to go another step further and allow for very context specific mapping, rather than just mixing ambigiously named methods from other objects. [...]]]></description>
			<content:encoded><![CDATA[<p>The other day i was <a href="http://www.claassen.net/geek/blog/2011/05/of-workflows-data-and-services.html">musing about improving readability by liberating verbs</a> from the containing objects that own them. Similar things are accomplished with mix-ins or traits in other languages, but I wanted to go another step further and allow for very context specific mapping, rather than just mixing ambigiously named methods from other objects. Since the <code>exports</code> construct looked a lot like a map of expressions, I decided to see what replicating the behavior with existing C# would look like.</p>
<p>To review, this is what I want (in <em>C#-like</em> pseudo code + <code>exports)</code>:</p>
<pre class="csharp" name="code">class PageWorkflow {
  UserService _userService exports { FindById =&gt; FindUserById };
  PageService _pageService exports {
    FindById        =&gt; FindPageById,
    UpdatePage(p,c) =&gt; Update(this p,c)
  };
  AuthService _authService exports {
    AuthorizeUserForPage(u,p,Permissions.Write) =&gt; UserCanUpdatePage(u,p)
  };

  UpdatePage(userid, pageid, content) {
    var user = FindUserById(userid);
    var page = FindPageById(pageid);
    if(UserCanUpdatePage(user,page)) {
      page.Update(content);
    } else {
      throw;
    }
  }
}</pre>
<p>And this is C# implementation of the above:</p>
<pre class="csharp" name="code">public class PageWorkflow {

&nbsp;&nbsp;&nbsp; private readonly Func&lt;int, User&gt; FindUserById;
&nbsp;&nbsp;&nbsp; private readonly Func&lt;int, Page&gt; FindPageById;
&nbsp;&nbsp;&nbsp; private readonly Action&lt;Page, string&gt; Update;
&nbsp;&nbsp;&nbsp; private readonly Func&lt;User, Page, bool&gt; UserCanUpdatePage;

&nbsp;&nbsp;&nbsp; public PageWorkflow(IUserService userService, IPageService pageService, IAuthService authService) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FindUserById = (id) =&gt; userService.FindById(id);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; FindPageById = (id) =&gt; pageService.FindById(id);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Update = (page, content) =&gt; pageService.UpdatePage(page, content);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UserCanUpdatePage = (user, page) =&gt; authService.AuthorizeUserForPage(user, page, Permissions.Write);
&nbsp;&nbsp;&nbsp; }

&nbsp;&nbsp;&nbsp; public void UpdatePage(int userid, int pageid, string content) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var user = FindUserById(userid);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; var page = FindPageById(pageid);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if(UserCanUpdatePage(user, page)) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Update(page, content);
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; throw new Exception();
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }
&nbsp;&nbsp;&nbsp; }
}</pre>
<p>As I mentioned, it&#39;s all possible, short of the context sensitive extension method on <code>Page</code>. Lacking extension methods, I was going to name the imported method <code>UpdatePage</code>, but since it would be a field, it conflicts with the <code>UpdatePage</code> workflow method despite functionally having different signatures.</p>
<p>All in all, the public workflow <code>UpdatePage</code> is pretty close to what I had wanted, but the explicit type declaration of the each <code>exports </code>makes it boilerplate that is likely not worth the trouble of writing, and, <em>no</em>, i won&#39;t even consider code generation.</p>
<p>This exercise along with every other language feature I&#39;ve dreamt up for <em><strong>Promise </strong></em>does illustrate one thing quite clearly to me: <strong>My ideal language should provide programatic access to its parser so that the syntax of the language can be extended by the libraries</strong>. Internal DSLs are a nice start with most languages, but often they fall short of being able to reduce default boilerplate and just create new boilerplate. Sure, designing the language to be more succinct is desirable, but if anything, that only covers what the language creators could imagine. Being able to tweak a language into a DSL for the task at hand, <em>a la</em> <a href="http://www.jetbrains.com/mps/" target="_blank">MPS</a>, seems a lot more flexible.</p>
<p>Is this added flexibility worth the loss of a common set of constructs that is shared by all programmers knowing language X? It certainly could be abused to become incomprehensible, but I would suggest that even knowing language X joining <strong>any Team working on a project of sufficient complexity adds its own wealth of implicit patterns and constructs</strong> and worse than a language whose compiler is extended, these constructs are communicated via comments and documentation that are not part of language X, i.e. the compiler and IDE lack the ability to aid someone learning these constructs.</p>
<p>Considering this, I really need to do a survey of languages that already offer this capability as well as take a closer look at <a href="http://www.jetbrains.com/mps/" target="_blank">MPS</a> and <a href="http://nemerle.org/About/" target="_blank">Nemerle</a> to see if the language I want is just a few parser rules a way from an existing meta programming language.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/gZeWEfIOIqM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/05/implementing-exports-in-c.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/05/implementing-exports-in-c.html</feedburner:origLink></item>
		<item>
		<title>Of Workflows, Data and Services</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/I6hAnFBuJyg/of-workflows-data-and-services.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/05/of-workflows-data-and-services.html#comments</comments>
		<pubDate>Mon, 23 May 2011 15:00:55 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>
		<category><![CDATA[Promise]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1350</guid>
		<description><![CDATA[This is yet another in my series of posts musing about what my ideal language would look like. This one is about readability. Most code I write these days seems to utilize three types of classes: Data, Services and Workflow. Data Classes These are generally POCO object hierarchies with fields/accessors but minimal logic for manipulating [...]]]></description>
			<content:encoded><![CDATA[<p>This is yet another in my series of posts musing about what my ideal language would look like. This one is about readability.</p>
<p>Most code I write these days seems to utilize three types of classes: <strong>Data</strong>, <strong>Services </strong>and <strong>Workflow</strong>.</p>
<h3>Data Classes</h3>
<p>These are generally POCO object hierarchies with fields/accessors but minimal logic for manipulating that data. They should not have any dependencies. If an operation on a data object has a dependency, it&#39;s really a service for that data. Data objects don&#39;t get mocked/stubbed/faked, since we can just create and populate them.</p>
<h3>Service Classes</h3>
<p>These are really containers for verbs. The verbs could have been methods on the calling object, but by pulling them into these containers we enable a number of desirable capabilities:</p>
<ul>
<li><em>re-use</em> &#8212; different workflows can use the same logic without creating their own copy</li>
<li><em>testing </em>&#8211; by faking the service we get greater control over testing different responses from the service</li>
<li><em>dependency abstraction</em> &#8212; there might be a number of other bits of logic that have to be invoked in order to provide the work the verb does but isn&#39;t a concern of the workflow</li>
<li><em>organization </em>&#8211; related verbs</li>
</ul>
<h3>Workflow Classes</h3>
<p>These end up being classes, primarily because in most OO languages everything&#39;s a class, but really workflow classes are organizational constructs used to collected related workflows as procedural execution environments. They can be set up with pre-requisites and promote code re-use via shared private members for common sub-tasks of the workflow. They are also responsible for condition and branching logic to do the actual work.</p>
<p>Actions (<em>requests from users, triggered tasks, etc</em>.) start at some entry point method on a workflow object, such as a REST endpoint, manipulate data via Data objects using services, the results of which trigger paths defined by the workflow.</p>
<h2>Same construct, radically different purposes</h2>
<p>Let&#39;s look how this works out for a fictional content management scenario. I&#39;m using a C#<em>-like</em> pseudo syntax to avoid unecessary noise (ironic, since this post is all about readibility):</p>
<pre class="csharp" name="code">class PageWorkflow {
  ...
  UpdatePage(userid, pageid, content) {
    var user = _userService.FindById(userid);
    var page = _pageService.FindById(pageid);
    if(_authService.AuthorizeUserForPage(user,page,Permissions.Write)) {
      _pageService.UpdatePage(page,content);
    } else {
      throw;
    }
  }
}
</pre>
<p><code>UpdatePage</code> is part of <code>PageWorkflow</code>, i.e a workflow in our workflow class. It is configured with <code>_userService</code>,<code> _pageService</code> and<code> _authService</code> as our service classes. Finally <code>user </code>and <code>page</code> are instances of our data classes. Nice for maintainability and separation of concerns, but awkward from a readibility perspective. It would be much more readable with syntax like this:</p>
<pre class="csharp" name="code">class PageWorkflow {
  ...
  UpdatePage(userid, pageid, content) {
    var user = FindUserById(userid);
    var page = FindPageById(pageid);
    if(UserCanUpdatePage(user,page)) {
      page.Update(content);
    } else {
      throw;
    }
  }
}
</pre>
<p>Much more like we think of the flow. Of course this could easily be done by creating those methods on <code>PageWorkflow</code>, but that&#39;s the beginning of the end of building a god object, and don&#39;t even get me started on putting <code>Update</code> on the <code>Page</code> data object.</p>
<h2>Importing verbs</h2>
<p>So let&#39;s assume that this separation of purposes is desirable &#8212; i&#39;m sure there&#39;ll be plenty of people who will disagree with that premise, but the premise isn&#39;t the topic here. What we really want to do here is alias or import the functionality into our execution context. Something like this:</p>
<pre class="csharp" name="code">class PageWorkflow {
  UserService _userService exports { FindById =&gt; FindUserById };
  PageService _pageService exports {
    FindById        =&gt; FindPageById,
    UpdatePage(p,c) =&gt; Update(this p,c)
  };
  AuthService _authService exports {
    AuthorizeUserForPage(u,p,Permissions.Write) =&gt; UserCanUpdatePage(u,p)
  };
  ...
}
</pre>
<p>Do not confuse this with VB&#39;s or javascript&#39;s <code>with</code> keywords. Both import the entirety of the referenced object into the current scope. The much maligned javascript version does this by importing it into the global namespace, which, given the dynamic nature of those objects, makes the variable use completely ambiguous. While VB kept scope ambiguity in check by forcing a . (dot) preceeding the imported object&#39;s members, it is a shorthand that is only questionably more readable.</p>
<p>The above construct is closer to the <code>@EXPORT</code> syntax of the perl <code>Exporter</code> module. Except instead of exporting functions, <code>exports</code> exports methods on an instance as methods on the current context. It also extends the export concept in three ways:</p>
<h3>Aliasing</h3>
<p>Instead of just blindly importing a method from a service class, the <code>exports</code> syntax allows for aliasing. This is useful because imported method likely defered some of its functionality context to the owning class and could collide with other imported methods,&nbsp; e.g. <code>FindById</code> on <code>PageService</code> and <code>UserService</code>.</p>
<h3>Argument rewriting</h3>
<p>As the methodname is rewritten, the argument order may no longer be appropriate, or we may want to change the argument modifiers, such as turn a method into an extension method.</p>
<pre class="csharp" name="code">UpdatePage(p,c) =&gt; Update(this p,c)</pre>
<p>The above syntax captures arguments into <code>p</code> and <code>c</code> and then aliases the method into the current class&#39; context and turns it into a method attached to <code>p</code>, i.e. the <code>page</code>, so that we can call <code>page.Update(content)</code></p>
<h3>Currying</h3>
<p>But why stop at just changing the argument order and modifiers. We&#39;re basically defining expressions that translate the calls from one to the other, so why shouldn&#39;t we be able to make every argument an expression itself?</p>
<pre class="csharp" name="code">AuthorizeUserForPage(u,p,Permissions.Write) =&gt; UserCanUpdatePage(u,p)
</pre>
<p>This syntax curries the <code>Permissions.Write</code> argument so that we can define our aliases entrypoint without the last argument and instead name it to convey the write permissions implcitly.</p>
<h2>Writing workflows more like we think</h2>
<p>Great, some new syntactic sugar. <em>Why bother?</em> Well, most language constructs are some level of syntactic sugar over the raw capabilities of the machine to let us express our intend more clearly. Generally syntactic sugar ought to meet two tests: make code easier to read and more compact to write.</p>
<p>The whole of the import mechanism could easily be accomplished (except maybe for the extension method rewrite) by creating those methods on <code>PageWorkflow</code> and calling the appropriate service members from there. The downside to this approach is that the methods are not differentiated from other methods in the body of <code>PageWorkflow</code> therefore not easily recognizable as aliasing constructs. In addition the setup as wrapper methods is syntactically a lot heavier.</p>
<p>The <code>exports</code> mechanism allows for code to be crafted more closely to how we would talk about accomplishing the task without compromising on the design of the individual pieces or tying their naming and syntax to one particular workflow. It is localized to the definition of the service classes and provides a more concise syntax. In this way it aids the readibility as well as theauthoring of a common task.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/I6hAnFBuJyg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/05/of-workflows-data-and-services.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/05/of-workflows-data-and-services.html</feedburner:origLink></item>
		<item>
		<title>When lazy evaluation attacks</title>
		<link>http://feedproxy.google.com/~r/Iloggable/~3/aIuKoFcLfRU/when-lazy-evaluation-attacks.html</link>
		<comments>http://www.claassen.net/geek/blog/2011/05/when-lazy-evaluation-attacks.html#comments</comments>
		<pubDate>Wed, 18 May 2011 05:46:52 +0000</pubDate>
		<dc:creator>arne</dc:creator>
				<category><![CDATA[geek]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[enumerable]]></category>
		<category><![CDATA[iterator]]></category>
		<category><![CDATA[lazy]]></category>

		<guid isPermaLink="false">http://www.claassen.net/geek/blog/?p=1357</guid>
		<description><![CDATA[I just had a lovely object lesson in lazy evaluation of Iterators. I wanted to have method that would return an enumerator over an encapsulated set after doing some sanity checking: public IEnumerable&#60;Subscription&#62; Filter(Func&#60;Subscription, bool&#62; filter) { if(filter == null) { throw new ArgumentNullException(&#34;filter&#34;,&#34;cannot execute with a null filter&#34;); } foreach(var subInfo in _subscriptions.ToArray()) { [...]]]></description>
			<content:encoded><![CDATA[<p>I just had a lovely object lesson in lazy evaluation of Iterators. I wanted to have method that would return an enumerator over an encapsulated set after doing some sanity checking:</p>
<pre class="csharp" name="code">public IEnumerable&lt;Subscription&gt; Filter(Func&lt;Subscription, bool&gt; filter) {
    if(filter == null) {
        throw new ArgumentNullException(&quot;filter&quot;,&quot;cannot execute with a null filter&quot;);
    }
    foreach(var subInfo in _subscriptions.ToArray()) {
        Subscription sub;
        try {
            var subDoc = XDocFactory.LoadFrom(subInfo.Path, MimeType.TEXT_XML);
            sub = new Subscription(subDoc );
            if(filter(sub) {
              continue;
            }
        } catch(Exception e) {
            _log.Warn(string.Format(&quot;unable to retrieve subscription for path &#39;{0}&#39;&quot;, subInfo.Path), e);
            continue;
        }
        yield return sub;
    }
}
</pre>
<p>I was testing registering a subscription in the repository with this code:</p>
<pre class="csharp" name="code">IEnumerable&lt;Subscription&gt; query;
try {
  query = _repository.Filter(handler);
} catch(ArgumentException e) {
  return;
}
foreach(var sub in query) {
   ...
}
</pre>
<p>And the test would throw a <code>ArgumentNullException</code> because handler was null. <em>What?</em> But, but i clearly had a<code> try/catch</code> around it! Well, here&#39;s where clever bit me. By using <code>yield</code>, the method had turned into an enumerator instead of a method call that returned an enumerable. That means that the method body would get squirreled away into an enumerator closure that would not get executed until the first <code>MoveNext()</code>. And that in turn meant that my sanity check on handler didn&#39;t happen at <code>Filter()</code> but at the first iteration of the <code>foreach</code>.</p>
<p>Instead of doing <em>&quot;return an Iterator for subscriptions</em>&quot;, I needed to do &quot;<em>check the arguments</em>&quot; and then &quot;<em>return an Iterators for subscriptions</em>&quot; as a separate action. This can be accomplished by factoring the <code>yield </code>into a method called by <code>Filter() </code>instead of being in <code>Filter()</code> itself:</p>
<pre class="csharp" name="code">public IEnumerable&lt;Subscription&gt; Filter(Func&lt;Subscription, bool&gt; filter) {
    if(filter == null) {
        throw new ArgumentException(&quot;cannot execute with a null filter&quot;);
    }
    return BuildSubscriptionEnumerator(Func&lt;Subscription, bool&gt; filter);
}

public IEnumerable&lt;Subscription&gt; BuildSubscriptionEnumerator(Func&lt;Subscription, bool&gt; filter) {
    foreach(var subInfo in _subscriptions.ToArray()) {
        Subscription sub;
        try {
            var subDoc = XDocFactory.LoadFrom(subInfo.Path, MimeType.TEXT_XML);
            sub = new Subscription(subDoc );
            if(filter(sub) {
              continue;
            }
        } catch(Exception e) {
            _log.Warn(string.Format(&quot;unable to retrieve subscription for path &#39;{0}&#39;&quot;, subInfo.Path), e);
            continue;
        }
        yield return sub;
    }
}
</pre>
<p>Now the sanity check happens at <code>Filter()</code> call time, while the enumeration of subscription still only occurs as its being iterated over, allowing for additional filtering and <code>Skip/Take</code> additions without having to traverse the entire possible set.</p>
<img src="http://feeds.feedburner.com/~r/Iloggable/~4/aIuKoFcLfRU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.claassen.net/geek/blog/2011/05/when-lazy-evaluation-attacks.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.claassen.net/geek/blog/2011/05/when-lazy-evaluation-attacks.html</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! -->

