<?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>Digital Digressions by Stuart Sierra</title>
	
	<link>http://stuartsierra.com</link>
	<description>From programming to everything else</description>
	<lastBuildDate>Thu, 04 Apr 2013 13:50:58 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/StuartSierra" /><feedburner:info uri="stuartsierra" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>On the Perils of Dynamic Scope</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/Y1cklyFIA-U/perils-of-dynamic-scope</link>
		<comments>http://stuartsierra.com/2013/03/29/perils-of-dynamic-scope#comments</comments>
		<pubDate>Fri, 29 Mar 2013 13:00:52 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[scope]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=710</guid>
		<description><![CDATA[Common Lisp the Language (CLtL) devotes an entire chapter to the subject of Scope and Extent. It defines scope as the textual region of a program in which an entity may be used, where &#8220;entity&#8221; could be a symbol, a value, or something more abstract like a variable binding. So scope is about where you [...]]]></description>
				<content:encoded><![CDATA[<p><i>Common Lisp the Language</i> (CLtL) devotes an entire chapter to the subject of <a href="http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node43.html">Scope and Extent</a>. It defines <b>scope</b> as the textual region of a program in which an entity may be used, where &#8220;entity&#8221; could be a symbol, a value, or something more abstract like a variable binding.
</p>
<p>
So scope is about <i>where</i> you can use something. CLtL defines two different kinds of scope:
</p>
<p>
<b>Lexical scope</b> is usually the body of a single expression like <code>let</code> or <code>defun</code>.
</p>
<p>
<b>Indefinite scope</b> is everything else, effectively the global set of symbols that exist in a program.
</p>
<p>
In contrast, <b>extent</b> is about <i>when</i>: it&#8217;s the interval of time during which something may be used. CLtL defines two different kinds of extent:
</p>
<p>
<b>Dynamic extent</b> refers to things that exist for a fixed period of time and are explicitly &#8220;destroyed&#8221; at the end of that period, usually when control returns to the code that created the thing.
</p>
<p>
<b>Indefinite extent</b> is everything else: things that get created, passed around, and eventually garbage-collected.
</p>
<p>
In any language with a garbage collector, most things have indefinite extent. You can create strings, lists, or hash tables and pass them around with impunity. When the garbage collector determines that you are done using something, it reclaims the memory. The process is, in most cases, completely transparent to you.
</p>
<p>
But what about the so-called <b>dynamic scope</b>? The authors of CLtL have this to say:
</p>
<blockquote>
<p>The term &#8220;dynamic scope&#8221; is a misnomer. Nevertheless it is both traditional and useful.
</p>
</blockquote>
<p>
They also define &#8220;dynamic scope&#8221; to be the combination of <i>indefinite scope</i> and <i>dynamic extent</i>. That is, things with dynamic scope are valid in any <i>place</i> in a program, but only for a limited <i>time</i>. In Common Lisp, these are called &#8220;special variables,&#8221; and are created with the macros <a href="http://www.lispworks.com/documentation/HyperSpec/Body/m_defpar.htm"><code>defparameter</code> and <code>defvar</code></a>.
</p>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1">Vars</h2>
<div class="outline-text-2" id="text-1">
<p>
So what does this have to do with Clojure? Clojure has these things called Vars. Every time you write <code>def</code> or <code>defn</code> or one of its variants in Clojure, you&#8217;re creating a Var.
</p>
<p>
Vars have <i>indefinite scope</i>: no matter where you <code>def</code> a Var, it&#8217;s visible everywhere in the program.<sup><a class="footref" name="fnr.1" href="#fn.1">1</a></sup>
</p>
<p>
Vars usually have <i>indefinite extent</i> as well. Usually. This is where things get tricky. Clojure, unlike Common Lisp, was designed for multi-threaded programs.<sup><a class="footref" name="fnr.2" href="#fn.2">2</a></sup> The meaning of <i>extent</i> gets a lot muddier in the face of multiple threads. Each thread has its own timeline, its own view of &#8220;now&#8221; which may or may not conform to any other thread&#8217;s view.
</p>
<p>
In Clojure versions 1.2 and earlier, <b>all</b> Vars had dynamic scope by default, but this meant that there was a performance cost to look up the current dynamic binding of a Var on every function call. Leading up to 1.3, Rich Hickey experimented with allowing Vars to be declared <code>^:static</code>, before settling on static by default with <code>^:dynamic</code> as an option. You can still find <code>^:static</code> declarations littered through the Clojure source code. Maybe someday they&#8217;ll be useful again.
</p>
<p>
The definition of &#8220;dynamic scope&#8221; in Clojure is even fuzzier than it is in Common Lisp. How do we define &#8220;extent&#8221; in the face of multiple threads, each potentially with its own thread-local binding? If a resource can be shared across multiple threads, we have to coordinate the cleanup of that resource. For example, if I open a socket and then hand it off to another piece of code, who is responsible for closing the socket?
</p>
<p>
Resource management is one concurrency bugaboo that Clojure developers have not managed to crack. Various attempts have been made: you can see the artifacts in wiki and mailing list discussions of <a href="http://dev.clojure.org/display/design/Resource+Scopes">Resource Scopes</a>. So far, no solution has been found that doesn&#8217;t just shift the problem somewhere else.
</p>
<p>
It ends up looking a bit like garbage collection: how do I track the path of every resource used by my program and ensure that it gets cleaned up at the appropriate time? But it&#8217;s even harder than that, because resources like file handles and sockets are much scarcer than memory: they need to be reclaimed as soon as possible. In a modern runtime like the JVM, garbage collection is stochastic: there&#8217;s no guarantee that it will happen at any particular time, or even that it will happen at all.
</p>
<p>
To make matters worse, Clojure has laziness to contend with. It&#8217;s entirely possible to obtain a resource, start consuming it via a lazy sequence, and <i>never finish</i> consuming it.
</p>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2">The Wrong Solution</h2>
<div class="outline-text-2" id="text-2">
<p>
This brings me to one of my top <a href="http://c2.com/cgi/wiki?AntiPattern">anti-patterns</a> in Clojure: the Dynamically-Scoped Singleton Resource (DSSR).
</p>
<p>
The DSSR is popular in libraries that depend on some external resource such as a socket, file, or database connection. It typically looks like this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">ns</span> com.example.library)

(<span class="org-keyword">def</span> <span class="org-constant">^:dynamic</span> <span class="org-function-name">*resource*</span>)

(<span class="org-keyword">defn-</span> <span class="org-function-name">internal-procedure</span> []
  <span class="org-comment-delimiter">;; </span><span class="org-comment">... uses *resource* ...</span>
  )

(<span class="org-keyword">defn</span> <span class="org-function-name">public-api-function</span> [arg]
  <span class="org-comment-delimiter">;; </span><span class="org-comment">... calls internal-procedure ...</span>
  )
</pre>
<p>
That is, there is a single dynamic Var holding the &#8220;resource&#8221; on which the rest of the API operates. The DSSR is often accompanied by a <code>with-*</code> macro:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defmacro</span> <span class="org-function-name">with-resource</span> [src &amp; body]
  `(<span class="org-keyword">binding</span> [*resource* (acquire src)]
     (<span class="org-keyword">try</span> ~@body
       (<span class="org-keyword">finally</span>
         (dispose *resource*)))))
</pre>
<p>
This looks harmless enough. It&#8217;s practically a carbon copy of Clojure&#8217;s <code>with-open</code> macro, and it ensures that the resource will get cleaned up even if <code>body</code> throws an exception.
</p>
<p>
The problem with this pattern, especially in libraries, is the constraints it imposes on any code that wants to use the library. The <code>with-resource</code> macro severely constrains what you can do in the <code>body</code>:
</p>
<p>
<b>You can&#8217;t dispatch to another thread.</b> Say goodbye to Agents, Futures, thread pools, non-blocking I/O, or any other kind of asynchrony. The resource is only valid on the current thread.<sup><a class="footref" name="fnr.3" href="#fn.3">3</a></sup>
</p>
<p>
<b>You can&#8217;t return a lazy sequence</b> backed by the resource because the resource will be destroyed as soon as <code>body</code> returns.
</p>
<p>
<b>You can&#8217;t have more than one resource at a time.</b> Hence the &#8220;singleton&#8221; in the name of this pattern. Using a thread-bound Var throughout the API means that you can never operate on more than one instance of the resource in a single thread. Lots of apps need to work with multiple databases, which really sucks using this kind of library.
</p>
<p>
The last problem with this pattern is a more subtle one: <b>hidden dependencies</b>. The public API functions, which have global scope, depend on the state (thread-local binding) of another Var with global scope. This dependency isn&#8217;t explicitly stated anywhere in the definition of those functions. That might not seem like such a big deal in small examples, and it isn&#8217;t. But as programs (and development teams) grow larger, it&#8217;s one additional piece of implicit knowledge that you have to keep in your head. If there are seventeen layers of function calls between the resource binding and its usage, how certain are you going to be that the resource has the right extent?
</p>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3">Friends Don&#8217;t Let Friends Use Dynamic Scope</h2>
<div class="outline-text-2" id="text-3">
<p>
The alternative is easy: don&#8217;t do it. Don&#8217;t try to &#8220;solve&#8221; resource management in every library.
</p>
<p>
By all means, provide the functions to acquire and dispose of resources, but then let the application programmer decide what to do with them. Define API functions to take the resource as an argument.
</p>
<p>
Applications can manage their own resources, and only the application programmer knows what the extent of those resources should be. Maybe you can pass it around as a value. Maybe you want to use dynamic binding after all. Maybe you want to stash it in a global state Var.<sup><a class="footref" name="fnr.4" href="#fn.4">4</a></sup> That&#8217;s for you to decide.
</p>
<p>
<a href="http://datomic.com/">Datomic</a> is a good example to follow: it creates connection objects that have a lot of state attached to them &mdash; sockets, queues, and threads. But it says nothing about how you should manage the extent of those connections.<sup><a class="footref" name="fnr.5" href="#fn.5">5</a></sup> Most functions in the <a href="http://docs.datomic.com/clojure/index.html">Datomic API</a> take either a connection or a database (a value obtained from the connection) as an argument.
</p>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4">Safe Dynamic Scope</h2>
<div class="outline-text-2" id="text-4">
<p>
So dynamic scope is totally evil, right? Not totally. There are situations where dynamic scope can be helpful without causing the cascade of problems I described above.
</p>
<p>
Remember that dynamic scope in Clojure is really <i>thread-local binding</i>. Therefore, it&#8217;s best suited to operations that are <i>confined to a single thread</i>. There are plenty of examples of this: most popular algorithms are single-threaded, after all. Consider the classic <a href="http://www.cs.engr.uky.edu/~lewis/essays/compilers/rec-des.html">recursive-descent parser</a>: you start with one function call at the top and you&#8217;re not done until that function returns. The entire operation happens on a single thread, in a single call stack. It has <b>dynamic extent</b>.
</p>
<p>
I took advantage of this fact in a <a href="https://github.com/clojure/data.json">Clojure JSON parser</a>. There were a number of control flags that I needed to make available to all the functions. Rather than pass around extra arguments all over the place, I created <a href="https://github.com/clojure/data.json/blob/data.json-0.2.1/src/main/clojure/clojure/data/json.clj#L20-L22">private dynamic Vars</a> to hold them. Those Vars get <a href="https://github.com/clojure/data.json/blob/data.json-0.2.1/src/main/clojure/clojure/data/json.clj#L263-L265">bound in the entry-point</a> to the parser, based on options passed in as arguments to the public API function. The thread-local state never leaks out of the initial function call.
</p>
<p>
As another example, the Clojure compiler, although written in Java, <a href="https://github.com/clojure/clojure/blob/clojure-1.5.1/src/jvm/clojure/lang/Compiler.java#L181-L203">uses dynamic Vars</a> to keep track of internal state.
</p>
<p>
And what about our friend <code>with-open</code>? I said that the example <code>with-resource</code> macro was nearly a copy of it, but only nearly. <code>clojure.core/with-open</code> creates <b>lexical</b> (i.e. local) bindings. It still suffers from some limitations around what you can do in the body, but at least it doesn&#8217;t limit you to one resource at a time.
</p>
<p>
Global state is the zombie in the closet of every Clojure program, about which I&#8217;ll have more to say in future posts. For now, I hope I&#8217;ve convinced you that dynamic scope is easily abused and has a lot of unintended consequences.
</p>
<div id="footnotes">
<h2 class="footnotes">Footnotes: </h2>
<div id="text-footnotes">
<p class="footnote"><sup><a class="footnum" name="fn.1" href="#fnr.1">1</a></sup> Technically, a Var is visible only <b>after</b> the point at which it was defined. This is significant with regard to the order of definitions, but Vars are still globally visible once they have been defined.
</p>
<p class="footnote"><sup><a class="footnum" name="fn.2" href="#fnr.2">2</a></sup> CLtL has this note embedded in the chapter on scope and extent: &#8220;Behind the assertion that dynamic extents nest properly is the assumption that there is only a single program or process. Common Lisp does not address the problems of multiprogramming (timesharing) or multiprocessing (more than one active processor) within a single Lisp environment.&#8221; Modern Common Lisp implementations have added multi-threading, but it remains absent from the language specification.
</p>
<p class="footnote"><sup><a class="footnum" name="fn.3" href="#fnr.3">3</a></sup> You can use <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/bound-fn">bound-fn</a> to capture the bindings and pass them to another thread, but you still have the problem that the resource may be destroyed before the other thread is finished with it.
</p>
<p class="footnote"><sup><a class="footnum" name="fn.4" href="#fnr.4">4</a></sup> Not recommended, to be discussed in a future post.
</p>
<p class="footnote"><sup><a class="footnum" name="fn.5" href="#fnr.5">5</a></sup> There&#8217;s some caching of connection objects under the hood, but this is not relevant to the consumer.
</p>
</div>
</div>
</div>
</div>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/Y1cklyFIA-U" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2013/03/29/perils-of-dynamic-scope/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2013/03/29/perils-of-dynamic-scope</feedburner:origLink></item>
		<item>
		<title>Affordance and Concision</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/JInsqqinpQ4/affordance-concision</link>
		<comments>http://stuartsierra.com/2013/02/04/affordance-concision#comments</comments>
		<pubDate>Mon, 04 Feb 2013 13:28:52 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=693</guid>
		<description><![CDATA[Quick, Clojure programmers, what does the following expression do? (get x k) If you answered, It looks up the key k in an associative data structure x and returns its associated value, you&#8217;re right, but only partially. What if x is not an associative data structure? In every released version of Clojure up to and [...]]]></description>
				<content:encoded><![CDATA[<p>Quick, Clojure programmers, what does the following expression do?
</p>
<pre class="src src-clojure">(<span class="org-builtin">get</span> x k)
</pre>
<p>
If you answered, <i>It looks up the key <code>k</code> in an associative data structure <code>x</code> and returns its associated value</i>, you&#8217;re right, but only partially.
</p>
<p>
What if <code>x</code> is not an associative data structure? In every released version of Clojure up to and including 1.5.0, <code>get</code> will return <code>nil</code> in that case.
</p>
<p>
Is that a bug or a feature? It can certainly lead to some hard-to-find bugs, such as this one which I&#8217;ve often found in my own code:
</p>
<pre class="src src-clojure">(<span class="org-keyword">def</span> <span class="org-function-name">person</span> (<span class="org-builtin">ref</span> {<span class="org-constant">:name</span> <span class="org-string">"Stuart"</span> <span class="org-constant">:job</span> <span class="org-string">"Programmer"</span>}))

(<span class="org-builtin">get</span> person <span class="org-constant">:name</span>)
<span class="org-comment-delimiter">;;</span><span class="org-comment">=&gt; nil</span>
</pre>
<p>
Spot the bug? <code>person</code> is not a map but rather a Ref whose state is a map. I should have written <code>(get @person :name)</code>. One character between triumph and defeat! To make matters worse, that <code>nil</code> might not show up until it triggers a NullPointerException several pages of code later.
</p>
<p>
It turns out that several core functions in Clojure behave this way: if called on an object which does not implement the correct interface, they return <code>nil</code> rather than throwing an exception.
</p>
<p>
The <code>contains?</code> function is a more bothersome example. Not only is the name difficult to remember &mdash; it&#8217;s an associative function that checks for keys, not a linear search of values like <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#contains(java.lang.Object)">java.util.Collection#contains</a> &mdash; but it also returns <code>nil</code> on functions which do not implement <a href="https://github.com/clojure/clojure/blob/clojure-1.4.0/src/jvm/clojure/lang/Associative.java">clojure.lang.Associative</a>. Or at least it did up through Clojure 1.4.0. I submitted a <a href="https://github.com/clojure/clojure/commit/3acb6ee7ec5c295ae14de861d03a5efd115a5968">patch</a> (<a href="http://dev.clojure.org/jira/browse/CLJ-932">CLJ-932</a>), included in Clojure 1.5.0, which changed <code>contains?</code> to throw an exception instead.<a class="footref" name="fnr.1" href="#fn.1">[1]</a>
</p>
<p>
I submitted a similar patch (<a href="http://dev.clojure.org/jira/browse/CLJ-1107">CLJ-1107</a>) to do the same thing for <code>get</code>, but not in time for consideration in the 1.5.0 release.
</p>
<p>
A few weeks later, I was writing some code that looked like this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defn</span> <span class="org-function-name">my-type</span> [x]
  (<span class="org-keyword">or</span> (<span class="org-builtin">get</span> x <span class="org-constant">:my-namespace/type</span>)
      (<span class="org-builtin">get</span> (<span class="org-builtin">meta</span> x) <span class="org-constant">:my-namespace/type</span>)
      (<span class="org-builtin">get</span> x <span class="org-constant">:type</span>)
      (clojure.core/<span class="org-builtin">type</span> x)))
</pre>
<p>
I wanted a flexible definition of &#8220;type&#8221; which worked on maps or records with different possible keys, falling back on the <code>clojure.core/type</code> function, which looks for a <code>:type</code> key in metadata before falling back to <code>clojure.core/class</code>.
</p>
<p>
Before the patch to <code>get</code> in CLJ-1107, this code works perfectly well. After the patch, it won&#8217;t. I would have to write this instead:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defn</span> <span class="org-function-name">my-type</span> [x]
  (<span class="org-keyword">or</span> (<span class="org-keyword">when</span> (<span class="org-builtin">associative?</span> x)
        (<span class="org-builtin">get</span> x <span class="org-constant">:my-namespace/type</span>))
      (<span class="org-builtin">get</span> (<span class="org-builtin">meta</span> x) <span class="org-constant">:my-namespace/type</span>)
      (<span class="org-keyword">when</span> (<span class="org-builtin">associative?</span> x)
        (<span class="org-builtin">get</span> x <span class="org-constant">:type</span>))
      (clojure.core/<span class="org-builtin">type</span> x)))
</pre>
<p>
But wait! The <code>meta</code> function also returns <code>nil</code> for objects which do not support metadata. Maybe that should be &#8220;fixed&#8221; too. Then I would have to write this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defn</span> <span class="org-function-name">my-type</span> [x]
  (<span class="org-keyword">or</span> (<span class="org-keyword">when</span> (<span class="org-builtin">associative?</span> x)
        (<span class="org-builtin">get</span> x <span class="org-constant">:my-namespace/type</span>))
      (<span class="org-keyword">when</span> (<span class="org-builtin">instance?</span> x <span class="org-preprocessor">clojure.lang.IMeta</span>)
        (<span class="org-builtin">get</span> (<span class="org-builtin">meta</span> x) <span class="org-constant">:my-namespace/type</span>))
      (<span class="org-keyword">when</span> (<span class="org-builtin">associative?</span> x)
        (<span class="org-builtin">get</span> x <span class="org-constant">:type</span>))
      (clojure.core/<span class="org-builtin">type</span> x)))
</pre>
<p>
And so on.
</p>
<p>
Every language decision means trade-offs. Clojure accepts <code>nil</code> as a logical false value in boolean contexts, like Common Lisp (and also many scripting languages). This &#8220;nil punning&#8221; enables a concise style in which <code>nil</code> stands in for an empty collection or missing data.<a class="footref" name="fnr.2" href="#fn.2">[2]</a> For example, Clojure 1.5.0 introduces two new macros <a href="https://github.com/clojure/clojure/blob/clojure-1.5.0-RC4/src/clj/clojure/core.clj#L6785-L6805"><code>some-&gt;</code> and <code>some-&gt;&gt;</code></a>, which keep evaluating expressions until one of them returns <code>nil</code>.
</p>
<p>
Is Clojure&#8217;s <code>get</code> wrong? It depends on what you think <code>get</code> should mean. If you&#8217;re a fan of more strictly-typed functional languages you might think <code>get</code> should be defined to return an instance of the <code>Maybe</code> monad:
</p>
<pre class="example">
;; made-up syntax:
get [Associative⟨K,V⟩, K] → Maybe⟨V⟩
</pre>
<p>
You can implement the <a href="http://onclojure.com/2009/03/05/a-monad-tutorial-for-clojure-programmers-part-1/">Maybe monad in Clojure</a>, but there&#8217;s less motivation to do so without the support of a static type checker. You could also argue that, since Clojure is dynamically-typed, <code>get</code> can have a more general type:
</p>
<pre class="example">
;; made-up syntax:
get [Any, Any] → Any | nil
</pre>
<p>
This latter definition is effectively the type of <code>get</code> in Clojure right now.
</p>
<p>
Which form is better is a matter of taste. What I do know is that the current behavior of <code>get</code> doesn&#8217;t give much <i>affordance</i> to a Clojure programmer, even an experienced one.<a class="footref" name="fnr.3" href="#fn.3">[3]</a>
</p>
<p>
Again, tradeoffs. Clojure&#8217;s definition of <code>get</code> is flexible but can lead to subtle bugs. The stricter version would be safer but less flexible.
</p>
<p>
An even stricter version of <code>get</code> would throw an exception if the key is not present instead of returning <code>nil</code>. Sometimes that&#8217;s what you want. The <a href="https://github.com/Datomic/simulant">Simulant testing framework</a> defines a utility function <a href="https://github.com/Datomic/simulant/blob/4d4580460a6aea917b74a923060c99dae906b3fc/src/simulant/util.clj#L23-L30"><code>getx</code></a> that does just that.
</p>
<p>
Over the past five years, Rich Hickey has gradually led Clojure in the direction of &#8220;fast but correct by default.&#8221; This is particularly evident in the <a href="http://dev.clojure.org/display/doc/Documentation+for+1.3+Numerics">numeric primitives since release 1.3.0</a>, which throw an exception on overflow (correct) but do not automatically promote from fixed- to arbitrary-precision types (slow).
</p>
<p>
I believe the change to <code>get</code> in CLJ-1107 will ultimately be more help than hindrance. But it might also be useful to have a function which retains the &#8220;more dynamic&#8221; behavior. We might call it <code>get'</code> in the manner of the auto-promoting arithmetic functions such as <code>+'</code>. Or perhaps, with some cleverness, we could define a higher order function that transforms <i>any</i> function into a function that returns <code>nil</code> when called on a type it does not support. This would be similar in spirit to <a href="http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/fnil"><code>fnil</code></a> but harder to define.<a class="footref" name="fnr.4" href="#fn.4">[4]</a>
</p>
<p><strong>Update #1:</strong> changed <code>(instance? x clojure.lang.Associative)</code> to <code>(associative? x)</code>, suggested by Luke VanderHart.</p>
<p><strong>Update #2:</strong> Some readers have pointed out that I could make <code>my-type</code>  polymorphic, thereby avoiding the conditional checks. But that would be even longer and, in my opinion, more complicated than the conditional version. The <code>get</code> function is already polymorphic, a fact which I exploited in the original definition of <code>my-type</code>. It&#8217;s a contrived example anyway, not a cogent design.</p>
<div id="footnotes">
<h2 class="footnotes">Footnotes: </h2>
<div id="text-footnotes">
<p class="footnote"><a class="footnum" name="fn.1" href="#fnr.1">[1]</a> We can&#8217;t do anything about the name of <code>contains?</code> without breaking a lot more code. This change, at least, is unlikely to break any code that wasn&#8217;t already broken.
</p>
<p class="footnote"><a class="footnum" name="fn.2" href="#fnr.2">[2]</a> There&#8217;s a <a href="http://www.apl.jhu.edu/~hall/lisp/Scheme-Ballad.text">cute poem about nil-punning</a> in Common Lisp versus Scheme or T.
</p>
<p class="footnote"><a class="footnum" name="fn.3" href="#fnr.3">[3]</a> I am slightly abusing the <a href="http://en.wikipedia.org/wiki/Affordance">definition of affordance</a> here, but I think it works to convey what I mean: the implementation of <code>get</code> in the Clojure runtime does not help me to write my code correctly.
</p>
<p class="footnote"><a class="footnum" name="fn.4" href="#fnr.4">[4]</a> I don&#8217;t actually know how to do it without catching <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html">IllegalArgumentException</a>, which would be bad for performance and potentially too broad. Left as an exercise for the reader!
</p>
</div>
</div>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/JInsqqinpQ4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2013/02/04/affordance-concision/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2013/02/04/affordance-concision</feedburner:origLink></item>
		<item>
		<title>A Brief Rant About Versioning</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/0OSP98NwwBo/brief-rant-about-versioning</link>
		<comments>http://stuartsierra.com/2013/01/28/brief-rant-about-versioning#comments</comments>
		<pubDate>Mon, 28 Jan 2013 15:07:37 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[rant]]></category>
		<category><![CDATA[versioning]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=688</guid>
		<description><![CDATA[Version numbers are meaningless. By that, I mean they convey no useful information. Oh sure, there are conventions: major.minor.patch, even/odd for stable/development versions, and designations like release candidate. But they&#8217;re just conventions. Version numbers are chosen by people, so they are subject to all the idiosyncrasies and whims of individuals. Semantic Versioning, you say? Pshaw. [...]]]></description>
				<content:encoded><![CDATA[<p>Version numbers are meaningless. By that, I mean they convey no useful information. Oh sure, there are conventions: <i>major.minor.patch</i>, even/odd for stable/development versions, and designations like <i>release candidate</i>. But they&#8217;re just conventions. Version numbers are chosen by people, so they are subject to all the idiosyncrasies and whims of individuals.
</p>
<p>
<a href="http://semver.org/">Semantic Versioning</a>, you say? Pshaw. Nobody does semantic versioning. If they did, we&#8217;d see dozens of libraries and applications with major-version numbers in the double or triple digits. It&#8217;s almost impossible to change software without breaking <b>something</b>. Even a change which is technically a bugfix can easily break a downstream consumer that relied, intentionally or not, on the buggy behavior.
</p>
<p>
That&#8217;s not to say you shouldn&#8217;t <i>try</i> to follow semantic versioning. It&#8217;s a good idea, and even its author admits that some versioning decisions boil down to <i>Use your best judgment</i>.
</p>
<p>
The trouble with semantic versioning is that everyone want <b>others</b> to follow it, but no one wants to follow it themselves. Everyone thinks <i>there&#8217;s room for one more quick fix</i>, or <i>this change isn&#8217;t big enough to warrant a major-version bump</i>, or simply <i>my project is special</i>. It&#8217;s a slippery slope from there to redesigning your entire API between versions <i>2.7.4-RC13</i> and <i>2.7.4-RC14</i>.
</p>
<p>
Everybody does it. I could name names, but that would be redundant. I&#8217;m not sitting in a glass house here, either. I caught major flack for breaking the API of a JSON parser &ndash; a JSON parser! &ndash; between two <i>0.x</i> releases. People don&#8217;t like change, even improvements, if it means the tiniest bit more work for them. Even if the new API is cleaner and more logical, even if you change things that were never explicitly promised by the old API, there will be grumbles and calls for your resignation. It&#8217;s enough to make you want to stop releasing things altogether, or to throw up your hands and just <a href="http://dev.clojure.org/display/design/ClojureScript+Releases">number all your releases sequentially</a>, or to go totally off the reservation a have your version numbers <a href="http://www.tex.ac.uk/cgi-bin/texfaq2html?label=TeXfuture">converge towards an irrational constant</a>.
</p>
<p><strong>Did I mention this was a rant? Please don&#8217;t take it too seriously.</strong></p>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/0OSP98NwwBo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2013/01/28/brief-rant-about-versioning/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2013/01/28/brief-rant-about-versioning</feedburner:origLink></item>
		<item>
		<title>The Reluctant Dictator</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/MOEkL6cTfv4/the-reluctant-dictator</link>
		<comments>http://stuartsierra.com/2013/01/16/the-reluctant-dictator#comments</comments>
		<pubDate>Thu, 17 Jan 2013 03:02:23 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[open-source]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=677</guid>
		<description><![CDATA[I have a confession to make. I&#8217;m bad at open-source. Not writing the code. I&#8217;m pretty good at that. I can even write pretty good documentation. I&#8217;m bad at all the rest: patches, mailing lists, chat rooms, bug reports, and anything else that might fall under the heading of &#8220;community.&#8221; I&#8217;m more than bad at [...]]]></description>
				<content:encoded><![CDATA[<p>I have a confession to make. I&#8217;m bad at open-source. Not writing the code. I&#8217;m pretty good at that. I can even write pretty good documentation. I&#8217;m bad at all the rest: patches, mailing lists, chat rooms, bug reports, and anything else that might fall under the heading of &#8220;community.&#8221; I&#8217;m more than bad at it: I don&#8217;t like doing it and generally try to avoid it.
</p>
<p>
I write software to scratch an itch. I release it as open-source in the vague hope that someone else might find it useful. But once I&#8217;ve scratched the itch, I&#8217;m no longer interested. I don&#8217;t want to found a &#8220;community&#8221; or try to herd a bunch of belligerent, independent-minded cats. I&#8217;m not in it for the money. I&#8217;m not even in it for the fame and recognition. (OK, maybe a little bit for the fame.)
</p>
<p>
But this age of &#8220;social&#8221; insists that <b>everything</b> be a community. Deoderant brands beg us to &#8220;like&#8221; their Facebook pages and advertising campaigns come accesorized with Twitter hash tags. In software, you can&#8217;t just release a bit of code as open-source. You have to create a Google Group and a blog and an IRC channel and a novelty Twitter account too.
</p>
<p>
The infrastructure of &#8220;social coding&#8221; has codified this trend into an expectation that every piece of open-source software participate in a world-wide collaboration / popularity contest. The only feature of <a href="https://github.com/">GitHub</a> that can&#8217;t be turned off is the <i>pull request</i>.
</p>
<p>
Don&#8217;t get me wrong, I love GitHub and use it every day. On work projects, I find pull requests to be an efficient tool for doing code reviews. GitHub&#8217;s collaboration tools are great when you&#8217;re only trying to collaborate with a handful of people, all of whom are working towards a common, mutually-understood goal.
</p>
<p>
But when it comes to open-source work, I use GitHub primarily as a hosting platform.<a class="footref" name="fnr.1" href="#fn.1">[1]</a> I put code on GitHub because I want people to be able to find it, and use it if it helps them. I want them to fork it, fix it, and improve it. But I don&#8217;t want to be bothered with it. If you added something new to my code, great! It&#8217;s open-source &ndash; have at it!
</p>
<p>
I&#8217;m puzzled by people who write to me saying, &#8220;If I were to write a patch for your library <i>X</i> to make it do <i>Y</i>, would you accept it?&#8221; First of all, you don&#8217;t need my or anybody else&#8217;s permission to modify my code. That&#8217;s the whole point of open-source! Secondly, how can I decide whether or not I&#8217;ll accept a patch I haven&#8217;t seen yet? Finally, if you do decide to send me a pull request, please don&#8217;t be offended if I don&#8217;t accept it, or if I ignore it for six months and then take the idea and rewrite it myself.
</p>
<p>
Why didn&#8217;t I accept your pull request? Not because I want to hog all the glory for myself. Not because I want to keep you out of my exclusive open-source masters&#8217; club. Not even because I can find any technical fault with your implementation. I&#8217;ve just got other things to do, other itches to scratch.
</p>
<p>
If everyone thought that way, would open-source still work? Probably. Maybe not as well.
</p>
<p>
To be sure, there&#8217;s a big difference between one-off utilities written in a weekend and major projects sustained for years by well-funded organizations. Managing a world-wide collaborative open-source project is a full-time job. The benevolent-dictator-for-life needs an equally-benevolent corporate-sponsor-for-life.<a class="footref" name="fnr.2" href="#fn.2">[2]</a> You can&#8217;t expect the same kind of support from individuals working in their spare time, for free.
</p>
<p>
I sometimes dream of an open-source collaboration model that is truly <i>pull</i>-based instead of GitHub&#8217;s <i>they-should-have-called-it-push request</i>. I don&#8217;t want to be forced to look at anything on any particular schedule. Don&#8217;t give me &#8220;notifications&#8221; or send me email. Instead, and only when I ask for it, allow me to browse the network of forks spawned by my code. Let me see who copied it, how they used it, and how they modified it. Be explicit about who owns the modifications and under what terms I can copy them back into my own project. And not just direct forks &mdash; show me all the places where my code was copied-and-pasted too.
</p>
<p>
Imagine if you could free open-source developers from all the time spent on mailing lists, IRC, bug trackers, wikis, pull requests, comment threads, and patches and channel all that energy into <i>solving problems</i>. Who knows? We might even solve the hard problems, like <a href="https://twitter.com/stuartsierra/status/159741771075694594">dependency management</a>.
</p>
<p><strong>Update Jan 17, 8:52am EST:</strong> I should mention that I have nothing but admiration and respect for people who are good at the organizational/community aspects of open-source software. I&#8217;m just not one of them.</p>
<div id="footnotes">
<h2 class="footnotes">Footnotes: </h2>
<div id="text-footnotes">
<p class="footnote"><a class="footnum" name="fn.1" href="#fnr.1">[1]</a> I&#8217;m not the only one. Linus Torvalds famously pointed out <a href="https://github.com/torvalds/linux/pull/17">flaws in the GitHub pull-request model</a>, in particular its poor support for more rigorous submission/signoff processes.
</p>
<p class="footnote"><a class="footnum" name="fn.2" href="#fnr.2">[2]</a> Even with a cushy corporate sponsor, accepting patches is a far more work than the authors of those patches typically realize. See <a href="https://plus.google.com/113026104107031516488/posts/ZRdtjTL1MpM">The story with #guava and your patches</a>.</p>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/MOEkL6cTfv4" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2013/01/16/the-reluctant-dictator/feed</wfw:commentRss>
		<slash:comments>11</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2013/01/16/the-reluctant-dictator</feedburner:origLink></item>
		<item>
		<title>Playing the Obstacle</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/82hH0fCl7v8/playing-the-obstacle</link>
		<comments>http://stuartsierra.com/2013/01/12/playing-the-obstacle#comments</comments>
		<pubDate>Sat, 12 Jan 2013 14:35:40 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=674</guid>
		<description><![CDATA[When I was in acting school (yes, I was in acting school, see my bio) one of my teachers had an expression: playing the obstacle. When studying for a role, one of an actor&#8217;s most important jobs is to determine the character&#8217;s overall objective: What&#8217;s my motivation? The plot of any play or movie typically [...]]]></description>
				<content:encoded><![CDATA[<p>When I was in acting school (yes, I was in acting school, see my bio) one of my teachers had an expression: <i>playing the obstacle</i>. When studying for a role, one of an actor&#8217;s most important jobs is to determine the character&#8217;s overall objective: <i>What&#8217;s my motivation?</i> The plot of any play or movie typically centers around how the character overcomes obstacles to achieve that objective.
</p>
<p>
What my teacher had noticed was a tendancy of young actors to focus too much on the obstacles themselves, attempting to build characters out of what they <i>can&#8217;t</i> do rather than what they <i>want</i> to do.
</p>
<p>
I think there&#8217;s a similar tendency in programmers. We start out with a clear objective, but when we encounter an obstacle to that objective we obsess over it. How many times has a programmer said, &#8220;I wanted to do <i>X</i>, but I couldn&#8217;t because <i>Y</i> got in the way,&#8221; followed by a 10-minute rant about how much language / framework / library / tool <i>Y</i> sucks? That&#8217;s playing the obstacle.
</p>
<p>
If you&#8217;re lucky enough to make software that real people (not programmers) actually use, then <i>Y</i> is irrelevant. No one cares how many ugly hacks you had to put in to make <i>Y</i> do something it wasn&#8217;t quite designed to do. All that matters is <i>X</i>.</p>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/82hH0fCl7v8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2013/01/12/playing-the-obstacle/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2013/01/12/playing-the-obstacle</feedburner:origLink></item>
		<item>
		<title>Clojure 2012 Year in Review</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/8J0_nlkelrA/clojure-2012-year-in-review</link>
		<comments>http://stuartsierra.com/2013/01/01/clojure-2012-year-in-review#comments</comments>
		<pubDate>Tue, 01 Jan 2013 22:22:55 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=667</guid>
		<description><![CDATA[I signed off my Clojure 2011 Year in Review with the words You ain&#8217;t seen nothing yet. Coming back for 2012, all I can think of is Wow, what a year! I&#8217;m happy to say that Clojure in 2012 exceeded even my wildest dreams. 2012 was the year when Clojure grew up. It lost the [...]]]></description>
				<content:encoded><![CDATA[<p>I signed off my <a href="http://stuartsierra.com/2012/01/03/clojure-2011-year-in-review">Clojure 2011 Year in Review</a> with the words <i>You ain&#8217;t seen nothing yet.</i> Coming back for 2012, all I can think of is <i>Wow, what a year!</i> I&#8217;m happy to say that Clojure in 2012 exceeded even my wildest dreams.
</p>
<p>
2012 was the year when Clojure grew up. It lost the squeaky voice of adolescence and gained the confident baritone of a professional language. The industry as a whole took notice, and people started making serious commitments to Clojure in both time and money.
</p>
<p>
There was so much Clojure news in 2012 that I can&#8217;t even begin to cover it all. I&#8217;m sure I&#8217;ve missed scores of important and exciting projects. But here are the ones that came to mind:
</p>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1">Growth &amp; Industry Mindshare</h2>
<div class="outline-text-2" id="text-1">
<ul>
<li>
<p>The <a href="https://groups.google.com/forum/#!forum/clojure">Clojure mailing list</a> has over <b>seven thousand</b> members.</p>
</li>
<li>
<p>Chas Emerick&#8217;s <a href="http://cemerick.com/2012/08/06/results-of-the-2012-state-of-clojure-survey/">State of Clojure Survey</a> got twice as many responses as in 2011.</p>
</li>
<li>
<p>Two new mailing lists spun up, <a href="https://groups.google.com/forum/#!aboutgroup/clojure-tools">clojure-tools</a> for &#8220;Clojure toolsmiths&#8221; and <a href="https://groups.google.com/forum/#!forum/clojure-sec">clojure-sec</a> for &#8220;security issues affecting those building applications with Clojure.&#8221;</p>
</li>
<li>
<p>Clojure moved into the &#8220;Adopt&#8221; section of <a href="http://www.thoughtworks.com/articles/technology-radar-october-2012">ThoughtWorks&#8217; Technology Radar</a> in October.</p>
</li>
<li>
<p>Conferences! I hereby dub 2012 the &#8220;year of the Clojure conference.&#8221; The first ever <a href="http://clojurewest.org/news/2012/5/11/clojurewest-video-schedule.html">Clojure/West</a> took place in San Jose in March, and <a href="http://clojure-conj.org/">Clojure/conj</a> returned to Raleigh in November. London got into the Clojure conference action with <a href="http://euroclojure.com/2012/">EuroClojure</a> in May and <a href="http://skillsmatter.com/event/home/clojure-exchange-2012">Clojure eXchange</a> in December.</p>
</li>
<li>
<p>O&#8217;Reilly got into the Clojure book game with two releases: the massive <a href="http://www.clojurebook.com/">Clojure Programming</a> by Chas Emerick, Christophe Grand, and Brian Carper; and the pocket-sized <a href="http://thinkrelevance.com/blog/2012/11/29/clojurescript-up-and-running">ClojureScript: Up and Running</a> by me and Luke VanderHart (see link for a discount code valid until Feb. 1, 2013).
</p>
</li>
</ul>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2">The Language</h2>
<div class="outline-text-2" id="text-2">
<ul>
<li>
<p>Clojure contributors closed 113 <a href="http://dev.clojure.org/jira">JIRA</a> tickets on the core language (not counting duplicates).</p>
</li>
<li>
<p><a href="https://github.com/clojure/clojure/blob/clojure-1.4.0/changes.md">Clojure 1.4</a> introduced <a href="https://github.com/clojure/clojure/blob/clojure-1.4.0/changes.md#21-reader-literals">tagged literals</a>, and the <a href="https://github.com/edn-format/edn">Extensible Data Notation</a> (edn) began an independent existence, including <a href="https://github.com/edn-format/edn/wiki/Implementations">implementations</a> in <a href="https://github.com/relevance/edn-ruby">Ruby</a> and <a href="https://github.com/shaunxcode/jsedn">JavaScript</a>.</p>
</li>
<li>
<p><a href="https://github.com/clojure/clojure/blob/clojure-1.5.0-RC1/changes.md">Clojure 1.5</a> entered &#8220;release candidate&#8221; status, bringing the new <a href="http://clojure.com/blog/2012/05/08/reducers-a-library-and-model-for-collection-processing.html">reducers</a> framework and <a href="https://github.com/clojure/clojure/blob/clojure-1.5.0-RC1/changes.md#24-new-threading-macros">new threading macros</a>.
</p>
</li>
</ul>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3">Software &amp; Tools</h2>
<div class="outline-text-2" id="text-3">
<ul>
<li>
<p>The big news, of course, was the release of <a href="http://www.datomic.com/">Datomic</a>, a radical new database from Rich Hickey and Relevance, in March. <a href="http://blog.datomic.com/2012/10/codeq.html">Codeq</a>, a new way to look at source code repositories, followed in October.</p>
</li>
<li>
<p><a href="http://www.lighttable.com/">Light Table</a>, a new IDE oriented towards Clojure, rocketed to over $300,000 in pledges <a href="http://www.kickstarter.com/projects/ibdknox/light-table">on Kickstarter</a> and entered the <a href="http://www.chris-granger.com/2012/05/17/light-table-is-in-yc/">Summer 2012 cohort of YCombinator</a>.</p>
</li>
<li>
<p>Speaking of tooling, what a bounty! <a href="http://leiningen.org/">Leiningen</a> got a major new version, as did <a href="https://github.com/clojure/tools.nrepl">nREPL</a> and <a href="https://github.com/clojure/tools.namespace">tools.namespace</a>. Emacs users finally escaped the Common Lisp <a href="http://common-lisp.net/project/slime/">SLIME</a> with <a href="https://github.com/kingtim/nrepl.el">nrepl.el</a>.</p>
</li>
<li>
<p>Red Hat&#8217;s <a href="http://immutant.org/">Immutant</a> became the first comprehensive application server for Clojure.</p>
</li>
<li>
<p><a href="http://clojure.com/blog/2012/01/11/announcing-clojurescript-one.html">ClojureScript One</a> demonstrated techniques for building applications in ClojureScript.
</p>
</li>
</ul>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4">Blogs and &#8216;Casts</h2>
<div class="outline-text-2" id="text-4">
<ul>
<li>
<p><a href="http://planet.clojure.in/">Planet Clojure</a> now aggregates over 400 blogs. </p>
</li>
<li>
<p>I laid out some history and motivation for the Clojure contribution process in  <a href="http://clojure.com/blog/2012/02/17/clojure-governance.html">Clojure/huh? &#8211; Clojure&#8217;s Governance and How It Got That Way</a>.</p>
</li>
<li>
<p>Chas Emerick&#8217;s <a href="http://mostlylazy.com/">Mostly Lazy</a> podcast featured <a href="http://mostlylazy.com/2012/09/21/episode-8-phil-hagelberg-empowering-userspace-in-heroku-leiningen-and-emacs/">Phil Hagelberg</a>, <a href="http://mostlylazy.com/2012/08/30/episode-7-anthony-grimes-tools-and-projects-minimum-viable-snippets/">Anthony Grimes</a>, and <a href="http://mostlylazy.com/2012/08/14/episode-6-chris-houser-clojure-surveys-getting-the-little-things-right-in-languages-yegge-rama-clojurescript-repls/">Chris Houser</a>.</p>
</li>
<li>
<p>Michael Fogus interviewed prominent Clojure community members in his &#8220;take 5&#8243; series: <a href="http://clojure.com/blog/2012/06/15/take5-anthony-grimes.html">Anthony Grimes</a>, <a href="http://clojure.com/blog/2012/06/01/take6-jim-crossley.html">Jim Crossley</a>, <a href="http://clojure.com/blog/2012/05/22/take5-colin-jones.html">Colin Jones</a>, <a href="http://clojure.com/blog/2012/04/19/take5-daniel-spiewak.html">Daniel Spiewak</a>, <a href="http://clojure.com/blog/2012/03/16/take5-baishampayan-ghose.html">Baishampayan Ghose</a>, <a href="http://clojure.com/blog/2012/02/28/take5-kevin-lynagh.html">Kevin Lynagh</a>, <a href="http://clojure.com/blog/2012/02/16/take5-william-byrd.html">William Byrd</a>, <a href="http://clojure.com/blog/2012/01/25/take4-arnoldo-molina.html">Arnoldo Jose Muller-Molina</a>, and <a href="http://clojure.com/blog/2012/01/04/take5-sam-aaron.html">Sam Aaron</a>.</p>
</li>
<li>
<p>Craig Andera launched the <a href="http://thinkrelevance.com/blog/tags/podcast">Relevance podcast</a>, where he interviewed many Clojurists such as <a href="http://thinkrelevance.com/blog/2012/12/12/timothy-baldridge-podcast-episode-022">Timothy Baldridge</a>, <a href="http://thinkrelevance.com/blog/2012/12/05/jason-rudolph-podcast-episode-021">Jason Rudolph</a>, <a href="http://thinkrelevance.com/blog/2012/10/12/rich-hickey-podcast-episode-019">Rich Hickey</a> (<a href="http://thinkrelevance.com/blog/2012/07/31/rich-hickey-podcast-episode-014">twice</a>), <a href="http://thinkrelevance.com/blog/2012/10/10/stuart-sierra-podcast-episode-018">me!</a>, <a href="http://thinkrelevance.com/blog/2012/09/22/clojure-conference-organizers-podcast-episode-015">Clojure conference organizers</a>, <a href="http://thinkrelevance.com/blog/2012/08/07/michael-fogus-podcast-episode-015">Michael Fogus</a> (<a href="http://thinkrelevance.com/blog/2012/03/28/thinkrelevance-the-podcast-episode-008-michael-fogus">twice</a>), <a href="http://thinkrelevance.com/blog/2012/04/26/thinkrelevance-the-podcast-episode-010-stu-halloway">Stuart Halloway</a>, <a href="http://thinkrelevance.com/blog/2012/04/09/thinkrelevance-the-podcast-episode-009-alan-dipert">Alan Dipert</a>, <a href="http://thinkrelevance.com/blog/2012/01/25/thinkrelevance-the-podcast-episode-004-aaron-bedra-s-valedictory">Aaron Bedra</a>, <a href="http://thinkrelevance.com/blog/2012/01/12/podcast-episode-003">Brenton Ashworth</a>, and <a href="http://thinkrelevance.com/blog/2012/01/05/podcast-episode-002">David Liebke</a>.
</p>
</li>
</ul>
<p>
&nbsp;
</p>
<p>
I have no idea what 2013 is going to bring. But if I were to venture a guess, I&#8217;d say it&#8217;s going to be a fantastic time to be working in Clojure.</p>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/8J0_nlkelrA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2013/01/01/clojure-2012-year-in-review/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2013/01/01/clojure-2012-year-in-review</feedburner:origLink></item>
		<item>
		<title>When (Not) to Write a Macro</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/KS_RqqFEvLA/when-to-write-a-macro</link>
		<comments>http://stuartsierra.com/2012/09/12/when-to-write-a-macro#comments</comments>
		<pubDate>Wed, 12 Sep 2012 13:15:18 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=659</guid>
		<description><![CDATA[The Solution in Search of a Problem A few months ago I wrote an article called Syntactic Pipelines, about a style of programming (in Clojure) in which each function takes and returns a map with similar structure: (defn subprocess-one [data] (let [{:keys [alpha beta]} data] (-&#62; data (assoc :epsilon (compute-epsilon alpha)) (update-in [:gamma] merge (compute-gamma [...]]]></description>
				<content:encoded><![CDATA[<div id="outline-container-1" class="outline-2">
<h2 id="sec-1">The Solution in Search of a Problem</h2>
<div class="outline-text-2" id="text-1">
<p>
A few months ago I wrote an article called <a href="http://stuartsierra.com/2012/05/16/syntactic-pipelines">Syntactic Pipelines</a>, about a style of programming (in Clojure) in which each function takes and returns a map with similar structure:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defn</span> <span class="org-function-name">subprocess-one</span> [data]
  (<span class="org-builtin">let</span> [{<span class="org-constant">:keys</span> [alpha beta]} data]
    (<span class="org-builtin">-&gt;</span> data
        (<span class="org-variable-name">assoc</span> <span class="org-constant">:epsilon</span> (compute-epsilon alpha))
        (<span class="org-variable-name">update-in</span> [<span class="org-constant">:gamma</span>] merge (compute-gamma beta)))))

<span class="org-comment-delimiter">;; </span><span class="org-comment">...</span>

(<span class="org-keyword">defn</span> <span class="org-function-name">large-process</span> [input]
  (<span class="org-builtin">-&gt;</span> input
      subprocess-one
      subprocess-two
      subprocess-three))
</pre>
<p>
In that article, I defined a pair of macros that allow the preceding example to be written like this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defpipe</span> <span class="org-function-name">subprocess-one</span> [alpha beta]
  (return (<span class="org-constant">:set</span> <span class="org-constant">:epsilon</span> (compute-epsilon alpha))
          (<span class="org-constant">:update</span> <span class="org-constant">:gamma</span> merge (compute-gamma beta))))

(<span class="org-keyword">defpipeline</span> <span class="org-function-name">large-process</span>
  subprocess-one
  subprocess-two
  subprocess-three)
</pre>
<p>
I wanted to demonstrate the possibilities of using macros to build abstractions out of common syntactic patterns. My example, however, was poorly chosen.
</p>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2">The Problem with the Solution</h2>
<div class="outline-text-2" id="text-2">
<p>
Every choice we make while programming has an associated cost. In the case of macros, that cost is usually borne by the person reading or maintaining the code.
</p>
<p>
In the case of <code>defpipe</code>, the poor sap stuck maintaining my code (maybe my future self!) has to know that it defines a function that takes a single map argument, despite the fact that it <i>looks</i> like a function that takes multiple arguments. That&#8217;s readily apparent if you read the docstring, but the docstring still has to be read and understood before the code makes sense.
</p>
<p>
The <code>return</code> macro is even worse. First of all, the fact that <code>return</code> is only usable within <code>defpipe</code> hints at some hidden coupling between the two, which is exactly what it is. Secondly, the word <i>return</i> is commonly understood to mean an immediate exit from a function. Clojure does not support non-tail function returns, and my macro does not add them, so the name <code>return</code> is confusing.
</p>
<p>
Using <code>return</code> correctly requires that the user first understand the <code>defpipe</code> macro, then understand the &#8220;mini language&#8221; I have created in the body of <code>return</code>, and also know that <code>return</code> only works in tail position inside of <code>defpipe</code>.
</p>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3">Is it Worth It?</h2>
<div class="outline-text-2" id="text-3">
<p>
Confusion, lack of clarity, and time spent reading docs: Those are the costs. The benefits are comparatively meager. Using the macros, my example is shorter by a couple of lines, one <code>let</code>, and some destructuring.
</p>
<p>
In short, the costs outweigh the benefits. Code using the <code>defpipe</code> macro is actually <i>worse</i> than code without the macro because it requires more effort to read. That&#8217;s not to say that the pipeline pattern I&#8217;ve described isn&#8217;t useful: It is. But my macros haven&#8217;t improved on that pattern enough to be worth their cost.
</p>
<p>
That&#8217;s the crux of the argument about macros. Whenever you think about writing one, ask yourself, &#8220;Is it worth it?&#8221; Is the benefit provided by the macro &ndash; in brevity, clarity, or power &ndash; worth the cost, in time, for you or someone else to understand it later? If the answer is anything but a resounding &#8220;yes&#8221; then you probably shouldn&#8217;t be writing a macro.
</p>
<p>
Of course, the same question can (and should) be asked of any code we write. Macros are a special case because they are so powerful that the cost of maintaining them is higher than that of &#8220;normal&#8221; code. Functions and values have semantics that are specified by the language and universally understood; macros can define their own languages. Buyer beware.
</p>
<p>
I still got some value out of the original post as an intellectual exercise, but it&#8217;s not something I&#8217;m going to put to use in my production code.
</p>
</div>
</div>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/KS_RqqFEvLA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2012/09/12/when-to-write-a-macro/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2012/09/12/when-to-write-a-macro</feedburner:origLink></item>
		<item>
		<title>Why I’m Using ClojureScript</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/MlH55igaalw/why-im-using-clojurescript</link>
		<comments>http://stuartsierra.com/2012/06/16/why-im-using-clojurescript#comments</comments>
		<pubDate>Sat, 16 Jun 2012 22:36:15 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[ClojureScript]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=629</guid>
		<description><![CDATA[Elise Huard wrote about why she&#8217;s not using ClojureScript. To quote her essential point, &#8220;The browser doesn&#8217;t speak clojure, it speaks javascript.&#8221; This is true. But the CPU doesn&#8217;t speak Clojure either, or JavaScript. This argument against ClojureScript is similar to arguments made against any high-level language which compiles down to a lower-level representation. Once [...]]]></description>
				<content:encoded><![CDATA[<p>Elise Huard wrote about <a href="http://jabberwocky.eu/2012/06/16/why-im-not-using-clojurescript/">why she&#8217;s not using ClojureScript</a>. To quote her essential point, <em>&#8220;The browser doesn&#8217;t speak clojure, it speaks javascript.&#8221;</em>
</p>
<p>
This is true. But the CPU doesn&#8217;t speak Clojure either, or JavaScript. This argument against ClojureScript is similar to arguments made against any high-level language which compiles down to a lower-level representation. Once upon a time, I feel sure, the same argument was made against FORTRAN.
</p>
<p>
A new high-level language has to overcome a period of skepticism from those who are already comfortable programming in the lower-level representation. A young compiler struggles to produce code as efficient as that hand-optimized by an expert. But compilers tend to get better over time, and some smart folks are working hard on <a href="http://www.50ply.com/cljs-bench/">making ClojureScript fast</a>. ClojureScript applications can get the benefit of improvements in the compiler without changing their source code, just as Clojure applications benefit from years of JVM optimizations.
</p>
<p>
To address Huard&#8217;s other points in order:
</p>
<p>
<i>1. Compiled ClojureScript code is hard to read, therefore hard to debug.</i>
</p>
<p>
This has not been an issue for me. In development mode (no optimizations, with pretty-printing) ClojureScript compiles to JavaScript which is, in my opinion, fairly readable. Admittedly, I know Clojure much better than I know JavaScript. The greater challenge for me has been working with the highly-dynamic nature of JavaScript execution in the browser. For example, a function called with the wrong number of arguments will not trigger an immediate error. Perhaps ClojureScript can evolve to catch more of these errors at compile time.
</p>
<p>
<em>2. ClojureScript forces the inclusion of the <a href="https://developers.google.com/closure/library/">Google Closure Library</a>.</em>
</p>
<p>
This is mitigated by the <a href="https://developers.google.com/closure/compiler/">Google Closure Compiler</a>&#8216;s dead-code elimination and aggressive space optimizations. You only pay, in download size, for what you use. For example, <a href="http://code.jquery.com/jquery-1.7.2.min.js">jQuery 1.7.2</a> is 33K, minified and gzipped. <a href="http://samsaffron.com/archive/2012/02/17/stop-paying-your-jquery-tax">Caching doesn&#8217;t always save you</a>. &#8220;Hello World&#8221; in ClojureScript, optimized and gzipped, is 18K.
</p>
<p>
<i>3. Hand-tuning performance is harder in a higher-level language.</i>
</p>
<p>
This is true, as per my comments above about high-level languages. Again, this has not been an issue for me, but you can always &#8220;drop down&#8221; to JavaScript for specialized optimizations.
</p>
<p>
<i>4. Cross-browser compatibility is hard.</i>
</p>
<p>
This is, as Huard admits, unavoidable in any language. The Google Closure Libraries help with some of the basics, and ClojureScript libraries such as <a href="https://github.com/levand/domina">Domina</a> are evolving to deal with other browser-compatibility issues. You also have the entire world of JavaScript libraries to paper over browser incompatibilities.
</p>
<p style="text-align:center">* * *</p>
<p>
Overall, I think I would agree with Elise Huard when it comes to browser programming &#8220;in the small.&#8221; If you just want to add some dynamic behavior to an HTML form, then ClojureScript has little advantage over straight JavaScript, jQuery, and whatever other libraries you favor.
</p>
<p>
What ClojureScript allows you to do is tackle browser-based programming &#8220;in the large.&#8221; I&#8217;ve found it quite rewarding to develop entire applications in ClojureScript, something I would have been reluctant to attempt in JavaScript.
</p>
<p>
It&#8217;s partially a matter of taste and familiarity. Clojure programmers such as myself will likely prefer ClojureScript over JavaScript. Experienced JavaScript programmers will have less to gain &mdash; and more work to do, learning a new language &mdash; by adopting ClojureScript. JavaScript is indeed &#8220;good enough&#8221; for a lot of applications, which means ClojureScript has to work even harder to prove its worth. I still believe that ClojureScript has an edge over JavaScript in the long run, but that edge will be less immediately obvious than the advantage that, say, Clojure on the JVM has over Java.</p>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/MlH55igaalw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2012/06/16/why-im-using-clojurescript/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2012/06/16/why-im-using-clojurescript</feedburner:origLink></item>
		<item>
		<title>Syntactic Pipelines</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/IIbLA2VqX98/syntactic-pipelines</link>
		<comments>http://stuartsierra.com/2012/05/16/syntactic-pipelines#comments</comments>
		<pubDate>Wed, 16 May 2012 22:42:41 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Clojure]]></category>
		<category><![CDATA[macros]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=624</guid>
		<description><![CDATA[Lately I&#8217;ve been thinking about Clojure programs written in this &#8220;threaded&#8221; or &#8220;pipelined&#8221; style: (defn large-process [input] (-&#62; input subprocess-one subprocess-two subprocess-three)) If you saw my talk at Clojure/West (video forthcoming) this should look familiar. The value being &#8220;threaded&#8221; by the -&#62; macro from one subprocess- function to the next is usually a map, and [...]]]></description>
				<content:encoded><![CDATA[<style type="text/css">
  .org-constant {
     color: purple;
  }</p>
<p>  .org-string {
     color: green;
  }</p>
<p>  .org-comment {
     color: darkred;
  }</p>
<p>  .org-comment-delimiter {
     color: darkred;
  }</p>
<p>  .org-keyword, .org-builtin, .org-variable-name {
     color: blue;
  }
  </style>
<p>
Lately I&#8217;ve been thinking about Clojure programs written in this &#8220;threaded&#8221; or &#8220;pipelined&#8221; style:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defn</span> <span class="org-function-name">large-process</span> [input]
  (<span class="org-builtin">-&gt;</span> input
      subprocess-one
      subprocess-two
      subprocess-three))
</pre>
<p>
If you saw my talk at Clojure/West (<a href="http://clojurewest.org/news/2012/5/11/clojurewest-video-schedule.html">video forthcoming</a>) this should look familiar. The value being &#8220;threaded&#8221; by the <code>-&gt;</code> macro from one <i>subprocess-</i> function to the next is usually a map, and each subprocess can add, remove, or update keys in the map. A typical subprocess function might look something like this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defn</span> <span class="org-function-name">subprocess-two</span> [data]
  (<span class="org-builtin">let</span> [{<span class="org-constant">:keys</span> [alpha beta]} data]
    (<span class="org-builtin">-&gt;</span> data
        (<span class="org-variable-name">assoc</span> <span class="org-constant">:epsilon</span> (compute-epsilon alpha))
        (<span class="org-variable-name">update-in</span> [<span class="org-constant">:gamma</span>] merge (compute-gamma beta)))))
</pre>
<p>
Most subprocess functions, therefore, have a similar structure: they begin by destructuring the input map and end by performing updates to that same map.
</p>
<p>
This style of programming tends to produce slightly longer code than would be obtained by writing larger functions with <code>let</code> bindings for intermediate values, but it has some advantages. The structure is immediately apparent: someone reading the code can get a high-level overview of what the code does simply by looking at the outer-most function, which, due to the single-pass design of Clojure&#8217;s compiler, will always be at the bottom of a file. It&#8217;s also easy to insert new functions into the process: as long as they accept and return a map with the same structure, they will not interfere with the existing functions.
</p>
<p>
The only problem with this code from a readability standpoint is the visual clutter of repeatedly destructuring and updating the same map. (It&#8217;s possible to move the destructuring into the function argument vector, but it&#8217;s still messy.)
</p>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1">defpipe</h2>
<div class="outline-text-2" id="text-1">
<p>
What if we could clean up the syntax without changing the behavior? That&#8217;s exactly what macros are good for. Here&#8217;s a first attempt:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defmacro</span> <span class="org-function-name">defpipe</span> [name argv &amp; body]
  `(<span class="org-keyword">defn</span> <span class="org-function-name">~name</span> [arg#]
     (<span class="org-builtin">let</span> [{<span class="org-constant">:keys</span> ~argv} arg#]
       ~@body)))
</pre>
<pre class="src src-clojure">(<span class="org-variable-name">macroexpand-1</span> '(<span class="org-keyword">defpipe</span> <span class="org-function-name">foo</span> [a b c] ...))
<span class="org-comment-delimiter">;;</span><span class="org-comment">=&gt; (clojure.core/defn foo [arg_47_auto]</span>
<span class="org-comment-delimiter">;;     </span><span class="org-comment">(clojure.core/let [{:keys [a b c]} arg_47_auto] ...))</span>
</pre>
<p>
That doesn&#8217;t quite work: we&#8217;ve eliminated the <code>:keys</code> destructuring, but lost the original input map.
</p>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2">return</h2>
<div class="outline-text-2" id="text-2">
<p>
What if we make a second macro specifically for updating the input map?
</p>
<pre class="src src-clojure">(<span class="org-keyword">def</span> <span class="org-constant">^:private</span> <span class="org-function-name">pipe-arg</span> (<span class="org-variable-name">gensym</span> <span class="org-string">"pipeline-argument"</span>))

(<span class="org-keyword">defmacro</span> <span class="org-function-name">defpipe</span> [name argv &amp; body]
  `(<span class="org-keyword">defn</span> <span class="org-function-name">~name</span> [~pipe-arg]
     (<span class="org-builtin">let</span> [{<span class="org-constant">:keys</span> ~argv} ~pipe-arg]
       ~@body)))

(<span class="org-keyword">defn-</span> <span class="org-function-name">return-clause</span> [spec]
  (<span class="org-builtin">let</span> [[command sym &amp; body] spec]
    (<span class="org-builtin">case</span> command
      <span class="org-constant">:update</span> `(<span class="org-variable-name">update-in</span> [~(<span class="org-variable-name">keyword</span> (<span class="org-variable-name">name</span> sym))] ~@body)
      <span class="org-constant">:set</span>    `(<span class="org-variable-name">assoc</span> ~(<span class="org-variable-name">keyword</span> (<span class="org-variable-name">name</span> sym)) ~@body)
      <span class="org-constant">:remove</span> `(<span class="org-variable-name">dissoc</span> ~(<span class="org-variable-name">keyword</span> (<span class="org-variable-name">name</span> sym)) ~@body)
      body)))

(<span class="org-keyword">defmacro</span> <span class="org-function-name">return</span> [&amp; specs]
  `(<span class="org-builtin">-&gt;</span> ~pipe-arg
       ~@(<span class="org-variable-name">map</span> return-clause specs)))
</pre>
<p>
This requires some more explanation. The <code>return</code> macro works in tandem with <code>defpipe</code>, and provides a mini-language for threading the input map through a series of transformations. So it can be used like this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defpipe</span> <span class="org-function-name">foo</span> [a b]
  (return (<span class="org-constant">:update</span> a + 10)
          (<span class="org-constant">:remove</span> b)
          (<span class="org-constant">:set</span> c a)))

<span class="org-comment-delimiter">;; </span><span class="org-comment">which expands to:</span>
(<span class="org-keyword">defn</span> <span class="org-function-name">foo</span> [input]
  (<span class="org-builtin">let</span> [{<span class="org-constant">:keys</span> [a b]} input]
    (<span class="org-builtin">-&gt;</span> input
        (<span class="org-variable-name">update-in</span> [<span class="org-constant">:a</span>] + 10)
        (<span class="org-variable-name">dissoc</span> <span class="org-constant">:b</span>)
        (<span class="org-variable-name">assoc</span> <span class="org-constant">:c</span> a))))
</pre>
<p>
As a fallback, we can put any old expression inside the <code>return</code>, and it will be just as if we had used it in the <code>-&gt;</code> macro. The rest of the code inside <code>defpipe</code>, before <code>return</code>, is a normal function body. The <code>return</code> can appear anywhere inside <code>defpipe</code>, as long as it is in tail position.
</p>
<p>
The symbol used for the input argument has to be the same in both <code>defpipe</code> and <code>return</code>, so we define it once and use it again. This is safe because that symbol is not exposed anywhere else, and the <code>gensym</code> ensures that it is unique.
</p>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3">defpipeline</h2>
<div class="outline-text-2" id="text-3">
<p>
Now that we have the <code>defpipe</code> macro, it&#8217;s trivial to add another macro for defining the composition of functions created with <code>defpipe</code>:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defmacro</span> <span class="org-function-name">defpipeline</span> [name &amp; body]
  `(<span class="org-keyword">defn</span> <span class="org-function-name">~name</span> [arg#]
     (<span class="org-builtin">-&gt;</span> arg# ~@body)))
</pre>
<p>
This macro does so little that I debated whether or not to include it. The only thing it eliminates is the argument name. But I like the way it expresses intent: a pipeline is purely the composition of <code>defpipe</code> functions.
</p>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4">Further Possibilities</h2>
<div class="outline-text-2" id="text-4">
<p>
One flaw in the &#8220;pipeline&#8221; style is that it cannot express conditional logic in the middle of a pipeline. Some might say this is a feature: the whole point of the pipeline is that it defines a single thread of execution. But I&#8217;m toying with the idea of adding syntax for predicate dispatch within a pipeline, something like this:
</p>
<pre class="src src-clojure">(<span class="org-keyword">defpipeline</span> <span class="org-function-name">name</span>
  pipe1
  <span class="org-comment-delimiter">;; </span><span class="org-comment">Map signifies a conditional branch:</span>
  {predicate-a pipe-a
   predicate-b pipe-b
   <span class="org-constant">:else</span>       pipe-c}
  <span class="org-comment-delimiter">;; </span><span class="org-comment">Regular pipeline execution follows:</span>
  pipe2
  pipe3)
</pre>
</div>
</div>
<div id="outline-container-5" class="outline-2">
<h2 id="sec-5">The Whole Shebang</h2>
<div class="outline-text-2" id="text-5">
<p>
The complete implementation follows. I&#8217;ve added doc strings, metadata, and some helper functions to parse the arguments to <code>defpipe</code> and <code>defpipeline</code> in the same style as <code>defn</code>.
</p>
<pre class="src src-clojure">(<span class="org-keyword">def</span> <span class="org-constant">^:private</span> <span class="org-function-name">pipe-arg</span> (<span class="org-variable-name">gensym</span> <span class="org-string">"pipeline-argument"</span>))

(<span class="org-keyword">defn-</span> <span class="org-function-name">req</span>
  <span class="org-doc">"Required argument"</span>
  [pred spec message]
  (<span class="org-variable-name">assert</span> (pred (<span class="org-variable-name">first</span> spec))
          (<span class="org-variable-name">str</span> message <span class="org-string">" : "</span> (<span class="org-variable-name">pr-str</span> (<span class="org-variable-name">first</span> spec))))
  [(<span class="org-variable-name">first</span> spec) (<span class="org-variable-name">rest</span> spec)])

(<span class="org-keyword">defn-</span> <span class="org-function-name">opt</span>
  <span class="org-doc">"Optional argument"</span>
  [pred spec]
  (<span class="org-builtin">if</span> (pred (<span class="org-variable-name">first</span> spec))
    [(<span class="org-variable-name">list</span> (<span class="org-variable-name">first</span> spec)) (<span class="org-variable-name">rest</span> spec)]
    [nil spec]))

(<span class="org-keyword">defmacro</span> <span class="org-function-name">defpipeline</span> [name &amp; spec]
  (<span class="org-builtin">let</span> [[docstring spec] (opt string? spec)
        [attr-map spec] (opt map? spec)]
    `(<span class="org-keyword">defn</span> <span class="org-function-name">~name</span> 
       ~@docstring
       ~@attr-map
       [arg#]
       (<span class="org-builtin">-&gt;</span> arg# ~@spec))))

(<span class="org-keyword">defmacro</span> <span class="org-function-name">defpipe</span>
  <span class="org-doc">"Defines a function which takes one argument, a map. The params are</span>
<span class="org-doc">  symbols, which will be bound to values from the map as by :keys</span>
<span class="org-doc">  destructuring. In any tail position of the body, use the 'return'</span>
<span class="org-doc">  macro to update and return the input map."</span>
  [name &amp; spec]
  {<span class="org-constant">:arglists</span> '([name doc-string? attr-map? [params*] &amp; body])}
  (<span class="org-builtin">let</span> [[docstring spec] (opt string? spec)
        [attr-map spec] (opt map? spec)
        [argv spec] (req vector? spec <span class="org-string">"Should be a vector"</span>)]
    (<span class="org-variable-name">assert</span> (<span class="org-variable-name">every?</span> symbol? argv)
            (<span class="org-variable-name">str</span> <span class="org-string">"Should be a vector of symbols : "</span>
                 (<span class="org-variable-name">pr-str</span> argv)))
    `(<span class="org-keyword">defn</span> <span class="org-function-name">~name</span>
       ~@docstring
       ~@attr-map
       [~pipe-arg]
       (<span class="org-builtin">let</span> [{<span class="org-constant">:keys</span> ~argv} ~pipe-arg]
         ~@spec))))

(<span class="org-keyword">defn-</span> <span class="org-function-name">return-clause</span> [spec]
  (<span class="org-builtin">let</span> [[command sym &amp; body] spec]
    (<span class="org-builtin">case</span> command
      <span class="org-constant">:update</span> `(<span class="org-variable-name">update-in</span> [~(<span class="org-variable-name">keyword</span> (<span class="org-variable-name">name</span> sym))] ~@body)
      <span class="org-constant">:set</span>    `(<span class="org-variable-name">assoc</span> ~(<span class="org-variable-name">keyword</span> (<span class="org-variable-name">name</span> sym)) ~@body)
      <span class="org-constant">:remove</span> `(<span class="org-variable-name">dissoc</span> ~(<span class="org-variable-name">keyword</span> (<span class="org-variable-name">name</span> sym)) ~@body)
      body)))

(<span class="org-keyword">defmacro</span> <span class="org-function-name">return</span>
  <span class="org-doc">"Within the body of the defpipe macro, returns the input argument of</span>
<span class="org-doc">  the defpipe function. Must be in tail position. The input argument,</span>
<span class="org-doc">  a map, is threaded through exprs as by the -&gt; macro.</span>

<span class="org-doc">  Expressions within the 'return' macro may take one of the following</span>
<span class="org-doc">  forms:</span>

<span class="org-doc">      (:set key value)      ; like (assoc :key value)</span>
<span class="org-doc">      (:remove key)         ; like (dissoc :key)</span>
<span class="org-doc">      (:update key f args*) ; like (update-in [:key] f args*)</span>

<span class="org-doc">  Optionally, any other expression may be used: the input map will be</span>
<span class="org-doc">  inserted as its first argument."</span>
  [&amp; exprs]
  `(<span class="org-builtin">-&gt;</span> ~pipe-arg
       ~@(<span class="org-variable-name">map</span> return-clause exprs)))
</pre>
</div>
</div>
<div id="outline-container-6" class="outline-2">
<h2 id="sec-6">And a Made-Up Example</h2>
<div class="outline-text-2" id="text-6">
<pre class="src src-clojure">(<span class="org-keyword">defpipe</span> <span class="org-function-name">setup</span> []
  (return  <span class="org-comment-delimiter">; </span><span class="org-comment">imagine these come from a database</span>
   (<span class="org-constant">:set</span> alpha 4)
   (<span class="org-constant">:set</span> beta 3)))

(<span class="org-keyword">defpipe</span> <span class="org-function-name">compute-step1</span> [alpha beta]
  (return (<span class="org-variable-name">:set</span> delta (<span class="org-variable-name">+</span> alpha beta))))

(<span class="org-keyword">defpipe</span> <span class="org-function-name">compute-step2</span> [delta]
  (return
   (<span class="org-variable-name">assoc-in</span> [<span class="org-constant">:x</span> <span class="org-constant">:y</span>] 42)  <span class="org-comment-delimiter">; </span><span class="org-comment">ordinary function expression</span>
   (<span class="org-constant">:update</span> delta * 2)
   (<span class="org-constant">:set</span> gamma (<span class="org-variable-name">+</span> delta 100))))  <span class="org-comment-delimiter">; </span><span class="org-comment">uses old value of delta</span>

(<span class="org-keyword">defpipe</span> <span class="org-function-name">respond</span> [alpha beta gamma delta]
  (<span class="org-variable-name">println</span> <span class="org-string">" Alpha is"</span> alpha <span class="org-string">"\n"</span>
           <span class="org-string">"Beta is"</span> beta <span class="org-string">"\n"</span>
           <span class="org-string">"Delta is"</span> delta <span class="org-string">"\n"</span>
           <span class="org-string">"Gamma is"</span> gamma)
  (return)) <span class="org-comment-delimiter">; </span><span class="org-comment">not strictly necessary, but a good idea</span>

(<span class="org-keyword">defpipeline</span> <span class="org-function-name">compute</span>
  compute-step1
  compute-step2)

(<span class="org-keyword">defpipeline</span> <span class="org-function-name">process-request</span>
  setup
  compute
  respond)
</pre>
<pre class="src src-clojure">(process-request {})

<span class="org-comment-delimiter">;; </span><span class="org-comment">Alpha is 4 </span>
<span class="org-comment-delimiter">;; </span><span class="org-comment">Beta is 3 </span>
<span class="org-comment-delimiter">;; </span><span class="org-comment">Delta is 14 </span>
<span class="org-comment-delimiter">;; </span><span class="org-comment">Gamma is 107</span>

<span class="org-comment-delimiter">;;</span><span class="org-comment">=&gt; {:gamma 107, :delta 14, :beta 3, :alpha 4}</span>
</pre>
</div>
</div>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/IIbLA2VqX98" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2012/05/16/syntactic-pipelines/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2012/05/16/syntactic-pipelines</feedburner:origLink></item>
		<item>
		<title>Three Kinds of Error</title>
		<link>http://feedproxy.google.com/~r/StuartSierra/~3/t9bF3DF1opA/three-kinds-of-error</link>
		<comments>http://stuartsierra.com/2012/04/03/three-kinds-of-error#comments</comments>
		<pubDate>Tue, 03 Apr 2012 16:07:00 +0000</pubDate>
		<dc:creator>Stuart</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[exceptions]]></category>

		<guid isPermaLink="false">http://stuartsierra.com/?p=613</guid>
		<description><![CDATA[Warning! This post contains strong, New York City-inflected language. If you are discomfited or offended by such language, do not read further &#8230; further &#8230; further &#8230; further &#8230; This is about three categories of software error. I have given them catchy names for purposes of illustration. The three kinds of error are the Fuck-Up, [...]]]></description>
				<content:encoded><![CDATA[<p>
<b>Warning! This post contains strong, New York City-inflected language. If you are discomfited or offended by such language, do not read further &hellip;</b>
</p>
<p>
further &hellip;
</p>
<p>
further &hellip;
</p>
<p>
further &hellip;
</p>
<p>
This is about three categories of software error. I have given them catchy names for purposes of illustration. The three kinds of error are the <i>Fuck-Up</i>, the <i>Oh, Fuck</i> and the <i>What the Fuck?</i>.
</p>
<div id="outline-container-1" class="outline-2">
<h2 id="sec-1">One</h2>
<div class="outline-text-2" id="text-1">
<p>
The <i>Fuck-Up</i> is a simple programmer mistake. In prose writing, it would be called a typo. You misspelled the name of a function or variable. You forgot to include all the arguments to a function. You misplaced a comma, bracket, or semicolon.
</p>
<p>
<i>Fuck-Up</i> errors are usually caught early in the development process and very soon after they are written. You made a change, and suddenly your program doesn&#8217;t work. You look back at what you just wrote and the mistake jumps right out at you.
</p>
<p>
Statically-typed languages can often catch <i>Fuck-Ups</i> at compile time, but not always. The mistake may be syntactically valid but semantically incorrect, or it may be a literal value such as a string or number which is not checked by the compiler. I find that one of the more insidious <i>Fuck-Ups</i> occurs when I misspell the name of a field, property, or keyword. This is more common in dynamically-typed languages that use literal keywords for property accesses, but even strongly-typed Java APIs sometimes use strings for property names. Compile-time type checkers cannot save you from all your <i>Fuck-Ups</i>.
</p>
<p>
I&#8217;ve occasionally wished for a source code checker that would look at all syntactic tokens in my program and warn me whenever I use a token exactly once: that&#8217;s a good candidate for a typo. Editors can help: even without the kind of semantic auto-completion found in Java IDEs, I&#8217;ve found I can avoid some misspellings by using auto-completion based solely on other text in the project.
</p>
<p>
<i>Fuck-Ups</i> become harder to diagnose the longer they go unnoticed. They are particularly dangerous in edge-case code that rarely gets run. The application seems to work until it encounters that unusual path, at which point it fails mysteriously. The failure could be many layers removed from the source line containing the <i>Fuck-Up</i>. This is where rapid feedback cycles and test coverage are helpful.
</p>
</div>
</div>
<div id="outline-container-2" class="outline-2">
<h2 id="sec-2">Two</h2>
<div class="outline-text-2" id="text-2">
<p>
Said with a mixture of resignation and annoyance, <i>Oh, Fuck</i> names the category of error when a program makes a seemingly-reasonable assumption about the state of the world that turns out not to be true. A file doesn&#8217;t exist. There isn&#8217;t enough disk space. The network is unreachable. We have wandered off the happy path and stumbled into the wilderness of the unexpected.
</p>
<p>
<i>Oh, Fuck</i> errors are probably the most common kind to make it past tests, due to positive bias. They&#8217;re also the most commonly ignored during development, because they are essentially unrelated to the problem at hand. You don&#8217;t care <i>why</i> the file wasn&#8217;t there, and it&#8217;s not necessarily something you can do anything about. But your code still has to deal with the possibility.
</p>
<p>
I would venture that most errors which make it through static typing, testing, and QA to surface in front of production users are <i>Oh, Fuck</i> errors. It&#8217;s difficult to anticipate everything that could go wrong.
</p>
<p>
However, I believe that <i>Oh, Fuck</i> errors are often inappropriately categorized as exceptions, because they are not really &#8220;exceptional,&#8221; <i>i.e.</i> rare. Exceptions are a form of non-local control flow, the last relic of <code>GOTO</code>. Whenever a failed condition causes an <i>Oh, Fuck</i> error, it typically needs to be handled locally, near the code that attempted to act on the condition, not in some distant error handler. Java APIs frequently use exceptions to indicate that an operation failed, but really they&#8217;re working around Java&#8217;s lack of union types. The return type of an file-read operation, for example, is the union of its normal return value and <code>IOException</code>. You have to handle both cases, but there&#8217;s rarely a good reason for the <code>IOException</code> to jump all the way out of the current function stack.
</p>
<p>
Programming &#8220;defensively&#8221; is not a bad idea, but filling every function with try/catch clauses is tedious and clutters up the code with non-essential concerns. I would advocate, instead, trying to isolate problem-domain code behind a &#8220;defensive&#8221; barrier of condition checking. Enumerate all the assumptions your code depends on, then encapsulate it in code which checks those assumptions. Then the problem-domain code can remain concise and free of extraneous error-checking.
</p>
<p>
Java APIs also frequently use <code>null</code> return values to indicate failure. Every non-primitive Java type declaration is an implicit union with <code>null</code>, but it&#8217;s easy to forget this, leading to the dreaded and difficult-to-diagnose <code>NullPointerException</code>. The possibility of a <code>null</code> return value really should be part of the type declaration. For languages which do not support such declarations, rigorous documentation is the only recourse.
</p>
</div>
</div>
<div id="outline-container-3" class="outline-2">
<h2 id="sec-3">Three</h2>
<div class="outline-text-2" id="text-3">
<p>
Finally, we have the errors that really are exceptional circumstances. You ran out of memory, divided by zero, overflowed an integer. In rare cases, these errors are caused by intermittent hardware failures, making them virtually impossible to reproduce consistently. More commonly, they are caused by emergent properties of the code that you did not anticipate. <i>What the Fuck?</i> errors are almost always encountered in production, when the program is exposed to new circumstances, longer runtimes, or heavier loads than it was ever tested with.
</p>
<p>
By definition, <i>What the Fuck?</i> errors are those you did not expect. The best you can do is try to ensure that such errors are noticed quickly and are not allowed to compromise the correct behavior of the system. Depending on requirements, this may mean the system should immediately shut down on encountering such an error, or it may mean selectively aborting and restarting the affected sub-processes. In either case, non-local control flow is probably your best hope. <i>What the Fuck?</i> errors are a crisis in your code: forget whatever you were trying to do and concentrate on minimizing the damage. The <i>worst</i> response is to ignore the error and continue as if nothing had happened: the system is in a failed state, and nothing it produces can be trusted.
</p>
</div>
</div>
<div id="outline-container-4" class="outline-2">
<h2 id="sec-4">Conclusion</h2>
<div class="outline-text-2" id="text-4">
<p>
All errors, even <i>What the Fuck?</i> errors, are ultimately programmer errors. But programmers are human, and software is hard. These categories I&#8217;ve named are not the only kinds of errors software can have, nor are they mutually exclusive. What starts as a simple <i>Fuck-Up</i> could trigger an <i>Oh, Fuck</i> that blossoms into a full-blown <i>What the Fuck?</i>.
</p>
<p>
Be careful out there.
</p>
</div>
</div>
<img src="http://feeds.feedburner.com/~r/StuartSierra/~4/t9bF3DF1opA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stuartsierra.com/2012/04/03/three-kinds-of-error/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://stuartsierra.com/2012/04/03/three-kinds-of-error</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 1.113 seconds. --><!-- Cached page generated by WP-Super-Cache on 2013-05-22 03:28:28 --><!-- Compression = gzip -->
