<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Oliver Steele &#187; Tips</title>
	<atom:link href="http://osteele.com/archives/category/tips/feed" rel="self" type="application/rss+xml" />
	<link>http://osteele.com</link>
	<description>Languages of the real and artificial.</description>
	<lastBuildDate>Thu, 10 Feb 2011 06:40:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.5</generator>
		<item>
		<title>Minimizing Code Paths in Asychronous Code</title>
		<link>http://osteele.com/archives/2008/04/minimizing-code-paths-asychronous-code</link>
		<comments>http://osteele.com/archives/2008/04/minimizing-code-paths-asychronous-code#comments</comments>
		<pubDate>Sun, 20 Apr 2008 22:28:18 +0000</pubDate>
		<dc:creator>Oliver</dc:creator>
				<category><![CDATA[Libraries]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://osteele.com/2008/04/20/minimizing-code-paths-in-asychronous-code</guid>
		<description><![CDATA[Have you ever written a function that looks like this?

[code language="javascript"]
function requestProductDetails(id, k) {
  var value = gProductDetailsCache[id];
  if (value)
    k(value)
  else
    ajax.get('/product/'+id, function(data) {
      gProductDetailsCache[id] = data;
      k(data);
    });
}
[/code]

@requestProductDetails@ calls its callback with the product details, which are stored in a cache.  Since it might need to request this information from the server, it has to "return" it by passing it to a callback; in order to present a uniform API whether or not the product is cached, it "returns" the data this way whether it came from the cache or not.]]></description>
			<content:encoded><![CDATA[<p>Have you ever written a function that looks like this?</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> requestProductDetails<span style="color: #009900;">&#40;</span>id<span style="color: #339933;">,</span> k<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> gProductDetailsCache<span style="color: #009900;">&#91;</span>id<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span>
    k<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span>
  <span style="color: #000066; font-weight: bold;">else</span>
    ajax.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'/product/'</span><span style="color: #339933;">+</span>id<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      gProductDetailsCache<span style="color: #009900;">&#91;</span>id<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
      k<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p><code>requestProductDetails</code> calls its callback with the product details, which are stored in a cache.  Since it might need to request this information from the server, it has to &#8220;return&#8221; it by passing it to a callback; in order to present a uniform <span class="caps">API </span>whether or not the product is cached, it &#8220;returns&#8221; the data this way whether it came from the cache or not.</p>

<p><code>requestProductDetails</code> is intended to be used this way:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">requestProductDetails<span style="color: #009900;">&#40;</span>id<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>details<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  infoPanel.<span style="color: #660066;">setDetails</span><span style="color: #009900;">&#40;</span>id<span style="color: #339933;">,</span> details<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
infoPanel.<span style="color: #660066;">setName</span><span style="color: #009900;">&#40;</span>id<span style="color: #339933;">,</span> gProductNames<span style="color: #009900;">&#91;</span>id<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>(I gave <code>infoPanel</code> a somewhat silly <span class="caps">API </span>in order to demonstrate a point.  The general pattern is that there&#8217;s some computation in the callback, and some other computation after the call.)</p>

<p>There&#8217;s a subtle problem in this code, which is that two different code paths run through it.  In the cached case, <code>infoPanel.setDetails</code> is called before <code>infoPanel.setName</code>.  In the uncached case (the first time through), it&#8217;s the other way around.  If there&#8217;s a bug that causes <code>setDetails</code> to work only after <code>setName</code> has been called, you may well miss it during casual testing, because it will only trigger the second time you trigger the code &#8212; and once it does trigger, it will appear intermittently (especially if you have a more sophisticated cache), and be darned difficult to find.</p>

<p>I recommend this implementation of <code>requestProductDetails</code> instead.  It makes the <em>inside</em> of the function more complex &#8212; and the <code>setTimeout</code> looks gratuitous &#8212; but it makes its <em>outside</em> simpler : <code>requestProductDetails</code>s <em>callers</em> are <em>much</em> easier to debug.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> requestProductDetails<span style="color: #009900;">&#40;</span>id<span style="color: #339933;">,</span> k<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> gProductDetailsCache<span style="color: #009900;">&#91;</span>id<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span>
    setTimeout<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> k<span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">10</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">else</span>
    ajax.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'/product/'</span><span style="color: #339933;">+</span>id<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      gProductDetailsCache<span style="color: #009900;">&#91;</span>id<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> data<span style="color: #339933;">;</span>
      k<span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>The general principle here is if a function <em>sometimes</em> has to call its callback asynchronously, <em>always</em> call it asynchronously, to minimize the number of possible code paths through the application.</p>]]></content:encoded>
			<wfw:commentRss>http://osteele.com/archives/2008/04/minimizing-code-paths-asychronous-code/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Self-Printing JavaScript Literals</title>
		<link>http://osteele.com/archives/2008/02/self-printing-javascript-literals</link>
		<comments>http://osteele.com/archives/2008/02/self-printing-javascript-literals#comments</comments>
		<pubDate>Fri, 15 Feb 2008 19:37:45 +0000</pubDate>
		<dc:creator>Oliver</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://osteele.com/2008/02/15/self-printing-javascript-literals</guid>
		<description><![CDATA[Sometimes you need a totally opaque "constant" -- a value that isn't intended to be projected or modified, and whose only purpose is to be completely different from every other value[1].  For example, <a href="/sources/javascript/functional/">Functional</a> uses <code>Functional._</code> as a placeholder; a comment on <a href="http://ejohn.org/blog/partial-functions-in-javascript/">John Resig's blog</a> suggests defining something like <code>Partial.PLACEHOLDER</code> for something similar.

In JavaScript, these are easy to make.  Here's one: <code>{}</code>.  And here's another: <code>{}</code>.  Note that these two values are <em>different</em>: the following code[2] will print @true@, then @true@, then @false@:]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need a totally opaque &#8220;constant&#8221; &#8212; a value that isn&#8217;t intended to be projected or modified, and whose only purpose is to be completely different from every other value<sup class="footnote"><a href="#fn1">1</a></sup>.  For example, <a href="/sources/javascript/functional/">Functional</a> uses <code>Functional._</code> as a placeholder; a comment on <a href="http://ejohn.org/blog/partial-functions-in-javascript/">John Resig&#8217;s blog</a> suggests defining something like <code>Partial.PLACEHOLDER</code> for something similar.</p>

<p>In JavaScript, these are easy to make.  Here&#8217;s one: <code>{}</code>.  And here&#8217;s another: <code>{}</code>.  Note that these two values are <em>different</em>: the following code<sup class="footnote"><a href="#fn2">2</a></sup> will print <code>true</code>, then <code>true</code>, then <code>false</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> L1 <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> L2 <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
console.<span style="color: #660066;">info</span><span style="color: #009900;">&#40;</span>L1 <span style="color: #339933;">==</span> L1<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;&gt;&gt;</span> <span style="color: #003366; font-weight: bold;">true</span>
console.<span style="color: #660066;">info</span><span style="color: #009900;">&#40;</span>L2 <span style="color: #339933;">==</span> L2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;&gt;&gt;</span> <span style="color: #003366; font-weight: bold;">true</span>
console.<span style="color: #660066;">info</span><span style="color: #009900;">&#40;</span>L1 <span style="color: #339933;">==</span> L2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;&gt;&gt;</span> <span style="color: #003366; font-weight: bold;">false</span></pre></div></div>




<p>The problem with these values is that they look the same when you print them.  <code>L1</code> and <code>L2</code> both print as <code>Object</code> (in Firefox).</p>

<p>I&#8217;m going to print a value now:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">console.<span style="color: #660066;">info</span><span style="color: #009900;">&#40;</span>isPrime<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">172942</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">?</span> L1 <span style="color: #339933;">:</span> L2<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&gt;&gt;&gt;</span> Object</pre></div></div>




<p>Quick, which one did I print?  Sure, you can figure it out in this case (assuming my implementation of <code>isPrime</code> isn&#8217;t buggy &#8212; probably not a safe bet, especially if you&#8217;re having to debug this in the first place), but in general this wreaks havoc with debugging.</p>

<p>Here&#8217;s an idiom for making opaque values that can be debugged.  This has the further benefit that if the value is bound to a variable, you can use this to create a value that evaluates to itself when you type it back into the console (or into your source code). This works in Firebug and Rhino and OpenLaszlo, at least.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> L1 <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>toString<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;L1&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> L2 <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>toString<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #3366CC;">&quot;L2&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
L1
<span style="color: #339933;">&gt;&gt;&gt;</span> L1
L2
<span style="color: #339933;">&gt;&gt;&gt;</span> L2</pre></div></div>




<p>If you do use opaque constants often, you can use this <code>makeLiteral</code> utility routine to make them:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> makeLiteral<span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>toString<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066;">name</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span>
<span style="color: #003366; font-weight: bold;">var</span> L1 <span style="color: #339933;">=</span> makeLiteral<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;L1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> L2 <span style="color: #339933;">=</span> makeLiteral<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;L2&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
L1
<span style="color: #339933;">&gt;&gt;&gt;</span> L1
L2
<span style="color: #339933;">&gt;&gt;&gt;</span> L2</pre></div></div>




<p>Some real-world uses might be:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Functional._ <span style="color: #339933;">=</span> makeLiteral<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Functional._&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
Partial.<span style="color: #660066;">PLACEHOLDER</span> <span style="color: #339933;">=</span> makeLiteral<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Partial.PLACEHOLDER&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>In fact, you could go further and define a defining-form.  I&#8217;m just including this for completeness; the version here doesn&#8217;t work unless <code>target</code> itself has a <code>toString()</code> method, and would need more work to be made robust.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> defineLiteral<span style="color: #009900;">&#40;</span>target<span style="color: #339933;">,</span> <span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  target<span style="color: #009900;">&#91;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>toString<span style="color: #339933;">:</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> target<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;.&quot;</span><span style="color: #339933;">+</span><span style="color: #000066;">name</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
defineLiteral<span style="color: #009900;">&#40;</span>Functional<span style="color: #339933;">,</span> <span style="color: #3366CC;">'_'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p><hr/></p>

<p class="footnote" id="fn1"><sup>1</sup> Basically an enumerated type or a member of an algebraic data type, except that in meta-level programming these values are often compared to <em>any</em> other value, not just values of a specific type.</p>

<p class="footnote" id="fn2"><sup>2</sup> This would work the same way with <code>===</code> instead of <code>==</code>, but here it&#8217;s not necessary.</p>]]></content:encoded>
			<wfw:commentRss>http://osteele.com/archives/2008/02/self-printing-javascript-literals/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Monads on the Cheap I: The Maybe Monad</title>
		<link>http://osteele.com/archives/2007/12/cheap-monads</link>
		<comments>http://osteele.com/archives/2007/12/cheap-monads#comments</comments>
		<pubDate>Mon, 17 Dec 2007 02:49:46 +0000</pubDate>
		<dc:creator>Oliver</dc:creator>
				<category><![CDATA[Essays]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming Languages]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://osteele.com/2007/12/17/monads-on-the-cheap-i-the-maybe-monad</guid>
		<description><![CDATA[Don't worry, this isn't YAMT ("Yet Another Monad Tutorial":/archives/2007/12/overloading-semicolon).  This is a practical post about a code smell that afflicts everyday code, and about an idiom that eliminates that smell.  It just so happens that this idiom corresponds to one of the uses for monads in Haskell, but that's just theory behind the practice, and I've saved the theory for the end.

This post is about style: implementation choices at the level of the expression and the statement.  Style doesn't matter much in a small program, or a write-only program (one that nobody will read later).  It isn't necessary to make a program run: by definition, it doesn't make a functional difference.  Style makes a difference to how easy or pleasant a program is to read; this can make a difference to whether it gets worked on (by its author, or somebody else) later.]]></description>
			<content:encoded><![CDATA[<p>Don&#8217;t worry, this isn&#8217;t <span class="caps">YAMT </span>(<a href="/archives/2007/12/overloading-semicolon">Yet Another Monad Tutorial</a>).  This is a practical post about a code smell that afflicts everyday code, and about an idiom that eliminates that smell.  It just so happens that this idiom corresponds to one of the uses for monads in Haskell, but that&#8217;s just theory behind the practice, and I&#8217;ve saved the theory for the end.</p>

<p>This post is about style: implementation choices at the level of the expression and the statement.  Style doesn&#8217;t matter much in a small program, or a write-only program (one that nobody will read later).  It isn&#8217;t necessary to make a program run: by definition, it doesn&#8217;t make a functional difference.  Style makes a difference to how easy or pleasant a program is to read; this can make a difference to whether it gets worked on (by its author, or somebody else) later.</p>

<h3>The Problem</h3>

<p>The types are <strong>Product</strong>, <strong>Offering</strong>, <strong>Merchant</strong>, and <strong>Name</strong>.  A Product <em>might</em> have an Offering; an Offering <em>might</em> have a Merchant; and a Merchant <em>might</em> have a Name.</p>

<p>The code displays the name of the merchant that is offering the selected product.  The input is named <var>product</var>.  This value <em>might</em> be an instance of <strong>Product</strong>, or it might be null.  The specification is this:  If <var>product</var> is a product that has an offering that has a merchant has a name, then display that name; else do nothing.</p>

<p>[This problem is adapted from an eCommerce application I'm writing.]</p>

<p>This code isn&#8217;t difficult to write.  The challenge isn&#8217;t in make it run; it&#8217;s in making it readable.</p>

<h3>The Obvious Implementation</h3>

<p>Here&#8217;s a naive solution.  This particular code is JavaScript, but the structure comes out the same in Python, or Ruby, or C++ or Java, or Lisp.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>product<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> offering <span style="color: #339933;">=</span> product.<span style="color: #660066;">offering</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>offering<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> merchant <span style="color: #339933;">=</span> offering.<span style="color: #660066;">merchant</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>merchant<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      <span style="color: #003366; font-weight: bold;">var</span> merchantName <span style="color: #339933;">=</span> merchant.<span style="color: #000066;">name</span><span style="color: #339933;">;</span>
      <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span>
        displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>Let&#8217;s stop for a moment and identify the smells.  There are two of them: I call the first one Narrative Mismatch, and the second Baton Carriers.</p>

<p>The first smell has to do with those nested conditionals.  There&#8217;s a narrative here, that flows from the beginning of the spec (&#8220;the input is named <i>product</i>&#8220;) to the end (&#8220;display that name&#8221;).  The code that corresponds to this narrative starts with <code>product=...</code>, and ends <code>displayMerchantName(...)</code>.  However, the line of this narrative isn&#8217;t linear in this implementation; it&#8217;s a series of <a href="http://en.wikipedia.org/wiki/Matryoshka_doll">Russian dolls</a>.  The climax to the story is buried in a subplot, displayed as though it were some exceptional case.  Narrative Mismatch is when the dramatic structure (the specification) of the program doesn&#8217;t match its control structure (in the implementation).</p>

<p>The other problem is the temporary variables.  These are the variables such as <code>offering</code> and <code>merchant</code>.  These variables are &#8220;bit players&#8221;: each variable enters the stage (the local scope) only to perform a trivial bit of business, and then hangs around as clutter.  Or, to use a racing metaphor, this implementation turns what could be a sprint into a relay race, where a series of runners hands off the data baton.</p>

<h3>Can we do better?</h3>

<p>If the code did nothing but display the merchant name and then return, we could invert each of the conditionals, and bail out early.  This changes the control structure to match the plot: the beginning and end of the narrative are both at the same (top) level of the control structure.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>product<span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> offering <span style="color: #339933;">=</span> product.<span style="color: #660066;">offering</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>offering<span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> merchant <span style="color: #339933;">=</span> offering.<span style="color: #660066;">merchant</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>merchant<span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> merchantName <span style="color: #339933;">=</span> merchant.<span style="color: #000066;">name</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>merchantName<span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>This implementation retains two of the disadvantages from the first, and it introduces a third. First, that&#8217;s still an awful lot of control flow (four lines) obfuscating a tiny amount of data flow (four lines).  Second, we&#8217;ve still got those baton variables, <code>offering</code>, <code>merchant</code>, <i>etc</i>.  Finally, the new implementation works only if the fragment is an entire function: if <code>displayMerchantName</code> is the last statement in the function<sup class="footnote"><a href="#fn1">1</a></sup>.</p>

<p>How about if we eliminate the batons altogether?  Then we can combine all the tests into a single conditional:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>product
    <span style="color: #339933;">&amp;&amp;</span> product.<span style="color: #660066;">offering</span>
    <span style="color: #339933;">&amp;&amp;</span> product.<span style="color: #660066;">offering</span>.<span style="color: #660066;">merchant</span>
    <span style="color: #339933;">&amp;&amp;</span> product.<span style="color: #660066;">offering</span>.<span style="color: #660066;">merchant</span>.<span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span>
  displayMerchantName<span style="color: #009900;">&#40;</span>product.<span style="color: #660066;">offering</span>.<span style="color: #660066;">merchant</span>.<span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>This implementation has fewer lines, at least, but there&#8217;s still a lot of repetition<sup class="footnote"><a href="#fn2">2</a></sup> &#8212; the text <code>product.offering</code> occurs four times.</p>

<p>It&#8217;s also inefficient. The previous implementations computed the value of <code>product.offering</code> only once, but this one computes it four times, and contains a total of nine member accesses to the alternatives&#8217; three.  These multiple accesses may not matter for this particular example: the case where all nine of those accesses are executed is the same case that ends with a a function call to a display routine. But consider the case where the accessor is <code>product.offering()</code> instead; or, in Ruby or <span class="caps">ECMAS</span>cript 4, the case where <code>product.offering</code> is a getter.</p>

<p>We can re-introduce the temporary variables, this time within the conditional, to keep the control flow simple:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">,</span>
    offering<span style="color: #339933;">,</span> merchant<span style="color: #339933;">,</span> merchantName<span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>product
    <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>offering <span style="color: #339933;">=</span> product.<span style="color: #660066;">offering</span><span style="color: #009900;">&#41;</span>
    <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>merchant <span style="color: #339933;">=</span> offering.<span style="color: #660066;">merchant</span><span style="color: #009900;">&#41;</span>
    <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span>merchantName <span style="color: #339933;">=</span> merchant.<span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
  displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>&#8230;but now we&#8217;ve brought back the batons.</p>

<p>(You may also have a stylistic object to the assignments inside of conditionals in this latest attempt. I&#8217;m not completely against the construct, but I avoid it unless it makes the code clearer, and it&#8217;s not clear that it does that, here.)</p>

<h3>Stepping Back</h3>

<p>I&#8217;d like to be able to write something that matches the language of the specification:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">,</span>
    merchantName <span style="color: #339933;">=</span> product.<span style="color: #660066;">offering</span>.<span style="color: #660066;">merchant</span>.<span style="color: #660066;">merchantName</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span>
  displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>and have the system just know that <code>product.offering</code> evaluates to null if <code>product</code> is null; and that <code>product.offering.merchant</code> evaluates to null if <code>product.offering</code> is null, <i>etc</i>.  Now, we might not like <code>null.property</code> to evaluate to null <em>everywhere</em> (that might move bug symptoms too far away from their defect sites), but we&#8217;d like it <em>here</em>.</p>

<p>This property &#8212; that member access to a property of null is itself null &#8212; could be called &#8220;null contagion&#8221;.  Many languages have &#8220;float contagion&#8221;, where an arithmetic operation produces a float if either of its arguments is a float.  (<i>i.e.</i> <code>a+b</code> is equivalent to <code>float(a)+float(b)</code> if <em>either</em> of <code>a</code> or <code>b</code> is a float.)  &#8220;Null contagion&#8221; is similar to float contagion except that it only applies to the member access (<code>.</code>) operator, and only from left to right.</p>

<p>You may be used to null contagion from other contexts &#8212; for example, from the declarative languages such as <span class="caps">CSS </span>and XPath and <span class="caps">SQL, </span>that adjoin the mainstream languages.  It&#8217;s just not present in any of the procedural languages that I listed at the top of this post.  For example, if <code>product</code> were <span class="caps">XML </span>and we were using <span class="caps">E4X, </span>we could write this as <code>product.offering.merchant.name</code> as desired.  Or if we could apply <span class="caps">CSS </span>to a JavaScript object, we might write something like <code>$('offering &gt; merchant &gt; name', product)</code>.  Or with XPath (and an Hpricot-like syntax, this time): <code>product/'offering/merchant/name/text()'</code>.</p>

<p>So one solution would be to write a function that applies <span class="caps">CSS </span>or XPath paths to JavaScript objects.  This works and there&#8217;s even Java libraries that do this, but here I&#8217;m looking for something less heavyweight than a library, and something that doesn&#8217;t require parsing strings at runtime.  I&#8217;m looking for an idiom that approximates null contagion within the language.</p>

<p>Without further ado, here&#8217;s how to write an expression that evaluates to <code>object</code>&#8216;s <code>property</code> property if <code>object</code> is not null, and to null otherwise<sup class="footnote"><a href="#fn3">3</a></sup>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span>object<span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">property</span></pre></div></div>




<p>And this can be chained as follows:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>object<span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">property1</span><span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">property2</span></pre></div></div>




<p>So let&#8217;s apply this, in two steps, to the problem above.  First, get rid of all the intermediate conditionals, in order to match the control flow to the narrative:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">,</span>
    offering <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>product<span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">offering</span><span style="color: #339933;">,</span>
    merchant <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>offering<span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">merchant</span><span style="color: #339933;">,</span>
    merchantName <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>merchant<span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #000066;">name</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span>
  displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>And now that each intermediate variable is used only once, we can inline its value and eliminate its name:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">,</span>
    merchantName <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>product<span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">offering</span><span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">merchant</span><span style="color: #339933;">||</span><span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #000066;">name</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span>
  displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>This isn&#8217;t as clean as the <span class="caps">E4X </span>example, but it&#8217;s relatively concise: no batons, and no non-narrative control flow.</p>

<p>It&#8217;s also, in the case where <em>most</em> products have offerings that have merchants that have names, potentially more performant.  A <code>||</code> (which short circuits) is comparable to an <code>if</code> statement, and the number of conditionals of either form (<code>||</code> or <code>if</code>) is conserved across all the implementations in this post.  The &#8220;null contagion&#8221; version defines <code>{}</code> literals, but these are only interpreted to create objects when the property target is null &#8212; here, assumed to be the exceptional case.  And since this attempt has fewer instances of variable name lookup than in the others, it should be more efficient than the others except when in the presence of more optimization that most of the scripting languages provide right now.</p>

<p>What about the case where most products <em>don&#8217;t</em> have offerings, or the offerings don&#8217;t have merchants, <i>vel cetera</i>?  If this were a frequent case, and this were inner-loop code, I might introduce a global empty object in order to reduce the object instantiation overhead (which happens right away) and the GC load (which shows up over time).  <i>E.g.</i> define <code>var $N={}</code>, and use:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> product <span style="color: #339933;">=</span> ...<span style="color: #339933;">,</span>
    merchantName <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>product<span style="color: #339933;">||</span>$N<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">offering</span><span style="color: #339933;">||</span>$N<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">merchant</span><span style="color: #339933;">||</span>$N<span style="color: #009900;">&#41;</span>.<span style="color: #000066;">name</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span>
  displayMerchantName<span style="color: #009900;">&#40;</span>merchantName<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>(The Ruby equivalent of <code>{}</code> is <code>{}</code> for a Hash, with array-style access; and <code>OpenStruct.new</code> for an Object, with property getter syntax.  You definitely want a reusable singleton for the latter.)</p>

<p>On the minus side, even this version always performs all four tests and all three property accesses.  That&#8217;s three extra tests (beyond the attempts at the top of this post) when <code>product</code> is <code>null</code>, and two extra when <code>product.offering</code> is <code>null</code>, and so on.  So it might still slower be than the solutions that don&#8217;t use null contagion &#8212; but on the other hand, it still avoids the temporary variables of those solutions.  In other words, there&#8217;s no substitute for actually measuring the difference, within the program and on each platform that you&#8217;re optimizing for.  Oh well.</p>

<h3>What Does this Have to Do With Monads?</h3>

<p>An expression such as <code>product.offering.merchant.name</code> is a pipe.  It can be read as &#8220;get the value of <code>product</code>; and then get that value&#8217;s <code>offering</code>; and then get that value&#8217;s <code>merchant</code>; and then get that value&#8217;s <code>name</code>&#8220;.  The dot says two things: (1) evaluate the expression (<code>product</code>) to its left, <em>and then</em> (2) use that as target for the projection function (<code>['offering']</code>) immediately to its right.</p>

<p>We&#8217;ve made up a new construct, <code>(object||{}).property</code>, which is like <code>object.property</code> except that if you put a null in (as the value of <code>object</code>), you get null out (as the value of <code>(object||{}).property</code>).  In effect, we&#8217;ve replaced dot&#8217;s interpretation of &#8220;and then&#8221;.  The interpretation of <code>object.property</code>&#8216;s &#8220;and then&#8221;  includes &#8220;and if <code>object</code> is <code>null</code>, then error&#8221;.  The interpretation of the new &#8220;and then&#8221; adds &#8220;and if <code>object</code> is null, evaluate to null&#8221;.</p>

<p>This construct, <code>(object||{}).property</code>, <em>isn&#8217;t</em> a monad.  It isn&#8217;t a monad because it isn&#8217;t associative; and it isn&#8217;t associative because the property accessor (dot) isn&#8217;t either [dot isn't the morphism of a category].  <code>(A.b).c</code> isn&#8217;t the same as <code>A.(b.c)</code> &#8212; in fact, the latter isn&#8217;t even well formed.</p>

<p>However, the class of property projection <em>functions</em> &#8212; just the <code>.b</code> part &#8212; <em>does</em> form a category.  If you consider just the <code>.b.c.d</code> part of <code>A.b.c.d</code>, it doesn&#8217;t make any difference whether you read it as &#8220;apply the &#8216;b&#8217; projection, and then apply the application of the &#8216;d&#8217; projection to the &#8216;c&#8217; projection, to that&#8221;; or &#8220;apply the &#8216;c&#8217; projection to the &#8216;b&#8217; projection, and then apply the &#8216;d&#8217; projection to that&#8221;.</p>

<p>You won&#8217;t find &#8220;null contagion&#8221; proposed as an implementation technique on the web.  What you&#8217;ll find is the Maybe Monad.</p>

<p><hr/></p>

<p class="footnote" id="fn1"><sup>1</sup> It would be sad if this were an entire function.  That would indicate that the function that <em>contains</em> <code>displayMerchantName</code> is just a <em>wrapper</em> for <code>displayMerchantName</code>, to protect it from being called when there isn&#8217;t a Product with an Offering with a Merchant.  Having to define a new function to wrap each instance of a common pattern is like having to define a new word to name the reference of each noun phrase. It&#8217;s reminiscent of the boilerplate getters and setters in logorrheic enterprise code.</p>

<p class="footnote" id="fn2"><sup>2</sup> &#8220;Repetition&#8221; is defined as &#8220;a host site for a defect infection&#8221;.</p>

<p class="footnote" id="fn3"><sup>3</sup> JavaScript has more than one null object.  This code takes advantage of the fact that an Object (even one with no properties) is <em>never</em> null, while <code>undefined</code> &#8212; the value of an undefined property access &#8212; <em>is</em> null.</p>]]></content:encoded>
			<wfw:commentRss>http://osteele.com/archives/2007/12/cheap-monads/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>One-Line JavaScript Memoization</title>
		<link>http://osteele.com/archives/2006/04/javascript-memoization</link>
		<comments>http://osteele.com/archives/2006/04/javascript-memoization#comments</comments>
		<pubDate>Sun, 16 Apr 2006 23:58:50 +0000</pubDate>
		<dc:creator>Oliver</dc:creator>
				<category><![CDATA[Essays]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://osteele.com/2006/04/16/one-line-javascript-memoization</guid>
		<description><![CDATA[Computing the length of a Bezier curve is expensive, but the length of a given Bezier doesn't change over time.  In my "JavaScript Bezier implementation":/archives/2006/02/javascript-beziers, I wanted to compute the length only the first time it's need, and save this result in order to return instantly thereafter.

This is a special case of "memoization":http://en.wikipedia.org/wiki/Memoization.  There are well-known strategies for implementing memoization.  But <code>getLength</code> is a "nullary":http://en.wikipedia.org/wiki/Arity function,  and there's a trick for implementing memoization of nullary methods in a dynamic language such as JavaScript (or Python or Ruby).  In these languages, you can memoize a nullary method by adding one line to it, without any support libraries.  This line replaces the method by a constant function, that returns the computed value. This memoization strategy is also more efficient than the general-purpose solution that non-nullary methods require.]]></description>
			<content:encoded><![CDATA[<p>Computing the length of a Bezier curve is expensive, but the length of a given Bezier doesn&#8217;t change over time.  In my <a href="/archives/2006/02/javascript-beziers">JavaScript Bezier implementation</a>, I wanted to compute the length only the first time it&#8217;s need, and save this result in order to return instantly thereafter.</p>

<p>This is a special case of <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a>.  There are well-known strategies for implementing memoization.  But <code>getLength</code> is a <a href="http://en.wikipedia.org/wiki/Arity">nullary</a> function,  and there&#8217;s a trick for implementing memoization of nullary methods in a dynamic language such as JavaScript (or Python or Ruby).  In these languages, you can memoize a nullary method by adding one line to it, without any support libraries.  This line replaces the method by a constant function, that returns the computed value. This memoization strategy is also more efficient than the general-purpose solution that non-nullary methods require.</p>

<h3>Memoizing by Hand</h3>

<p>The naive way to implement memoization is to store the value in a property the first time it&#8217;s computed, and test for the presence of the property thereafter:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>._length<span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>length <span style="color: #339933;">===</span> undefined<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive computation</span>
    <span style="color: #000066; font-weight: bold;">this</span>._length <span style="color: #339933;">=</span> length<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>or:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'_length'</span> <span style="color: #000066; font-weight: bold;">in</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>._length<span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive computation</span>
  <span style="color: #000066; font-weight: bold;">this</span>._length <span style="color: #339933;">=</span> length<span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>There are some problems with these solutions.  First, they&#8217;re verbose.  Worse, the domain logic (the line labelled &#8220;expensive computation&#8221;) and the memoization logic (the code that accesses <code>length</code> and <code>this._length</code>) are tangled up with each other.</p>

<p>These implementations also require a private property for each memoized method.  And then there&#8217;s a (minor) performance hit too: it takes a few instructions, each time, just to discover that the return value has already been computed.</p>

<h3>The Big Gun</h3>

<p>The standard solution to the first two of the problems above (the length and structure of the implementation) is to write a higher-order-function, that creates a memoizing function from a non-memoizing one.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">Function</span>.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">memoize</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> fn <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> cacheName <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// create a unique property name</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> key <span style="color: #339933;">=</span> serialize<span style="color: #009900;">&#40;</span>arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> cache <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#91;</span>cacheName<span style="color: #009900;">&#93;</span> <span style="color: #339933;">||</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#91;</span>cacheName<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> key <span style="color: #000066; font-weight: bold;">in</span> cache <span style="color: #339933;">?</span> cache<span style="color: #009900;">&#91;</span>key<span style="color: #009900;">&#93;</span> <span style="color: #339933;">:</span>
      cache<span style="color: #009900;">&#91;</span>key<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> fn.<span style="color: #660066;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #339933;">,</span> arguments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p> (Keith Gaughan has a complete implementation <a href="http://talideon.com/weblog/2005/07/javascript-memoization.cfm">here</a>.)  Then you can use it thus:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive compuation</span>
  <span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>.<span style="color: #660066;">memoize</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>This is the best general-purpose solution, and it&#8217;s good for a framework, or for a complete application.  But in a small standalone code library such as <a href="/sources/javascript/bezier.js">this</a> or <a href="/sources/javascript/gradient.js">this</a>, I don&#8217;t want to include a copy of <code>Function.prototype.memoize</code> in each standalone file (and then worry about version skew); and I don&#8217;t want to make each file depend on a utility file (and then worry about file dependencies).</p>

<h3>The One-Liner</h3>

<p>A nullary function such as <code>getLength</code> is a special case of functions in general, and there&#8217;s a particular technique<sup class="footnote"><a href="#fn1">1</a></sup> for memoizing it, that fits on a single line.</p>

<p>Here&#8217;s the first variant.&Acirc;&nbsp; This is less source code that the version above, and uses fewer instructions to retrieve a memoized value.  (In fact, it uses the fewest possible number of instructions, if the <span class="caps">API </span>for retrieving a value requires a function call at all.)  It&#8217;s an extra line (the assignment to <code>this.getLength</code>) that you can stick in a nullary method, that memoizes the method&#8217;s value on a per-instance basis.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive computation</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>The second variant moves the return  and the assignment to the same line.  Think of this line as a &#8220;memoizing return statement&#8221;.  It comes at the cost of more opaque code, and an extra function call. (The overhead of a function call is probably not a problem if the computation is expensive enough to be worth memoizing anyway.)  And although it&#8217;s not a style I would use for general-purpose programming, I find it acceptable in an idiom<sup class="footnote"><a href="#fn2">2</a></sup>.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive computation</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<h3>Another Use</h3>

<p>You can use a similar technique to prevent a function from being called twice.&Atilde;‚&Acirc;&nbsp; This is even simpler, since you don&Atilde;&cent;&acirc;‚&not;&acirc;„&cent;t need to keep track of the value.&Atilde;‚&Acirc;&nbsp; For example (from <a href="/sources/javascript/docs/gradients">gradients.js</a>):</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">OSGradients.<span style="color: #660066;">initialize</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
  OSGradients.<span style="color: #660066;">initialize</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  ... <span style="color: #006600; font-style: italic;">// initialization</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<h3>Avoiding Memory Leaks</h3>

<p>The inner function captures the variables from the outer function.  In the method below, <code>temp</code> will never be deallocated, until the instance that <code>getLength</code> has been applied to (and that the constant version of <code>getLength</code> is therefore now attached to) has been deallocated.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> temp <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Array<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">10000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive computation</span>
  <span style="color: #006600; font-style: italic;">// the following line captures length and temp:</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>If there are large temporaries, or pointers to <span class="caps">DOM </span>elements that may be deleted later, you should either detach them before you exit the outer function body:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> temp <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Array<span style="color: #009900;">&#40;</span><span style="color: #CC0000;">10000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ... <span style="color: #006600; font-style: italic;">// expensive computation</span>
  temp <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">// so the value won't be captured</span>
  <span style="color: #006600; font-style: italic;">// the following line captures length and work:</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> length<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>or use a helper function that closes over just the return value:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Function.K(value) is a constant-valued function that returns</span>
<span style="color: #006600; font-style: italic;">// value.</span>
<span style="color: #003366; font-weight: bold;">Function</span>.<span style="color: #660066;">K</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>value<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> value<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
Bezier.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> temp <span style="color: #339933;">=</span> ...
  <span style="color: #003366; font-weight: bold;">var</span> length <span style="color: #339933;">=</span> ...
  <span style="color: #006600; font-style: italic;">// the following line only captures length:</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getLength</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">Function</span>.<span style="color: #660066;">K</span><span style="color: #009900;">&#40;</span>length<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<h3>Thunks for the Memories</h3>

<p>Although I didn&#8217;t realize it until later (when I was writing my Bezier library, coming at this more from the &#8220;how can I cache this value&#8221; perspective than from a &#8220;theory of memoization and programming language implementation&#8221; perspective), this is nothing more than an implementation of <a href="http://en.wikipedia.org/wiki/Thunk">thunks</a> for JavaScript.</p>

<p>In a lazy (or call-by-need) language such as Haskell, memoization comes for free.  A variable with an initializer has the same syntax and semantics as a function; the initializer is evaluated once, the first time the variable is referenced, and then cached.</p>

<p>A referentially transparent nullary function has the syntax of a function, but the semantics of a value.  (In Haskell, the syntax is the same too.)  By memoizing it, we&#8217;re making this value <a href="http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_need">call-by-need</a>.  One technique for implementing call-by-need (or &#8220;lazy&#8221;) values is to create a thunk that replaces its computation by its value the first time it&#8217;s evaluated.  In JavaScript, we can implement these semantics but have to stick with the function-call syntax.</p>

<h3>Beyond Thunks</h3>

<p>There&#8217;s three directions to go from here, but all of them involve giving up the single-line solution.</p>

<p>First, it&#8217;s a bother that a method has to know its own name.  This means you can&#8217;t paste the same line of code into each memoized function.  This is the only way, however, that the method can replace itself with the constant function<sup class="footnote"><a href="#fn3">3</a></sup>.  You can eliminate the need to type the name twice, if give up both the no-helpers requirement and the optimization that a memoized function doesn&#8217;t test any conditions the second time it is called.  (The higher-order function in the section &#8220;The Big Gun&#8221; does this.)</p>

<p>Second, you can memoize non-nullary functions by getting out the big gun too.  In this case the replace-yourself optimization is useless too, since each invocation needs to check whether the value has already been computed <em>for these arguments</em>, regardless of how many times the function has been invoked before.</p>

<p>A third extension lets you hang onto the optimization, but takes more than a line of code (and therefore, realistically, depends on a support function).  It&#8217;s for the case where the return value depends upon the object state, and that state is <em>mutable</em>.  In this case, you need a way to reset the memoized function to its initial state, so that it will perform the computation the next time it&#8217;s called.  For example, <code>setRadians</code> below resets <code>getDegrees</code> so that the multiplication happens again upon the first call <code>getDegrees</code> after each time <code>setRadians</code> is called.  (This example isn&#8217;t a realistic candidate for memoization, but pretend multiplication is really really really slow.)</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> Angle<span style="color: #009900;">&#40;</span>radians<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">setRadians</span><span style="color: #009900;">&#40;</span>radians<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span>
Angle.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">setRadians</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>radians<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">radians</span> <span style="color: #339933;">=</span> radians<span style="color: #339933;">;</span>
  <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">getDegrees</span>.<span style="color: #660066;">reset</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
Angle.<span style="color: #660066;">prototype</span>.<span style="color: #660066;">getDegrees</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">radians</span> <span style="color: #339933;">*</span> <span style="color: #CC0000;">180</span> <span style="color: #339933;">/</span> Math.<span style="color: #660066;">PI</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
memoizeConstantMethod<span style="color: #009900;">&#40;</span>Angle.<span style="color: #660066;">prototype</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'getDegrees'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>




<p>Here&#8217;s a long but marginally readable implementation of <code>memoizeConstantMethod</code>:</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> memoizeConstantMethod<span style="color: #009900;">&#40;</span>object<span style="color: #339933;">,</span> property<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> f <span style="color: #339933;">=</span> object<span style="color: #009900;">&#91;</span>property<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> mf <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> value <span style="color: #339933;">=</span> f.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003366; font-weight: bold;">var</span> kf <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> value<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
    kf.<span style="color: #660066;">reset</span> <span style="color: #339933;">=</span> reset<span style="color: #339933;">;</span>
    object<span style="color: #009900;">&#91;</span>property<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> kf<span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> value<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  <span style="color: #003366; font-weight: bold;">var</span> reset <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    object<span style="color: #009900;">&#91;</span>property<span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> mf<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
  mf.<span style="color: #660066;">reset</span> <span style="color: #339933;">=</span> reset<span style="color: #339933;">;</span>
  reset<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p>And here&#8217;s a shorter version, that sacrifices the remaining readability for source code size<sup class="footnote"><a href="#fn4">4</a></sup>.</p>


<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> memoizeConstantMethod<span style="color: #009900;">&#40;</span>o<span style="color: #339933;">,</span> p<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> f <span style="color: #339933;">=</span> o<span style="color: #009900;">&#91;</span>p<span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span> mf<span style="color: #339933;">,</span> value<span style="color: #339933;">;</span>
  <span style="color: #003366; font-weight: bold;">var</span> s <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>v<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> o<span style="color: #009900;">&#91;</span>p<span style="color: #009900;">&#93;</span><span style="color: #339933;">=</span>v<span style="color: #339933;">||</span>mf<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#40;</span>mf <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #009900;">&#40;</span>s<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><span style="color: #000066; font-weight: bold;">return</span> value<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">reset</span> <span style="color: #339933;">=</span> mf.<span style="color: #660066;">reset</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">return</span> value <span style="color: #339933;">=</span> f.<span style="color: #660066;">call</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">reset</span> <span style="color: #339933;">=</span> s<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>




<p><ins>Update: Peter Michaux has a nicely written description of a similar technique <a href="http://peter.michaux.ca/article/3556">here</a>.</ins></p>

<p><hr/></p>

<p class="footnote" id="fn1"><sup>1</sup> Memoization in general requires a finite map (or &#8220;hash&#8221;) from argument lists to result values.  In the special case where the function is nullary, you don&#8217;t need a map, because the empty list is the only key.</p>

<p class="footnote" id="fn2"><sup>2</sup> Just as I don&#8217;t need to understand what the tabs are in an English idiom such as &#8220;keep tabs on&#8221;, I don&#8217;t need to easily read a programming language idiom compositionally each time I see it.</p>

<p class="footnote" id="fn3"><sup>3</sup> You can&#8217;t search the object and its prototype chain for a function that&#8217;s <code>===</code> to the one being replaced, because the same function might be present at different property names.</p>

<p class="footnote" id="fn4"><sup>4</sup> This is written in might be called the &#8220;<a href="http://redhanded.hobix.com/">_why</a> <a href="http://en.wikipedia.org/wiki/Combinator">combinator</a>&#8221; style of programming.</p>]]></content:encoded>
			<wfw:commentRss>http://osteele.com/archives/2006/04/javascript-memoization/feed</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>Better Living Through Bigger Text</title>
		<link>http://osteele.com/archives/2004/09/bigger-text</link>
		<comments>http://osteele.com/archives/2004/09/bigger-text#comments</comments>
		<pubDate>Tue, 21 Sep 2004 22:10:08 +0000</pubDate>
		<dc:creator>Oliver</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://osteele.com/2004/09/21/better-living-through-bigger-text</guid>
		<description><![CDATA[Today my office is an airplane.  I'm visiting the "home office":http://www.laszlosystems.com in San Francisco for the week.  I get to remind everyone that those of us in the Boston office are real people (insert your favorite joke here), and come back with enough to understand what's behind the email and phone conferences for another month.

One of the geek games you can play on an airplane is stretching out the battery life of your computer.  I have enough batteries to last me through a six-hour flight now, but old habits die hard.

Since I save my files every minute or two, spinning down the hard disk isn't an option.  (I tend to use programs that communicate use the file system to communicate.  And I don't want to be in a position to lose more than a few minutes of work anyway.)  I don't usually use a CD or DVD player, so I'm already optimizing there.  The CPU that I'm using steps down to 800MHz when the plug is out, so that's taken care of for me.  That leaves screen brightness.]]></description>
			<content:encoded><![CDATA[<p>Today my office is an airplane.  I&#8217;m visiting the <a href="http://www.laszlosystems.com">home office</a> in San Francisco for the week.  I get to remind everyone that those of us in the Boston office are real people (insert your favorite joke here), and come back with enough to understand what&#8217;s behind the email and phone conferences for another month.</p>

<p>One of the geek games you can play on an airplane is stretching out the battery life of your computer.  I have enough batteries to last me through a six-hour flight now, but old habits die hard.</p>

<p>Since I save my files every minute or two, spinning down the hard disk isn&#8217;t an option.  (I tend to use programs that communicate use the file system to communicate.  And I don&#8217;t want to be in a position to lose more than a few minutes of work anyway.)  I don&#8217;t usually use a CD or <span class="caps">DVD </span>player, so I&#8217;m already optimizing there.  The <span class="caps">CPU </span>that I&#8217;m using steps down to 800MHz when the plug is out, so that&#8217;s taken care of for me.  That leaves screen brightness.</p>

<p>The problem with turning down the screen brightness is that this also turns down my reading speed.  I&#8217;ve noticed that I read a lot faster when I&#8217;m reading higher-contrast text.  Since I already use black text on a white background, the contrast is proportional to the screen brightness (as long as the overhead light is off).</p>

<p>This effect matters most when I&#8217;m reading English.  When I&#8217;m reading math or code, or writing anything, my word recognition time, which is the part of the pipeline modulated by the contrast, isn&#8217;t the bottleneck anyway &#8212; in those cases I&#8217;m limited by comprehension time, or by other central abilities.  So I used to turn the brightness up when I&#8217;m reading, and turn it down the rest of the time.</p>

<p>Let&#8217;s call this the <dfn>contrast modulation strategy</dfn>.  It trades off reading speed against battery life, based on the current activity (reading versus other work).  The contrast modulation strategy works if I&#8217;m spending long stretches of time reading, or not-reading.  It&#8217;s a pain if I&#8217;m going back and forth &#8212; referring to one document while I&#8217;m writing another, for instance.</p>

<p>Here&#8217;s today&#8217;s discovery: my reading speed is <strong>also</strong> proportional to the <strong>text size</strong>.  I just ran a few informal comparisons, and setting my document zoom to 200% at the lowest brightness works just as well as turning the brightness all the way up.  (With a large font, it doesn&#8217;t seem to matter how bright the screen is, at least within the range that my screen adjusts to.)</p>

<p>With larger text (a larger font size, or a greater zoom), I have to scroll more, but when I&#8217;m reading English I don&#8217;t need to see more than a few paragraphs for continuity anyway.  When I&#8217;m reading code I want to see as many lines as possible (this one reason I prefer concise programming languages, so I can see several different levels of structure without having commit as much to my mental buffers so that I can scroll) and technical documents always seem to refer to tables and figures a page away, which makes for a lot of scrolling, anyway.  So I want big fonts for English that I&#8217;m reading, and small fonts for everything else.  But font size, unlike screen brightness, is something you can associate with a specific document.</p>

<p>Let&#8217;s call this the <dfn>text size modulation strategy</dfn>.  The text size modulation strategy trades reading speed off against the amount of the document that&#8217;s simultaneously visible.  The text size modulation strategy takes decouples the trade-off between reading speed and battery life and, unlike the contrast modulation strategy, it&#8217;s automatic once you zoom your documents, no matter how many times you switch between them.</p>]]></content:encoded>
			<wfw:commentRss>http://osteele.com/archives/2004/09/bigger-text/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

