<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.1.2" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>Exploration Through Example</title>
	<link>http://www.exampler.com/blog</link>
	<description>Example-driven development, Agile software development, testing, Ruby, and other things of interest to Brian Marick</description>
	<pubDate>Sat, 07 Jan 2012 17:25:41 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.1.2</generator>
	<language>en</language>
			<item>
		<title>Some thoughts on classes after 18 months of Clojure</title>
		<link>http://www.exampler.com/blog/2012/01/07/some-thoughts-on-classes-after-18-months-of-clojure/</link>
		<comments>http://www.exampler.com/blog/2012/01/07/some-thoughts-on-classes-after-18-months-of-clojure/#comments</comments>
		<pubDate>Sat, 07 Jan 2012 16:51:24 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[ruby]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2012/01/07/some-thoughts-on-classes-after-18-months-of-clojure/</guid>
		<description><![CDATA[I had some thoughts about classes that wouldn&#8217;t fit into a talk I&#8217;m building about functional programming in Ruby, so I recorded them as a video. 
Topics:



Using hashes instead of classes.




Classes as a documentation tool&#8212;specifically, as a way of making functions easy to find.




Preferring module inclusion to subclassing (which is akin to preferring adjectives to [...]]]></description>
			<content:encoded><![CDATA[<p>I had some thoughts about classes that wouldn&#8217;t fit into a talk I&#8217;m building about <a href="http://geekfest.gathers.us/events/geekfest-functional-programming-in-ruby">functional programming in Ruby</a>, so I recorded them as <a href="http://vimeo.com/34522837">a video</a>. </p>
<p>Topics:</p>
<ul>
<li>
<p>
Using hashes instead of classes.
</p>
</li>
<li>
<p>
Classes as a documentation tool&#8212;specifically, as a way of making functions easy to find.
</p>
</li>
<li>
<p>
Preferring module inclusion to subclassing (which is akin to preferring adjectives to nouns as a way of organizing the documentation of verbs). (Vaguely similar to <a href="http://t.co/7wqEQTEM">duck-typing in Haskell</a>.)
</p>
</li>
<li>
<p>
Object dot notation as a more readable way of writing function composition. (Similar to the motivation for the <code>-&gt;</code> macro in Clojure or <a href="http://hackage.haskell.org/trac/haskell-prime/wiki/TypeDirectedNameResolution">type-directed name resolution in Haskell</a>.)
</p>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2012/01/07/some-thoughts-on-classes-after-18-months-of-clojure/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Here are three Ruby functions&#8230;</title>
		<link>http://www.exampler.com/blog/2011/12/27/here-are-three-ruby-functions/</link>
		<comments>http://www.exampler.com/blog/2011/12/27/here-are-three-ruby-functions/#comments</comments>
		<pubDate>Wed, 28 Dec 2011 01:36:06 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[ruby]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/12/27/here-are-three-ruby-functions/</guid>
		<description><![CDATA[Here are three Ruby functions. Each solves this problem: &#8220;You are given a starting and ending date and an increment in days. Produce all incremental dates that don&#8217;t include the starting date but may include the ending date. More formally: produce a list of all the dates such that  for some n >= 1, [...]]]></description>
			<content:encoded><![CDATA[<p>Here are three Ruby functions. Each solves this problem: &#8220;You are given a starting and ending date and an increment in days. Produce all incremental dates that don&#8217;t include the starting date but may include the ending date. More formally: produce a list of all the dates such that <code> for some n >= 1, date = starting_date + (increment * n) &#038;&#038; date < = ending_date</code>. </p>
<p>Solution 1:</p>
<script src="https://gist.github.com/1525608.js?file=gistfile1.rb"></script>
<p>Solution 2: </p>
<script src="https://gist.github.com/1525613.js?file=gistfile1.txt"></script>
<p>Solution 3 depends on a </code><code>lazily</code> function that produces an unbounded list from a starting element and a next-element function. Here&#8217;s a use of <code>lazily</code>:</p>
<script src="https://gist.github.com/1525622.js?file=gistfile1.rb"></script>
<p>As a lazy sequence, <code>integers</code> both (1) doesn&#8217;t do the work of calculating the <code>i</code>th element unless a client of <code>integers</code> asks for it, and also (2) doesn&#8217;t waste effort calculationg any intermediate values more than once.</p>
<p>Solution 3:</p>
<script src="https://gist.github.com/1525682.js?file=gistfile1.rb"></script>
<p>The third solution seems &#8220;intuitively&#8221; better to me, but I&#8217;m having difficulty explaining why. </p>
<p>The first solution fails on three aesthetic grounds:</p>
<ul>
<li>
<p>
It lacks <b>decomposability</b>. There&#8217;s no piece that can be ripped out and used in isolation. (For example, the body of the loop both creates a new element and updates an intermediate value.)
</p>
</li>
<li>
<p>
It lacks <b>flow</b>. It&#8217;s pleasing when you can view a computation as flowing a data structure through a series of functions, each of which changes its &#8220;shape&#8221; to convert a lump of coal into a diamond.
</p>
</li>
<li>
<p>
It has <b>wasted motion</b>: it puts an element at the front of the array, then throws it away. (Note: you can eliminate that by having <code>current</code> start out as <code>exclusive+increment</code> but that code duplicates the later +=increment. Arguably, that duplicated increment-date action is wasted (programmer) motion, in the sense that the same action is done twice. (Or: <a href="http://www.artima.com/intv/dry.html">don&#8217;t repeat yourself</a> / <a href="http://xprogramming.com/classics/expemergentdesign/">Eliminate duplication</a>.))
</p>
</li>
</ul>
<p>The second solution has flow of values through functions, but it wastes a lot of motion. A bunch of dates are created, only to be thrown away in the next step of the computation. Also, in some way I cannot clearly express, it seems wrong to stick the <code>inclusive_end</code> between the <code>exclusive_start</code> and the <code>increment</code>, given that the latter two are what was originally presented to the user and the <code>inclusive_end</code> is a user choice. (Therefore shouldn&#8217;t the <code>exclusive_start</code> and <code>increment</code> be more visually bound together than this solution does?)</p>
<p>The third solution &#8230;</p>
<ul>
<li>
<p>
&#8230; is decomposable: the sequence of dates is distinct from the decision about which subset to use. (You could, for example, pass in the whole lazy sequence instead of a <code>exclusive_start/increment</code> pair, something that couldn&#8217;t be done with the other solutions.)
</p>
</li>
<li>
<p>
&#8230; eliminates wasted work, in that only the dates that are required are generated. (Well, it does store away a first date &#8212; <code>excluded_start</code> &#8212; that is then dropped. But it doesn&#8217;t create an excess new date.)
</p>
</li>
<li>
<p>
&#8230; has the same feel of a data structure flowing through functions that #2 has.
</p>
</li>
</ul>
<p>So: #3 seems best to me, but the advantages over the other two seem unconvincing (especially given that programmers of my generation are likely to see closure-evaluation-requiring-heap-allocation-because-of-who-knows-what-bound-variables as scarily expensive). </p>
<p>Have you better arguments? Can you refute my arguments?</p>
<p>I&#8217;m trying to show the virtues of a lazy functional style. Perhaps this is a bad example? [It&#8217;s a real one, though, where I really do prefer the third solution.]</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/12/27/here-are-three-ruby-functions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using functional style in a Ruby webapp</title>
		<link>http://www.exampler.com/blog/2011/10/31/using-functional-style-in-a-ruby-webapp/</link>
		<comments>http://www.exampler.com/blog/2011/10/31/using-functional-style-in-a-ruby-webapp/#comments</comments>
		<pubDate>Mon, 31 Oct 2011 06:54:45 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[ruby]]></category>

		<category><![CDATA[programming]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/10/31/using-functional-style-in-a-ruby-webapp/</guid>
		<description><![CDATA[Motivation
Consider a Ruby backend that communicates with its frontend via JSON. It sends (and perhaps receives) strings like this:

Let&#8217;s suppose it also communicates with a relational database. A simple translation of query results into Ruby looks like this:

(I&#8217;m using the Sequel gem to talk to Postgres.)
On the face of it, it seems odd for our [...]]]></description>
			<content:encoded><![CDATA[<p><b>Motivation</b></p>
<p>Consider a Ruby backend that communicates with its frontend via JSON. It sends (and perhaps receives) strings like this:</p>
<script src="https://gist.github.com/1327796.js?file=gistfile1.rb"></script>
<p>Let&#8217;s suppose it also communicates with a relational database. A simple translation of query results into Ruby looks like this:</p>
<script src="https://gist.github.com/1327804.js?file=gistfile1.rb"></script>
<p>(I&#8217;m using the <a href="http://sequel.rubyforge.org/">Sequel</a> gem to talk to Postgres.)</p>
<p>On the face of it, it seems odd for our code to receive dumb hashes and arrays, laboriously turn them into model objects with rich behavior, fling some messages at them to transform their state, and then convert the resulting object graph back into dumb hashes and arrays. There are strong historical reasons for that choice&#8212;see <a href="http://martinfowler.com/">Fowler</a>&#8217;s <i><a href="http://martinfowler.com/books.html#eaa">Patterns of Enterprise Application Architecture</a></i>&#8212;but I&#8217;m starting to wonder if it&#8217;s as clear a <i>default</i> choice as it used to be. Perhaps a functional approach could work well:</p>
<ul>
<li>
<p>
Functional programs focus on the flow of data through code, rather than on objects with changing state. The former seems more of a match for a typical webapp.
</p>
</li>
<li>
<p>
It&#8217;s common in functional languages to lean toward a few core datatypes&#8212;like hashes and arrays&#8212;that are operated on by a wealth of functions. We could skip the conversion step into objects. Rather than having to deal with the <a href="http://www.joelonsoftware.com/articles/LeakyAbstractions.html">leaky abstraction</a> of an object-relational mapping layer, we&#8217;d embrace the nature of our data.
</p>
</li>
</ul>
<p>Seems plausible, I&#8217;ve been thinking. However, I&#8217;ve never been wildly good at understanding the problems of an approach just <a href="http://incanter.org/images/misc/hammock-driven-dev.png">by thinking about it</a>. It&#8217;s more efficient for me to learn by doing. So I&#8217;ve decided to <a href="http://martinfowler.com/bliki/StranglerApplication.html">strangle</a> an application whose communication with its database is, um, labored.  </p>
<p>I&#8217;m going to concentrate on two things: </p>
<ul>
<li>
<p>
<i>Structuring the code</i>. More than a year of work on <a href="https://github.com/marick/Midje">Midje</a> has left me still unhappy about the organization of its code, despite my using <a href="http://www.raggedclown.com/">Kevin Lawrence</a>&#8217;s <a href="http://www.exampler.com/old-blog/2005/06/16/">guideline</a>: if you have trouble finding a piece of code, move it to where you first looked. I have some hope that Ruby&#8217;s structuring tools (classes, modules, <code>include</code>, etc.) will be useful.</p>
</li>
<li>
<p>
<i>Dependencies</i>. As you&#8217;ll see, I&#8217;ll be writing code with a lot of <a href="http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx">temporal coupling</a>. Is that and <a href="http://en.wikipedia.org/wiki/Coupling_(computer_programming)#Types_of_coupling">other kinds of coupling</a> dooming me to a <a href="http://en.wikipedia.org/wiki/Intertwingularity">deeply intertwingled</a> mess that I can&#8217;t change safely or quickly?
</p>
</li>
</ul>
<p>This blog post is about where I stand so far, after adding just one new feature.</p>
<p><b>A path through the app</b></p>
<p><a href="https://github.com/marick/critter4us">Critter4us</a> is an app that&#8217;s used to reserve teaching animals at the University of Illinois vet school. Reserving animals is like reserving meeting rooms, but with some different business rules. For example, Boombird the horse doesn&#8217;t care if students practice bandaging on him every day. However, it would be inhumane to practice giving him injections every day, so that can be done at most twice a week. </p>
<p>The story I&#8217;ve been working on is one that makes a copy of an existing reservation but with a new &#8220;timeslice&#8221; (something like &#8220;January 1st through 3d, in the mornings&#8221;). Ideally, the same animals will be assigned to the copy, but that&#8217;s not always possible. If someone else has already reserved the animal for an overlapping timeslice, a new animal has to be found. Or if a procedure (like giving injections) would be within an animal&#8217;s &#8220;blackout period&#8221;, a new animal has to be found for it. For historical reasons, the reservation is made without the unusable animals and the user is alerted to edit it to add new ones.</p>
<p>Here&#8217;s the heart of the code for the feature:</p>
<script src="https://gist.github.com/1326261.js?file=gistfile1.rb"></script>
<p>The rest of this post will explain how that works and how it&#8217;s in a functional style. When I mention classes, I&#8217;ll link to the source.</p>
<p><b>FullReservation</b></p>
<p>The object model for the old program starts with a <i>reservation</i>, which contains information like &#8220;Who made the reservation?&#8221; and &#8220;For when?&#8221;. It also contains zero or more <i>groups</i>, each of which contains zero or more <i>uses</i>. A use links an animal to a procedure to be performed on it. I defined the class structure first, then mapped it onto a database schema, deliberately deferring any worries about efficiency:</p>
<script src="https://gist.github.com/1326270.js?file=gistfile1.rb"></script>
<p>The object-to-relational mapping library (<a href="http://sequel.rubyforge.org/">Sequel</a>) let me work with the data in a way that hid (&#8221;unflattened&#8221;) the table structure:</p>
<script src="https://gist.github.com/1326274.js?file=gistfile1.rb"></script>
<p>The existence of three tables is made somewhat implicit.</p>
<p>I&#8217;m replacing that old <code><a href="https://github.com/marick/critter4us/blob/functional/strangled-src/model/reservation.rb">Reservation</a></code> object with a new <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code>. In <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code>, I chose instead to make them explicit:</p>
<script src="https://gist.github.com/1326276.js?file=gistfile1.rb"></script>
<p>That notation is awkward to type and it doesn&#8217;t lend itself to the <a href="http://pragdave.pragprog.com/pragdave/2005/11/symbolto_proc.html">Symbol#to_proc hack</a>, so I follow Javascript by allowing dot notation as a pun for key lookup:</p>
<script src="https://gist.github.com/1326277.js?file=gistfile1.rb"></script>
<p><b>Namespacing</b></p>
<p>I&#8217;m supposedly doing this in a functional style, and the very first thing I&#8217;ve done is make a class? What&#8217;s up with that?</p>
<p>I have two reasons. First, I think having the order of function application flow left to right fits the (Western-language-speaker) perception that time flows from left to right and from top to bottom. That makes this:</p>
<script src="https://gist.github.com/1328061.js?file=gistfile1.rb"></script>
<p>&#8230; easier to read than this:</p>
<script src="https://gist.github.com/1328068.js?file=gistfile1.rb"></script>
<p>The second reason is namespacing. You&#8217;ll shortly see that everything is built on top of an immutable, lazy <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> object. A <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> just collects those methods that wouldn&#8217;t make sense for anything but a <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> being treated as a reservation. It&#8217;s about avoiding name collisions more than about modeling the world.</p>
<p>Inheritance gives me nested namespaces, something I dearly wish I had in Clojure. For example, there are a variety of functions that apply to <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a>es</code> that represent database tables, but are irrelevant to other ones. That code is contained in <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code>&#8217;s superclass, <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/db_hash.rb">DBHash</a></code>.</p>
<p>Actually: not quite. The text of the code is found in three different modules that are <code>included</code> into <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/db_hash.rb">DBHash</a></code>. I expect to do a lot of mixing-and-matching to create namespaces for particular <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/db_hash.rb">DBHash</a></code> classes and even particular objects (via <code>extend</code>). </p>
<p><b>Extracting a FunctionalTimeslice from a FullReservation</b></p>
<p>In the <code>reservations</code> table, there are three columns devoted to &#8220;when is the reservation for?&#8221; They are <code>:first_date</code>, <code>:last_date</code>, and <code>:time_bits</code>. (The first two are Date objects; the last represents the set <code>{morning, afternoon, evening}</code>. In a proper object-oriented design, you&#8217;d expect a <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> to <a href="https://github.com/marick/critter4us/blob/functional/strangled-src/model/reservation.rb#L78">contain</a> a <code><a href="https://github.com/marick/critter4us/blob/functional/strangled-src/model/timeslice.rb">Timeslice</a></code> that in turn contains those three values and some timeslice-specific methods as well. I chose to handle such sub-objects differently. Instead of asking a reservation for its timeslice, you make a timeslice from a reservation using setlike operations.</p>
<p><code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> has an <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L70">only</a></code> method that produces a smaller <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> containing <i>only</i> the named key-value pairs. So this is a timeslice:</p>
<script src="https://gist.github.com/1328691.js?file=gistfile1.rb"></script>
<p>I give the timeslice access to a timeslice-specific namespace by wrapping it in a class: </p>
<script src="https://gist.github.com/1328692.js?file=gistfile1.rb"></script>
<p><b>Adding a new Timeslice to Full Reservation</b></p>
<p>It&#8217;s often said that code without mutable state is easier to reason about. I don&#8217;t personally find that as big a deal as other people do, but I&#8217;ve gotten used to immutability from my Clojure programming. So <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> disallows messages like this:</p>
<script src="https://gist.github.com/1328713.js?file=gistfile1.rb"></script>
<p>The equivalent of assigning a value to a key is done by merging it and creating a new <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a>. The equivalent of deleting a key is done by making a copy of </code><code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> without the given key. At the moment, this implementation is grossly space-inefficient. Eventually, I&#8217;ll port it over to <a href="http://www.harukizaemon.com/">Simon Harris</a>&#8217;s <a href="https://github.com/harukizaemon/hamster">Hamster</a>, which implements structure sharing and other optimization techniques. I&#8217;m even thinking I might port his code to C.</p>
<p>Here&#8217;s the way to change a reservation&#8217;s date:</p>
<script src="https://gist.github.com/1328728.js?file=gistfile1.rb"></script>
<p>A few notes:</p>
<ul>
<li>
<p>
<code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L35">change_within</a></code> is a way of &#8220;merging&#8221; into a nested hash. It&#8217;s the equivalent of this:</p>
<script src="https://gist.github.com/1328732.js?file=gistfile1.rb"></script>
</p>
</li>
<li>
<p>
Remember that, here, <code>timeslice</code> is a three-key hash, not an object.
</p>
</li>
<li>
<p>
I&#8217;m also removing the <code>id</code> to remind myself that the reservation produced here no longer corresponds to one in the database.
</p>
</li>
</ul>
<p><b>Working with disallowed animals</b></p>
<p>Any time a reservation is made, it disallows some animals (because they&#8217;re now in use) and may disallow some animal/procedure pairs (because of rules about how frequently a procedure can be performed). That information is calculated once and stored in Postgres tables named <code>excluded_because_in_use</code> and <code>excluded_because_of_blackout_period</code>.</p>
<p>The code to look up which animals are in use during a timeslice is factored into three pieces. Inlined, it would look like this:</p>
<script src="https://gist.github.com/1328803.js?file=gistfile1.rb"></script>
<p>(<code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L87">Fall</a></code> turns an array of hashes into an array of <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHashes</a></code>.) </p>
<p>Because that code doesn&#8217;t refer to a reservation at all, it seems reasonable to put it in the <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/functional_timeslice.rb">FunctionalTimeslice</a></code> namespace.</p>
<p>The <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> can use the list of animal ids to prune out its uses:</p>
<script src="https://gist.github.com/1328833.js?file=gistfile1.rb"></script>
<p>That&#8217;s all easy enough, but the contract with the user is that she&#8217;ll see a list of names of animals that couldn&#8217;t be included in the reservation. Getting that list is easy enough, given that we have ready access to the rejected uses. Here&#8217;s the code, with changes to the previous version highlighted:</p>
<script src="https://gist.github.com/1328848.js?file=gistfile1.rb"></script>
<p>That&#8217;s fine, but what do we do with the value named by <code>___animals_already_in_use___</code>? I&#8217;d hate to return it along with the new version of the reservation because its caller would have to look like this:</p>
<script src="https://gist.github.com/1328875.js?file=gistfile1.rb"></script>
<p>I&#8217;d rather avoid names for intermediate steps in the creation of the reservation copy. I want the various versions to flow anonymously through a chain of functions so that I need only name the original and the final copy. (<code>original</code> and <code>copy</code> would be better names than <code>reservation</code> and <code>new_reservation</code>, it occurs to me, but I&#8217;m not going to go back now and change all these gists.)</p>
<p>That suggests slamming the animal list into the next version of the reservation, like this:</p>
<script src="https://gist.github.com/1328919.js?file=gistfile1.rb"></script>
<p>That kind of creeps me out, and it exacerbates temporal coupling. Nevertheless, it lets the caller <i>look nice</i>, which might mean something. (If mathematicians can go on about elegance, why can&#8217;t I?) I hope my tests will loudly tell me when coupling causes a change to function X to break function Y.  </p>
<p><b>as_saved</b></p>
<p>The last step of creating the copied reservation is oddly named:</p>
<script src="https://gist.github.com/1328974.js?file=gistfile1.rb"></script>
<p><i>as_saved?</i> This is a stylistic affectation that I&#8217;m not sure is a good idea. What I&#8217;m trying to imply is that the <i>main</i> thing this function does is create a new <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> with a bit of extra data, namely <code>data.id</code>, merged in. (The id needs to be sent off to the front end.) The fact that the id is created by changing persistent state somewhere is just an implementation detail. It could just as well be that every possible reservation always already exists somewhere as a big immutable pool, so <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb#L67">as_saved</a></code> just does a lookup to find the matching id.</p>
<p>(Which, it again occurs to me too late, perhaps makes as_saved a name that, strictly, reveals too much about the implementation.)</p>
<p>(Interestingly, I understand that the human immune system works roughly like the silly implementation above: you&#8217;re born with some <a href="http://en.wikipedia.org/wiki/Antibody#Immunoglobulin_diversity">10 billion different antibodies</a> and the response to infection (mostly) involves finding the useful ones, not creating new ones that match the foreign agent.)</p>
<p><b><code>only</code> and the nature of classes</b></p>
<p>After the as-it-appears-in-the-database <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> is created, the pieces that the frontend code care about are extracted and returned to the controller code, which turns them into JSON:</p>
<script src="https://gist.github.com/1328962.js?file=gistfile1.rb"></script>
<p>But something creepy is going on here. What&#8217;s the type of the result of <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L70">only</a></code>?</p>
<script src="https://gist.github.com/1329092.js?file=gistfile1.rb"></script>
<p>How can anyone possibly believe that the two-element hash, containing nothing about the reservation in question (but only about the difference between it and its original) is a <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code>?  </p>
<p>For a time, I considered changing <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L70">only</a></code> to produce a <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code>, rather than (as it does) an object of the same class as the receiver of the method. Then I smacked myself and reminded myself that I&#8217;m using classes to identify namespaces, not <a href="http://plato.stanford.edu/entries/natural-kinds/">natural kinds</a>. Saying that the result of <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L70">only</a></code> &#8220;is a&#8221; <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> would be absurd. But it&#8217;s less absurd to say that (1) we started with a hash, (2) the functions in the namespace <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> applied to it, (3) we derived a second hash from the first, so (4) it&#8217;s probably a good guess that the same namespace will be also useful for the second hash.</p>
<p>That is, it&#8217;s all about conservation of work. If I stripped every result of <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb#L70">only</a></code> down to a bare <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code>, I&#8217;d sometimes have to add a namespace back. By not stripping it, sure, I may get irrelevant functions in the easily-accessible namespace, but I can just ignore them.</p>
<p><b>Laziness</b></p>
<p>I chose the name <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> not just because <code>Reservation</code> was already taken. It&#8217;s because a <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> contains all the values that can possibly be relevant to a reservation. But some HTTP requests only care about the reservation&#8217;s id. Some only care about some of the data (like the timeslice). Only a few care about the uses and the groups.</p>
<p>Laziness of the sort implemented in Clojure and Haskell seems a nice match for this. When a <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> key is assigned a block/lambda, it doesn&#8217;t treat that as a value. Rather, the <code><a href="https://github.com/marick/critter4us/blob/functional/src/functional/functional_hash.rb">FunctionalHash</a></code> runs that block to calculate the value when the key is dereferenced. After that, the value is cached (and is immutable, just like any other value).</p>
<p>So consider these two steps from our controller:</p>
<script src="https://gist.github.com/1329344.js?file=gistfile1.rb"></script>
<p>We create a new reservation by saving a modified reservation to disk. That gives us a new row in the <code>reservations</code> table, some new rows in the <code>groups</code> table, and some new rows in the <code>uses</code> table. But nothing of the <code>groups</code> or <code>uses</code> is used from then on, so it would be a waste to populate the <code>new_reservation</code> with them. How is that avoided? By creating a <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> like this:</p>
<script src="https://gist.github.com/1329455.js?file=gistfile1.rb"></script>
<p>The uses and groups and even the row in the <code>:reservations</code> table are only loaded when they&#8217;re needed, so it costs little to use a <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> for everything. With this structure, I&#8217;m trying to gain more control than an object-to-relational mapping library gives me, while still freeing myself from the micromanagement of loading. Time will tell if that works.</p>
<p>(Note: I stash the original <code>id</code> that led to the <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> in <code>:starting_id</code>. Part of the motivation was to allow a completely fresh <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code> to return its id without going to the database at all, and another part was to retain the original id even after later changes made it no longer an index into the reservation contents. This dual purpose makes the code confused, I think.)</p>
<p>(Note: Postgres supports the SQL <a href="http://www.postgresql.org/docs/8.3/interactive/sql-insert.html">RETURNING</a> extension. So it&#8217;d be relatively easy to fully populate a saved <code><a href="https://github.com/marick/critter4us/blob/functional/src/db/full_reservation.rb">FullReservation</a></code>. I&#8217;ve used RETURNING several times, but always later discarded it for one reason or another.)</p>
<p><b>The grand conclusion</b></p>
<p>I&#8217;ve always hated end-of-talk or end-of-post summations. So I don&#8217;t really have one here, except that this approach feels promising, I want to continue trying it, I&#8217;d like to hear your comments (sorry about the antiquated blog software), and I&#8217;d especially like to hear what happens if you try out this approach.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/10/31/using-functional-style-in-a-ruby-webapp/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Top-down design in &#8220;functional classic&#8221; programming</title>
		<link>http://www.exampler.com/blog/2011/10/07/top-down-design-in-functional-classic-programming-2/</link>
		<comments>http://www.exampler.com/blog/2011/10/07/top-down-design-in-functional-classic-programming-2/#comments</comments>
		<pubDate>Fri, 07 Oct 2011 12:47:33 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[TDD]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/10/07/top-down-design-in-functional-classic-programming-2/</guid>
		<description><![CDATA[While waiting for my product owner to get back to me, I was going through open browser tabs. I read this from Swizec Teller:

The problem is one of turning a list of values, say, [A, B, C, D] into a list of pairs with itself, like so [[A,B], [A,C], [A,D], [B, C], [B,D], [C,D]].

He had [...]]]></description>
			<content:encoded><![CDATA[<p>While waiting for my product owner to get back to me, I was going through open browser tabs. I read <a href="http://swizec.com/blog/functional-isnt-always-better/swizec/2591">this</a> from Swizec Teller:</p>
<blockquote><p>
The problem is one of turning a list of values, say, [A, B, C, D] into a list of pairs with itself, like so [[A,B], [A,C], [A,D], [B, C], [B,D], [C,D]].
</p></blockquote>
<p>He had problems coming up with a good solution. &#8220;I can do that!&#8221; I said, launched a Clojure REPL, and started typing the whole function out. I quickly got bogged down. </p>
<p>This, I think, is a problem with a common functional approach. Even with this kind of problem&#8212;the sort of list manipulation that functional programming lives for&#8212;there&#8217;s a temptation to build a single function bottom up. &#8220;I need to create the tails of the sequence,&#8221; I thought, &#8220;because I know roughly how I&#8217;ll use them.&#8221;</p>
<p><i>For me</i> (and let&#8217;s not get into <a href="http://www.exampler.com/blog/2011/09/29/my-clojure-problem/">all that again</a>), it usually works better to go top down, mainly because it lets me think of discrete, meaningful functions, give them names, and write facts about how they relate to one another. So that&#8217;s what I did.</p>
<p>First, what am I trying to do? Not create all the pairs, but only ones in which an element is combined with another element further down the list. Like this:</p>
<script src="https://gist.github.com/1270705.js?file=gistfile1.clj"></script>
<p>As I often do when doing list-manipulation problems, I lay things out to visually emphasize the &#8220;shape&#8221; of the solution. That helps me see more clearly what has to be done to create that solution. There&#8217;s one set of pairs, each <i>headed</i> by the first element of the list, then another set, each headed by the second element. That is, I can say the above fact is true <i>provided</i> two other facts are true:</p>
<script src="https://gist.github.com/1270709.js?file=gistfile1.clj"></script>
<p>It&#8217;s easy to see how I get the heads&#8212;just map down the list (maybe I have to worry about the last element, maybe not&#8212;I&#8217;ll worry about it if it comes up). What are those heads combined with? Just the successive <i>tails</i> of the original list: <code>[2 3], [3]</code>. I&#8217;ll assume there&#8217;s a function that does that for me. That gives me this entire fact-about-the-world-of-this-program:</p>
<script src="https://gist.github.com/1270720.js?file=gistfile1.clj"></script>
<p>Given all that, <code>downward-pairs</code> is easy enough to write:</p>
<script src="https://gist.github.com/1270722.js?file=gistfile1.clj"></script>
<p>It&#8217;s important to me that I have reached a stable point here. When building up a complicated function from snippets in a REPL, I more often create the wrong snippets than when I <i>define</i> what those snippets need to do via a function that uses them. (I&#8217;m not saying that I never backtrack: I might find a subfunction too hard to write, or I may have <a href="http://ask.metafilter.com/58170/What-is-the-origin-of-the-phrase-Carving-nature-by-its-joints">carved up the world</a> in a way that leads to gross inefficiency, etc. I&#8217;m saying that I seem to end up with correct answers faster this way.)</p>
<p>Now I just have to solve two simpler problems. Tails I&#8217;ve done before, and here&#8217;s a solution I like: </p>
<script src="https://gist.github.com/1270736.js?file=gistfile1.clj"></script>
<p>For those who don&#8217;t know Clojure well, this produces this sequence of calls to <code>drop</code>:</p>
<script src="https://gist.github.com/1270744.js?file=gistfile1.clj"></script>
<p>This does roughly the same work as an iteration would do because of how laziness is implemented.</p>
<p>That leaves me <code>headed-pairs</code>, which is a pretty straightforward map:</p>
<script src="https://gist.github.com/1270748.js?file=gistfile1.clj"></script>
<p>This seems like a reasonable solution, doesn&#8217;t strike me as being terribly inefficient (given laziness), has a readability that I like, doubtless took me less time than developing it bottom-up would have, and comes with tests (including an end-to-end test that I won&#8217;t bother showing).</p>
<p>The whole solution is <a href="https://gist.github.com/1270755">here</a>.</p>
<p>UPDATE: Yes, I could have used <code>do</code> or even gotten explicit with the <code>sequence-m</code> monad, but that wouldn&#8217;t have addressed the original poster&#8217;s point, which I took to be how to think about functional problems.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/10/07/top-down-design-in-functional-classic-programming-2/feed/</wfw:commentRss>
		</item>
		<item>
		<title>How mocks can cut down on test maintenance</title>
		<link>http://www.exampler.com/blog/2011/10/06/how-mocks-can-cut-down-on-test-maintenance/</link>
		<comments>http://www.exampler.com/blog/2011/10/06/how-mocks-can-cut-down-on-test-maintenance/#comments</comments>
		<pubDate>Thu, 06 Oct 2011 13:28:39 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[ruby]]></category>

		<category><![CDATA[TDD]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/10/06/how-mocks-can-cut-down-on-test-maintenance/</guid>
		<description><![CDATA[After around 11 months of not working on it, I needed to make a change to Critter4us, an app I wrote for the University of Illinois vet school. The change was simple. When I tried to push it to Heroku, though, I discovered that my Ruby gems were too out of date. So, I ended [...]]]></description>
			<content:encoded><![CDATA[<p>After around 11 months of not working on it, I needed to make a change to Critter4us, an app I wrote for the University of Illinois vet school. The change was simple. When I tried to push it to <a href="http://www.heroku.com/">Heroku</a>, though, I discovered that my Ruby gems were too out of date. So, I ended up upgrading from Ruby 1.8 to 1.9, to <a href="http://www.sinatrarb.com/">Sinatra</a> 1.3 from a Sinatra less than 1.0, to a modern version of <a href="http://rack.rubyforge.org/">Rack</a>, etc. etc. In essence, I replaced all the <a href="http://en.wikipedia.org/wiki/Turtles_all_the_way_down">turtles</a> upon which my code-world was resting. There were some backwards-compatibility problems.</p>
<p>One incompatibility was that I was sending an incorrectly formatted URI to fetch some JSON data. The old version of Rack accepted it, but the new one rejected it. The easy fix was to split what had been a single `timeslice` parameter up into multiple parameters. [Update: I later did something more sensible, but it doesn&#8217;t affect the point of this post.] &#8220;Crap!&#8221;, I thought. &#8220;I&#8217;m going to have to convert who knows how much test data.&#8221; But I was pleased when I looked at the first test and saw this:</p>
<script src="https://gist.github.com/1267790.js?file=gistfile1.rb"></script>
<p>The key point here is that neither the format of the URI parameters nor the resulting timeslice object is given in its real form. Instead, they&#8217;re represented by strings that basically name their type. (In my Clojure testing framework, <a href="https://github.com/marick/Midje">Midje</a>, I refer to these things as &#8220;<a href="https://github.com/marick/Midje/wiki/Metaconstants">metaconstants</a>&#8220;.)</p>
<p>The only responsibility this code has toward timeslices is to pass them to another object. That object, the `internalizer`, has the responsibility for understanding formats. The test (and code) change is trivial:</p>
<script src="https://gist.github.com/1267811.js?file=gistfile1.rb"></script>
<p>The test is even (and appropriately) less specific than before. It says only that the GET parameters (a hash) will contain some key/value pairs of use to the internalizer. It&#8217;s up to the internalizer to know which those are and do the right thing.</p>
<p>The point here is that the size of the test change is in keeping with the size of the code change. It is unaffected by the nature of the change to the data&#8212;which is as it should be.</p>
<p>This application is the one where I finally made the important decision to use mocks heavily in the <a href="http://www.growing-object-oriented-software.com/">Freeman and Pryce</a> &#8220;London&#8221; style and&#8212;most importantly&#8212;to not fall into the trap of thinking &#8220;Mocks are stupid!&#8221; when I ran into problems. Instead, I said &#8220;<i>I&#8217;m</i> stupid!&#8221; and, working on that assumption, figured out what I was doing wrong.</p>
<p>I made that decision halfway through writing the app. One of the happy results of the mocking that followed was that a vast amount of test setup code devoted to constructing complete data structures went away. No more &#8220;fixtures&#8221; or &#8220;object mothers&#8221; or &#8220;test factories.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/10/06/how-mocks-can-cut-down-on-test-maintenance/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Clojure and the future for programmers like me</title>
		<link>http://www.exampler.com/blog/2011/09/29/my-clojure-problem/</link>
		<comments>http://www.exampler.com/blog/2011/09/29/my-clojure-problem/#comments</comments>
		<pubDate>Thu, 29 Sep 2011 19:07:48 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/09/29/my-clojure-problem/</guid>
		<description><![CDATA[
TL;DR: Attitudes common in the Clojure community are making that community increasingly unappealing to people like me. They may also be leading to a language less appealing to people like me than a Lisp should be.
I think people like me are an important constituency.
The dodgy attitudes come from the Clojure core, especially Rich Hickey himself, [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>
<i><a href="http://www.urbandictionary.com/define.php?term=tl%3Bdr">TL;DR</a>: Attitudes common in the Clojure community are making that community increasingly unappealing to people like me. They may also be leading to a language less appealing to people like me than a Lisp should be.</i></p>
<p><i>I think people like me are an important constituency.</i></p>
<p><i>The dodgy attitudes come from the Clojure core, especially Rich Hickey himself, I&#8217;m sad to say. I wish the Clojure core would be more supportive of programmers not like them, and of those with different goals. Otherwise, I&#8217;m afraid Clojure won&#8217;t achieve a popularity that justifies the kind of commitment I&#8217;ve been making to it. What should I do?</i></p></blockquote>
<p>I&#8217;ve caused a bit of kerfuffle on Twitter about Clojure and testing. I&#8217;ve been somewhat aggressive because I&#8217;m trying to suss out how much effort to put into Clojure over, say, the next year.</p>
<p>[Note to the reader: scatter &#8220;I think&#8221; and &#8220;I could be wrong&#8221; statements freely throughout the following.]</p>
<p>Here&#8217;s the deal.</p>
<p>What&#8217;s at issue is a style of working (roughly <a href="http://www.extremeprogramming.org/rules.html">XPish</a>). After some years of work by many, it&#8217;s entirely possible in the Ruby world to work in that style. After doing the whole Agile spokesmodel thing for a decade, that&#8217;s all I want: a place where there are enough people with my style that we can (1) find each other to work together, and (2) work together without having to re-justify our style to every damn person we meet. In Ruby, XP style is mainstream enough that we can let the product of our work speak for us. (Hence, my recently co-founded <a href="http://path11.com">contract software company</a>.)</p>
<p>I think it was at the 2nd <a href="http://rubyconf.org/">RubyConf</a> that <a href="http://terralien.com/">Nathaniel Talbott</a> introduced Test::Unit, a Ruby version of jUnit. I can&#8217;t be positive, but I&#8217;m pretty sure <a href="http://en.wikipedia.org/wiki/Yukihiro_Matsumoto">Matz</a> (the author of Ruby) didn&#8217;t care all that much about testing or, especially, TDD. Wasn&#8217;t his style. Perhaps still isn&#8217;t. However: he did not, to my recollection, express any reaction other than his usual &#8220;People are doing things with my language! I am happy!&#8221; And while Matz gives keynotes about design and such, they are pretty obviously about how <i>he</i> feels about design and about how <i>he</i> approaches it. They are invitations, not instructions.</p>
<p>One of the strengths of Ruby in the early days was this air of invitation. (I don&#8217;t really follow that community closely any more.) </p>
<p>Rich Hickey, for all his undoubted brilliance as a language implementor and his fruitful introspection into his own design process, presents a less welcoming demeanor than Matz&#8217;s. From what I&#8217;ve seen, he is more prone, in his public speaking and writing, to instruction than to invitation.</p>
<p>Which is OK with me, all things being equal. But there&#8217;s a problem. Brilliant solo language designers set a tone for the community that gathers around the language, especially in the early days. We&#8217;ve seen that with Python and <a href="http://on-ruby.blogspot.com/2008/03/gracious-dave-and-minswan.html">Ruby</a>. (Rails too, which acts as a contrast to the &#8220;Ruby Classic&#8221; tone.) It&#8217;s happening again in Clojure, where I&#8217;d say the picture of the ideal developer is someone who, with grim determination, wrestles a hard problem to the ground and beats it into submission with a multi-issue bound copy of <i><a href="http://en.wikipedia.org/wiki/Finger_tree">The Journal of Functional Programming</a></i>. I&#8217;m all for people who do that! So I don&#8217;t have to! But I personally prefer something more akin to the style of Ruby&#8217;s <a href="http://en.wikipedia.org/wiki/Why_the_lucky_stiff">_why</a>, who&#8217;d sneak up on a problem and tickle it until it was laughing too hard to be a problem any more.</p>
<p>I didn&#8217;t always prefer the Ruby style. Just after I started my first post-graduate job, <a href="http://en.wikipedia.org/wiki/Tony_Hoare">Tony Hoare</a>&#8217;s <a href="http://thor.cs.ucsb.edu/~ravenben/papers/coreos/Hoa81.pdf">Turing Award lecture</a> came out, containing the famous quote: </p>
<blockquote><p>I conclude that there are two ways of constructing a software design: One way is to make it so simple that there are <i>obviously</i> no deficiencies and the other way is to make it so complicated that there are no <i>obvious</i> deficiencies. The first method is far more difficult.</p></blockquote>
<p>I positively <i>thrilled</i> to that. <i>That</i> was the man I wanted to be.</p>
<p>As time went on, though, I ran into difficulties. What if you <i>can&#8217;t</i> solve the problem with that first method, whether because you&#8217;re not smart enough, or the problem domain is inherently messy, or the problem keeps changing on you? What then? Do you just give up? Or do you try to find a third method?</p>
<p>Those difficulties, plus some timely encounters with some strange thinkers, notably <a href="http://en.wikipedia.org/wiki/Paul_Feyerabend">Feyerabend</a> and his <i><a href="http://en.wikipedia.org/wiki/Against_Method">Against Method</a></i>, put me on my current career path. Which causes me to say this:</p>
<blockquote><p>
<i>For someone doing core infrastructural design, such as the huge task of tricking the JVM into running a Clojure program speedily, an emphasis on purity and simplicity&#8212;one bordering on asceticism&#8212;seems to me essential. God speed Rich Hickey for that!</i></p>
<p><i>But when a community adopts purity, simplicity, and asceticism as core tenets&#8212;ones approaching matters of morality&#8212;you can end up with a community that makes things unpleasant for not just the impure and hedonistic, but also for just plain normal people. And they will go elsewhere.</i>
</p></blockquote>
<p>Much as I love Lisp and admire Clojure, if it can&#8217;t grab the enthusiasm of, say, the median pretty-good Ruby or Java programmer who has the TDD habit, it&#8217;s not economically sensible for a cofounder of a new company to put as much effort into it as I have been putting. </p>
<p>If Clojure turns into a tool for hardcore people to solve hardcore problems, without making concessions for people with softer cores&#8212;if it remains a niche language, in other words&#8212;I should probably spend more time with Ruby. And I do think, right now, that Clojure is more likely to be a niche language than I thought last year.</p>
<p>So in the last few weeks, I&#8217;ve been sending out little probes, mainly to see if anyone with some star power can provisionally buy the story above. If so, I can hope to see an intentional broadening in a direction designed to shackle me and those like me more tightly into the Clojure community&#8212;and so help it succeed. </p>
<p>So far, <a href="http://en.wikipedia.org/wiki/Meh">meh</a>.</p>
<p>If I&#8217;m sensible, a continuing &#8220;meh&#8221; response will prompt me to reduce my effort around Clojure&#8212;to resist the temptation to <a href="http://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip/">make</a> <a href="http://www.vimeo.com/20717301">another</a> <a href="https://github.com/cgrand/enlive/wiki/Table-and-Layout-Tutorial,-Part-1:-The-Goal">tutorial</a>, to cut back on new <a href="https://github.com/marick/Midje">Midje</a> features (but not on fixes and the 1.3 port, I hasten to reassure its users!), and so on. If Clojure then wins big, I can <a href="http://en.wikipedia.org/wiki/Bandwagon_effect">jump back on the bandwagon</a>. I will have lost some early mover advantage, but that doesn&#8217;t look to be huge anyway. (Not like it was with Agile, or would have been with Ruby if I hadn&#8217;t drifted away before Rails came out.)</p>
<p>I haven&#8217;t decided what to do. Reaction to this post might help. Probably the best thing would be for me to be convinced I&#8217;m nuts. Hey, it&#8217;s happened before!</p>
<p><a href="http://www.exampler.com/blog/2011/09/30/a-postscript-about-the-validity-of-claims/">A postscript on the validity of what I claim</a></p>
<p><a href="http://www.exampler.com/blog/2011/09/30/a-postscript-on-expressiveness-and-performance/">A postscript on worries about the effect of performance on expressiveness</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/09/29/my-clojure-problem/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Further reading for &#8220;Functional Programming for Object-Oriented Programmers&#8221;</title>
		<link>http://www.exampler.com/blog/2011/09/23/further-reading-for-functional-programming-for-object-oriented-programmers/</link>
		<comments>http://www.exampler.com/blog/2011/09/23/further-reading-for-functional-programming-for-object-oriented-programmers/#comments</comments>
		<pubDate>Fri, 23 Sep 2011 19:17:26 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/09/23/further-reading-for-functional-programming-for-object-oriented-programmers/</guid>
		<description><![CDATA[I&#8217;ve been asked for things to read after my &#8220;Functional Programming for Object-Oriented Programmers&#8221; course. Here are some, concentrating on the ones that are more fun to read and less in love with difficulty for difficulty&#8217;s sake.
If you were more interested in the Clojure/Lisp part of the course:



The Little Schemer and other books by the [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been asked for things to read after my &#8220;<a href="http://www.exampler.com/blog/2011/07/29/functional-programming-for-the-object-oriented-programmer/">Functional Programming for Object-Oriented Programmers</a>&#8221; course. Here are some, concentrating on the ones that are more fun to read and less in love with difficulty for difficulty&#8217;s sake.</p>
<p>If you were more interested in the Clojure/Lisp part of the course:</p>
<ul>
<li>
<p>
<i><a href="http://www.amazon.com/Little-Schemer-Daniel-P-Friedman/dp/0262560992">The Little Schemer</a></i> and other books by the same authors. These teach some deep ideas even though they start out very simply. You&#8217;ll either find the way they&#8217;re written charming or annoying.
</p>
</li>
<li>
<p>
<i><a href="http://landoflisp.com/">Land of Lisp</a></i> is a strange book on Lisp.
</p>
</li>
<li>
<p>
If you were totally fascinated by multimethods, you could try <i><a href="http://www.amazon.com/Art-Metabobject-Protocol-Metaobject/dp/0262610744/ref=cm_lmf_tit_4">The Art of the Metaobject Protocol</a></i>.
</p>
</li>
</ul>
<p>If you were more interested in the functional programming part of the course, the suggestions are harder. So much of the writing on functional programming is overly math-fetishistic. </p>
<ul>
<li>
<p><i><a href="http://learnyouahaskell.com/">Learn You a Haskell for Great Good</a></i> is another quirky book (lots of odd drawings that have little to do with the text), but it covers many topics using the purest functional language. There&#8217;s both a paper version and a free online version. The online version has better drawings (color!).
</p>
</li>
<li>
<p>
I haven&#8217;t read <i><a href="http://www.amazon.com/Purely-Functional-Structures-Chris-Okasaki/dp/0521663504/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1316809076&amp;sr=1-1">Purely Functional Data Structures</a></i>, though I think I have it somewhere. @SamirTalwar tweeted to me that &#8220;I&#8217;m enjoying Purely Functional Data Structures. It&#8217;s quite mathsy, but with a practical bent.&#8221; The book is derived from the author&#8217;s <a href="http://www.cs.cmu.edu/~rwh/theses/okasaki.pdf">PhD thesis</a>.
</p>
</li>
</ul>
<p>The approach I took in the course was inspired by the famous <i><a href="http://mitpress.mit.edu/catalog/item/default.asp?ttype=2&amp;tid=3305">Structure and Interpretation of Computer Programs</a></i> (<a href="http://mitpress.mit.edu/sicp/full-text/book/book.html">free online version</a>). Many people find the book more difficult than most of the ones above. Part of the reason is that the problems are targeted at MIT engineering students, so you get a lot of problems that involve resistors and such.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/09/23/further-reading-for-functional-programming-for-object-oriented-programmers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Functional Programming for the Object-Oriented Programmer</title>
		<link>http://www.exampler.com/blog/2011/07/29/functional-programming-for-the-object-oriented-programmer/</link>
		<comments>http://www.exampler.com/blog/2011/07/29/functional-programming-for-the-object-oriented-programmer/#comments</comments>
		<pubDate>Fri, 29 Jul 2011 15:10:23 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/07/29/functional-programming-for-the-object-oriented-programmer/</guid>
		<description><![CDATA[Here is a draft blurb for a course I&#8217;d like to teach, possibly in Valladolid, Spain, in September. I&#8217;d like to see if enough people are interested in it, either there or somewhere else. (There&#8217;s a link to a survey after the description.)
Short version



Target audience: Programmers who know Java, C#, C++, or another object-oriented language. [...]]]></description>
			<content:encoded><![CDATA[<p>Here is a draft blurb for a course I&#8217;d like to teach, possibly in Valladolid, Spain, in September. I&#8217;d like to see if enough people are interested in it, either there or somewhere else. (There&#8217;s a link to a survey after the description.)</p>
<p><b>Short version</b></p>
<ul>
<li>
<p>
<b>Target audience</b>: Programmers who know Java, C#, C++, or another object-oriented language. Those who know languages like Ruby, Python, or JavaScript will already know some&#8212;but not all!&#8212;of the material.
</p>
</li>
<li>
<p>
<b>The goal</b>: To make you a better object-oriented programmer by giving you hands-on experience with the ideas behind functional languages. The course will use <a href="http://en.wikipedia.org/wiki/Clojure">Clojure</a> and JavaScript for its examples. You&#8217;ll learn enough of Clojure to work through exercises, but this is not a &#8220;Learn Clojure&#8221; course.
</p>
</li>
<li>
<p>
<b>After the course</b>: I expect you to return to your job programming in Java or Ruby or whatever, not to switch to Clojure. To help put the ideas into practice, you&#8217;ll get a copy of <a href="http://www.deanwampler.com/">Dean Wampler</a>&#8217;s <i><a href="http://oreilly.com/catalog/0636920021667">Functional Programming for Java Developers</a></i>.
</p>
</li>
</ul>
<p><b>Syllabus</b></p>
<ul>
<li>
Just enough Clojure
</li>
<li>
Multimethods as a generalization of methods attached to objects
</li>
<li>
Protocols as a different approach to interfaces
</li>
<li>
Functions as objects, objects as functions
</li>
<li>
Mapping and folding in contrast to iteration
</li>
<li>
Functions that create functions
</li>
<li>
Laziness and infinite sequences
</li>
<li>
Time as a sequence of events
</li>
<li>
Generic datatypes with many functions <i>versus</i> many small classes
</li>
<li>
Immutable data structures and programs as truth-statements about functions
</li>
</ul>
<div style="text-align: center"><a href="http://www.surveymonkey.com/s/GXQ5M76">Interested?</a></div>
<p><b>Longer version</b></p>
<p>Many, many of the legendary programmers know many programming languages. What they know from one language helps them write better code in another one. But it&#8217;s not really the language that matters: adding knowledge of C# to your knowledge of Java doesn&#8217;t make you much better. The languages are too similar&#8212;they encourage you to look at problems in pretty much the same way. You need to know languages that conceptualize problems and solutions in substantially different ways.</p>
<p>Once upon a time, object-oriented programming was a radical departure from what most programmers knew. So learning it was both hard and mind-expanding. Nowadays, the OO style is the dominant one, so ambitious people need to proactively seek out different styles.</p>
<p>The functional programming style is nicely different from the OO style, but there are many interesting points of comparison between them. This course aims to teach you key elements of the functional style, helping you take them back to your OO language (probably Java or C#). </p>
<p>There&#8217;s a bit more, though: although the functional style has been around for many years, it&#8217;s recently become trendy, partly because language implementations keep improving, and partly because functional languages are better suited for solving the multicore problem<sup><a href="#multicoreproblem">*</a></sup> than are other languages. Some trends with a lot of excitement behind them wither, but others (like object-oriented programming) succeed immensely. If the functional style becomes commonplace, this course will position you to be on the leading edge of that wave.</p>
<p>There are many functional languages. There are arguments for learning the purest of them (<a href="http://en.wikipedia.org/wiki/Haskell_(programming_language)">Haskell</a>, probably). But it&#8217;s also worthwhile to learn a slightly-less-pure language if there are more jobs available for it or more opportunities to fold it into your existing projects. According that standard, Clojure and <a href="http://www.scala-lang.org/">Scala</a>&#8212;both hosted on the JVM&#8212;stand out. This course will be taught mainly in Clojure. Where appropriate, I&#8217;ll also illustrate the ideas in JavaScript, a language whose <a href="http://oreilly.com/catalog/9780596517748">good parts</a> were strongly influenced by the functional style.</p>
<p>While this particular course will concentrate on what you can do in Clojure, it&#8217;d be unfair to make you do all the work of translating these ideas into your everyday language. To help you with that, every participant will get a copy of <a href="http://www.deanwampler.com/">Dean Wampler</a>&#8217;s <i><a href="http://oreilly.com/catalog/0636920021667">Functional Programming for Java Developers</a></i>, which shows how functional ideas work in Java.</p>
<p><b>Your instructor</b></p>
<p><a href="http://exampler.com/">Brian Marick</a> was first exposed to the functional style in <a href="http://en.wikipedia.org/wiki/1983">1983</a>, when the accident of knowing a little bit of Lisp tossed him into the job of technical lead on a project to port <a href="http://common-lisp.net/">Common Lisp</a> to a <a href="http://en.wikipedia.org/wiki/Systems_Engineering_Laboratories#SEL_32_series">now-defunct computer architecture</a>. That led him to a reading spree about all things Lisp, the language from which the functional style <a href="http://www.informatik.uni-trier.de/~ley/db/conf/lfp/index.html">arguably originated</a>. He&#8217;s been a language geek ever since, despite making most of his living as a software process <a href="http://exampler.com/consulting.html">consultant</a>. He&#8217;s the author of the popular <a href="https://github.com/marick/Midje">Midje</a> testing library for Clojure and has written two books (<i><a href="http://pragprog.com/book/bmsft/everyday-scripting-with-ruby">Everyday Scripting with Ruby</a></i> and <i><a href="http://pragprog.com/book/bmrc/programming-cocoa-with-ruby">Programming Cocoa with Ruby</a></i>).</p>
<p>For examples of Marick&#8217;s teaching style, read his explanations of the <a href="http://www.exampler.com/blog/2010/09/01/editing-trees-in-clojure-with-clojurezip/">Zipper</a> and <a href="https://github.com/cgrand/enlive/wiki/Table-and-Layout-Tutorial,-Part-1:-The-Goal">Enlive</a> libraries or watch his videos on <a href="http://vimeo.com/19404746">Top-down TDD in Clojure</a> and <a href="http://vimeo.com/20717301">Monads</a>. </p>
<div style="text-align: center"><a href="http://www.surveymonkey.com/s/GXQ5M76">Interested?</a></div>
<p>
&nbsp;
</p>
<p><sup><a name="multicoreproblem">*</a></sup>The <a href="http://gigaom.com/2008/06/19/multicores-not-so-secret-problem/">multicore problem</a> is that chip manufacturers have hit the wall making single CPUs faster. The days of steadily increasing clock rates are over. Cache sizes are no longer the bottleneck. The big gains from <a href="http://en.wikipedia.org/wiki/Speculative_execution">clever hardware tricks</a> have been gotten. So we programmers are getting more cores instead of faster cores, and we have to figure out how to use multiple cores in a single program. That&#8217;s a tough problem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/07/29/functional-programming-for-the-object-oriented-programmer/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Enlive tutorial</title>
		<link>http://www.exampler.com/blog/2011/07/15/enlive-tutorial/</link>
		<comments>http://www.exampler.com/blog/2011/07/15/enlive-tutorial/#comments</comments>
		<pubDate>Fri, 15 Jul 2011 15:50:02 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/07/15/enlive-tutorial/</guid>
		<description><![CDATA[Enlive is a templating library for Clojure. Instead of the usual substitute-into-delimited-text approach, it works by editing node trees selected by CSS selectors. I&#8217;ve written a tutorial for it. Comments welcome.
]]></description>
			<content:encoded><![CDATA[<p><a href="https://github.com/cgrand/enlive">Enlive</a> is a templating library for Clojure. Instead of the usual substitute-into-delimited-text approach, it works by editing node trees selected by CSS selectors. I&#8217;ve written a <a href="https://github.com/cgrand/enlive/wiki/Table-and-Layout-Tutorial,-Part-1:-The-Goal">tutorial</a> for it. Comments welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/07/15/enlive-tutorial/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A small note about with-group and hiccup</title>
		<link>http://www.exampler.com/blog/2011/07/05/a-small-note-about-with-group-and-hiccup/</link>
		<comments>http://www.exampler.com/blog/2011/07/05/a-small-note-about-with-group-and-hiccup/#comments</comments>
		<pubDate>Tue, 05 Jul 2011 20:52:30 +0000</pubDate>
		<dc:creator>Brian Marick</dc:creator>
		
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://www.exampler.com/blog/2011/07/05/a-small-note-about-with-group-and-hiccup/</guid>
		<description><![CDATA[As novice user of Hiccup, a Clojure HTML-layout format, I wanted to write a form that gathered information about N animals. Each animal had a name, a nickname, etc. I wanted to use Ring&#8217;s ring.middleware.nested-params so that I could iterate over new animals.
I had some trouble getting it to work, so perhaps this note will [...]]]></description>
			<content:encoded><![CDATA[<p>As novice user of <a href="https://github.com/weavejester/hiccup">Hiccup</a>, a Clojure HTML-layout format, I wanted to write a form that gathered information about N animals. Each animal had a name, a nickname, etc. I wanted to use <a href="https://github.com/mmcgrana/ring">Ring</a>&#8217;s <a href="https://github.com/mmcgrana/ring/blob/master/ring-core/src/ring/middleware/nested_params.clj#L48"><code>ring.middleware.nested-params</code> </a>so that I could iterate over new animals.</p>
<p>I had some trouble getting it to work, so perhaps this note will help someone else. Note that this applies to hiccup-0.3.5.</p>
<p>My first attempt was something like this:</p>
<script src="https://gist.github.com/1066212.js"> </script>
<p>This was derived from the description of <code>with-group</code> <a href="http://weavejester.com/grouping-fields-in-hiccup">here</a>. However, this didn&#8217;t work. Only the last text-field appears in the HTML page. [Note: I was using <a href="http://www.webnoir.org/">Noir</a> to render pages.]</p>
<p>Having written a builder-style renderer like Hiccup before, I thought. &#8220;Ah. I must make a vector of the rendered functions&#8221;:</p>
<script src="https://gist.github.com/1066213.js?file=gistfile1.clj"></script>
<p>That lead to a scary exception:</p>
<blockquote><p>
java.lang.RuntimeException: java.lang.RuntimeException: java.lang.IllegalArgumentException: [:label {:for &#8220;animal1-true-name&#8221;} &#8220;Name: &#8220;] is not a valid tag name.
</p></blockquote>
<p>The solution I found was to wrap the sub-form inside another element, in this case a :p:</p>
<script src="https://gist.github.com/1066238.js?file=gistfile1.clj"></script>
<p>It&#8217;s ironic that I&#8217;d do something like that as a matter of course, except that I was exploring the API. Which led me astray.</p>
<p><b>UPDATE</b>: <a href="http://chris-granger.com/blog">Chris Granger</a> points out &#8220;Hiccup treats any vector as a tag, but any other seq will work. Vectors have semantic meaning, the others don&#8217;t.&#8221; Instead of wrapping the separate steps in a vector, I should have used a list:</p>
<script src="https://gist.github.com/1067379.js?file=gistfile1.clj"></script>
<p>I should have realized that in the beginning (though one could argue that the two uses for a vector are distinguishable so why not make a vector work as well as a list?).</p>
<p>Chris also writes &#8220;In my experience the best solution is to wrap the block in (html &#8230; ). Then you never worry.&#8221; That is:</p>
<script src="https://gist.github.com/1067395.js?file=gistfile1.clj"></script>
]]></content:encoded>
			<wfw:commentRss>http://www.exampler.com/blog/2011/07/05/a-small-note-about-with-group-and-hiccup/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

