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

<channel>
	<title>Yet Another Programming Blog</title>
	<atom:link href="http://www.davehking.com/wordpress/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.davehking.com/wordpress</link>
	<description>Programming the Enterprise</description>
	<lastBuildDate>Sun, 22 Apr 2012 23:45:12 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>jasmine-mocks: A Tiny Mocking Library for Jasmine</title>
		<link>http://www.davehking.com/wordpress/?p=400</link>
		<comments>http://www.davehking.com/wordpress/?p=400#comments</comments>
		<pubDate>Sun, 22 Apr 2012 23:45:12 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=400</guid>
		<description><![CDATA[I just released version 0.0.2 of jasmine-mocks, a tiny mocking library for use with Jasmine. I really like Jasmine as a testing framework &#8212; I&#8217;ve converted my last two teams to using it and I really like how easy and &#8230; <a href="http://www.davehking.com/wordpress/?p=400">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I just released version 0.0.2 of <a title="jasmine-mocks" href="https://github.com/tildedave/jasmine-mocks" target="_blank">jasmine-mocks</a>, a tiny mocking library for use with Jasmine.</p>
<p>I really like Jasmine as a testing framework &#8212; I&#8217;ve converted my last two teams to using it and I really like how easy and expressive it makes testing.  However, I have some very minor pain points around using Jasmine for larger codebases that include a lot of little objects with very isolated behaviors. jasmine-mocks aims to address issues that arise when writing Jasmine specifications for this kind of codebase.</p>
<h3>Creating Mock Objects From Prototypical Classes</h3>
<p>jasmine-mocks allows you to easily create a mock instance from a prototypical class (defining a constructor as a function and methods as functions on the constructor&#8217;s prototype).  This removes the need for you to explicitly define functions on mock objects.</p>
<pre class="brush: javascript; ">

var Dog = function () {};
Dog.prototype.bark = function () {
 alert(&#039;bark!&#039;);
};

describe(&#039;DogTricks&#039;, function () {
  var mockDog = mock(Dog);
  var tricks = new DogTricks(mockDog);
  tricks.whistle();

  expect(mockDog.bark).toHaveBeenCalled();
});
</pre>
<h3>Mocks That Can Emit Events</h3>
<p>JavaScript frameworks allow firing events on arbitrary objects (two examples: Node&#8217;s EventEmitter and Closure&#8217;s EventTarget).  jasmine-mocks allows you to make mock objects that inherit real behavior to allow testing these objects without instantiating a real class.</p>
<pre class="brush: javascript; ">

var Dog = function () {};
Dog.prototype = Object.create(EventEmitter.prototype);
Dog.prototype.giveBiscuit = function () {
  ++this.numBiscuits;
};

describe(&#039;DogTricks&#039;, function () {
  var mockDog = mock(Dog, EventEmitter);
  var tricks = new DogTricks(mockDog);

  mockDog.emit(&#039;roll over&#039;);

  expect(mockDog.giveBiscuit).toHaveBeenCalled();
});
</pre>
<h3>Basic Matching Functionality</h3>
<p>Spies are great, but they don&#8217;t allow you to be certain you are passing the right values to them.  If you want to make sure that your Jasmine spies are being called with the right arguments you need to add extra asserts, something that shouldn&#8217;t be necessary.</p>
<p>jasmine-mocks allows you to easily create matchers that give your spies different functionality when different arguments are passed in.  The main benefit to this is not returning good values when bad arguments are passed in.</p>
<pre class="brush: javascript; ">

describe(&#039;DogFeeder&#039;, function () {
  var mockDog = mock(Dog, EventEmitter);

  when(mockDog.likesFood).isCalledWith(&#039;biscuit&#039;).thenReturn(true);
  when(mockDog.likesFood).isCalledWith(&#039;kibble&#039;).thenReturn(false);

  var dogFeeder = new DogFeeder(mockDog);
  dogFeeder.addFood(&#039;biscuit);
  dogFeeder.addFood(&#039;kibble);
  dogFeeder.feed();

  expect(mockDog.feed).toHaveBeenCalledWith(&#039;biscuit&#039;);
});
</pre>
<p>The source code is available on <a href="https://github.com/tildedave/jasmine-mocks" title="Github">Github</a>.  I hope that you find it useful!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=400</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using JQuery AJAX instead of CFAJAXProxy</title>
		<link>http://www.davehking.com/wordpress/?p=390</link>
		<comments>http://www.davehking.com/wordpress/?p=390#comments</comments>
		<pubDate>Sat, 25 Feb 2012 21:42:13 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=390</guid>
		<description><![CDATA[This is a sufficiently wacky enough scenario that I don&#8217;t think it will be useful for everyone, but I learned a bunch about how JavaScript and ColdFusion interact from client to server so writing this up is probably worthwhile. This &#8230; <a href="http://www.davehking.com/wordpress/?p=390">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This is a sufficiently wacky enough scenario that I don&#8217;t think it will be useful for everyone, but I learned a bunch about how JavaScript and ColdFusion interact from client to server so writing this up is probably worthwhile.</p>
<p>This project is a standard ColdFusion backend (CF8) that sits in front of a SQL Server database. Rows are fetched from the database and displayed in a JQuery DataTable widget &#8212; one of the main reasons of using DataTables is the Excel export.</p>
<p>Sometimes we fetch a lot of data to export (on the order of 5MB or more). This is transferred back to the browser as JSON. For most of our requests to the server, we use CFAjaxProxy to instantiate JavaScript objects that make requests to the server on method invocation:</p>
<pre class="brush: html; ">

&lt;cfajaxproxy cfc=&quot;package.model.BackendService&quot; jsclassname=&quot;BackendService&quot;&gt;&lt;/code&gt;
</pre>
<pre class="brush: javascript; ">

&lt;script type=&quot;text/javascript&quot;&gt;
  var service = new BackendService();
  service.fetchAllTheData();
&lt;/script&gt;
</pre>
<p>The specific issue I was having was that Firefox died while parsing the returned data with a console error in <code>cfajax.js</code>.  Digging into I found that the issue was related to how the browser escapes returned JSON data.</p>
<p>I replaced the method invocation with a call to JQuery&#8217;s JSON handler:</p>
<pre class="brush: javascript; ">

  proxy = new BackendService();
  // OLD CODE
  proxy.fetchAllTheData(arg1, arg2, arg3);

  // NEW CODE
  $.getJSON(&quot;/package/model/BackendService.cfc&quot;,
    {
      method: &quot;fetchAllTheData&quot;,
      returnFormat: &quot;json&quot;,
      argumentCollection: JSON.stringify(
        {
          argName1: arg1,
          argName2: arg2,
          argName3: arg3
        }
      ),
      _cf_clientid: window._cf_clientid
    },
    function (data) {
      proxy.callbackHandler(data);
    });
</pre>
<p>This had the happy effects of fixing the bug (always good) while using a more mainstream technology (JQuery 1.6+ over years-old CF8 ajax.js) for browser/server interaction.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=390</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>MUSHCode: Functional Programming the Really Hard Way</title>
		<link>http://www.davehking.com/wordpress/?p=376</link>
		<comments>http://www.davehking.com/wordpress/?p=376#comments</comments>
		<pubDate>Wed, 28 Dec 2011 01:17:32 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=376</guid>
		<description><![CDATA[One of the main languages that I learned to program with is something that&#8217;s not really a programming language in any accepted sense &#8212; MUSHCode! Back in high school and college I spent a lot of time logged in to &#8230; <a href="http://www.davehking.com/wordpress/?p=376">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the main languages that I learned to program with is something that&#8217;s not really a programming language in any accepted sense &#8212; MUSHCode!  Back in high school and college I spent a lot of time logged in to <a href="http://www.pennmush.org/">PennMUSH</a> installations.  MUSHes are like MUDs, except that while MUDs are mostly written in C, most MUSHes are powered by MUSHCode, an interpreted language that is build into the PennMUSH server.  (Non-technically, MUDs are usually more aimed at leveling up while MUSHes are more aimed at roleplaying.)</p>
<h3>What&#8217;s a MUSH, and Why MUSHCode?</h3>
<p>On a MUSH, the game world is populated by <i>objects</i>, and each object has a unique reference number (the <i>dbref</i>).  Objects have <i>attributes</i>, which can contain either data or code.  Certain attributes can listen for <i>commands</i> entered by the player, which triggers code execution.  For example, many MUSHes have a <tt>+who</tt> command, showing logged in players along with handy information (time logged in, location, what they are doing).</p>
<p><i>Wizards</i> have the permissions to create objects and change any attributes on any object, anywhere.  In practice, Wizards build the systems that power the MUSH&#8217;s roleplaying through writing MUSHCode.  MUSHCode is a layer on top of the PennMUSH server that provides things like background approval, roleplaying nominations, adjucated combat &#8212; all the things necessary to take a tabletop game online.</p>
<h3>Why is MUSHCode Interesting</h3>
<p>Code is the same as data &#8212; data is stored on objects side-by-side with code.  We are already very close to Lisp!</p>
<p>There are two main code types of MUSHCode: <i>commands</i> and <i>functions</i>.  Commands are the only way to start code execution, and these are very powerful &#8212; some fundamental things are only available as commands (namely, destruction of an object).  Functions are much more versitile and in general mode of your MUSHCode is made<br />
up of functions.</p>
<p>Here&#8217;s an example of a function:</p>
<p><tt>th iter(1|2|3|4,add(##,1),|)</tt><br />
<tt>2 3 4 5</tt></p>
<p>Here&#8217;s an example of a command:</p>
<p><tt>@pemit me=Hi there!</tt><br />
<tt>Hi there!</tt></p>
<p>Some commands and functions have overlapping functionality but during my time writing MUSHCode I found functions much more useful.  When it was time to reach for behavior that was not exposed in a function, it was time to use a command &#8212; otherwise commands were code entry points and functions would end up doing most of the work.</p>
<p>Javelin, uberdev of PennMUSH, wrote a <a href="http://community.pennmush.org/book/export/html/21">guide</a> that talks about a lot of these things, and adds a lot more technical detail.</p>
<p>Functions have a stack limit &#8212; you can&#8217;t do too much work in a function or you&#8217;d run into errors.  We ran into this a lot building our Star Wars MUSH.</p>
<h3>The Greatest Game Never Released</h3>
<p>I spent something like a year working, on and off, on a Star Wars MUSH that was never released.  I think this happens a lot in MUSH-land &#8212; people have high ambitions about the kind of games that should be built.  Some games only work once you have a critical mass of code and I fear our concept was a little high on that front.  What we did build<br />
seems amazing years later.</p>
<ul>
<li>Virtualized object system that allowed users to buy/trade/create fake objects for roleplaying purposes (mostly weapons &#8212; lightsabers, blasters)</li>
<li>Mostly complete space combat system implementing most of the Star Wars d20 space system &#8212; turn-based space combat including movement, damage, collisions, missiles</li>
<li>Viewscreens that linked ships and emitted events back and forth between the two</li>
<li>Character generation and d20 roleplaying implementation</li>
<li>Puppet system for Game Masters to create and command objects as puppets</li>
<li>All the usual MUSH CRUD applications for opening/closing/commenting on issues</li>
</ul>
<p>We apparently even wrote a bug database for keeping track of all the problems with the code I wrote!</p>
<h3>Example Code</h3>
<p>Here&#8217;s the code that powered interstellar transport.  This is a pretty simple object relatively &#8212; a character goes to a location, sees that there is a transport node, and uses this object to teleport from one planet to another (while showing them the amount of time that this would take in-game to discourage planet-hopping for the sake of it).</p>
<div id="gist-1525601" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>PARENT: Intergalactic Transportation Node(#690TWn)</div><div class='line' id='LC2'>Type: THING Flags: WIZARD NO_COMMAND</div><div class='line' id='LC3'>An intergalactic transport node.  See [ansi(hy,+help transports)] for information as to their use.</div><div class='line' id='LC4'>Owner: Pozzo(#270POWwerACMcJ)  Zone: *NOTHING*  Building Chips: 10</div><div class='line' id='LC5'>Parent: *NOTHING*</div><div class='line' id='LC6'>Powers: </div><div class='line' id='LC7'>Channels: SpaceMonitor</div><div class='line' id='LC8'>Warnings checked: </div><div class='line' id='LC9'>Created: Thu May 20 20:53:07 2004</div><div class='line' id='LC10'>Last Modification: Sun Mar 18 17:53:42 2007</div><div class='line' id='LC11'>CMD_+TRANSPORT [#270R]: $^\+transport (.+)$:@switch [u(fn_cmd.+transport,%1)]=0,{th [syspemit(%#,%qz)]},1,{th [u(fn_cmd.do_+transport)]}</div><div class='line' id='LC12'>CMD_+TRANSPORT_LIST [#270R]: $^\+transport\/list$:@pemit %#=[u(fn_cmd.+transport_list)]</div><div class='line' id='LC13'>FN_CMD.DO_+TRANSPORT [#270]: [syspemit(%#,You take [setr(g,a transport from [ansi(hy,[name(loc(%!))])] to [ansi(hy,[name(%qd)])].  The trip takes [setq(h,u(fn_get_travel_time_between_systems,u(zone(loc(%!))/fn_get_system),u(zone(squish(%qd))/fn_get_system)))][iter(timestring(mul(%qh,60,60)),if(and(f(strmatch(##,0*)),f(strmatch(##,*m)),f(strmatch(##,*s))),##),,)] of IC time)]; please RP accordingly.)][tel(%#,%qd)][remit(loc(%!),[name(%#)] leaves on a transport.)][remit(%qd,[name(%#)] arrives on a transport.)][cemit(spacemonitor,%n takes %qg.,1)]</div><div class='line' id='LC14'>FN_CMD.+TRANSPORT [#270]: [setq(z,[setq(d,iter(u(fn_get_other_nodes),if(strmatch([squish(u(fn_get_name,##))],%0*),##),,))][if(f(%qd),%0 does not match any transport node.,if(gt(words(%qd),2),%0 matches more than one possible transport node; please be more specific.))])][f(%qz)]</div><div class='line' id='LC15'>FN_CMD.+TRANSPORT_LIST [#270]: [header(Transport Node: [u(get_name)],,hw,,b)]%r[ljust(ansi(g,Destination:),30)][ljust(ansi(g,Destination),15)][ansi(g,Travel Time (IC hours))]%r[iter(setr(l,iter(lattr(v(trans_db)/*_nodes),remove(xget(v(trans_db),##),loc(%!)),%b)),[ljust(u(fn_get_name,##),30)][ljust(if(isdbref(setr(g,u(zone(##)/fn_get_system))),u(%qg/get_name),%qg),15)][u(fn_get_travel_time_between_systems,u(zone(loc(%!))/fn_get_system),u(zone(##)/fn_get_system))],,%r)]%r[header(,[setr(w,words(%ql))] Destination[if(gt(words(%ql),1),s)],,hw,b)]</div><div class='line' id='LC16'>FN_GET_NAME [#270]: [setq(a,squish(rest(name(%0),:)))][if(hasattr(%0,display_name),xget(%0,display_name),if(strmatch(name(%0),*:*),%qa,if(strmatch(name(%0),*--*),after(name(%0),--%b),name(%0))))]</div><div class='line' id='LC17'>FN_GET_OTHER_NODES [#270]: setr(l,iter(lattr(v(trans_db)/*_nodes),remove(xget(v(trans_db),##),loc(%!))))</div><div class='line' id='LC18'>FN_GET_REGION_FOR_SYSTEM [#270]: [extract(grab(xget(v(hyper_obj),system_region_mapping),[edit(%0,%b,_)]|*),2,1,|)]</div><div class='line' id='LC19'>FN_GET_REGION_NUMBER_FOR_SYSTEM [#270]: [member(xget(v(hyper_obj),space_regions),extract(grab(xget(v(hyper_obj),system_region_mapping),[edit(%0,%b,_)]|*),2,1,|))]</div><div class='line' id='LC20'>FN_GET_SYSTEM [#270]: [if(hasattr(loc(loc(%0)),wing),loc(loc(loc(%0))),if(xget(loc(%0),ship),loc(loc(%0)),ulocal(zone(loc(%0))/fn_get_system)))]</div><div class='line' id='LC21'>FN_GET_TRAVEL_TIME_BETWEEN_SYSTEMS [#270]: [setq(0,if(isdbref(%0),squish(rest(name(%0),:)),%0))][setq(1,if(isdbref(%1),squish(rest(name(%1),:)),%1))][mul(extract(extract(xget(v(hyper_obj),space_travel_times),ulocal(fn_get_region_number_for_system,%q0),1,|),ulocal(fn_get_region_number_for_system,%q1),1),2)]</div><div class='line' id='LC22'>GET_NAME [#270]: [name(loc(%!))]</div><div class='line' id='LC23'>HYPER_OBJ [#270]: #405</div><div class='line' id='LC24'>TRANS_DB [#270]: #691</div><div class='line' id='LC25'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1525601/149be4a0fedb695ccb8de350a5b9e374ddac3c9f/gistfile1.txt" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1525601#file_gistfile1.txt" style="float:right;margin-right:10px;color:#666">gistfile1.txt</a>
            <a href="https://gist.github.com/1525601">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<ul>
<li><tt>CMD_+TRANSPORT</tt> is the entry point.  You type in <tt>+transport LOCATION</tt> to be transported to a location (specified by name).
<li><tt>FN_CMD.+TRANSPORT</tt> does validation: take the list of other transport nodes.  Get their names.  Make sure that the string that the user typed matches one and only one of them.</li>
<li><tt>FN_CMD.DO_+TRANSPORT</tt> performs the action.  It&#8217;s worth examining this one more closely.
</ul>
<div id="gist-1525617" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'>[syspemit(%#,</div><div class='line' id='LC2'>&nbsp;You take [setr(g,a transport from [ansi(hy,[name(loc(%!))])] </div><div class='line' id='LC3'>&nbsp;to [ansi(hy,[name(%qd)])]. The trip takes</div><div class='line' id='LC4'>&nbsp;[setq(h,u(fn_get_travel_time_between_systems,</div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;u(zone(loc(%!))/fn_get_system), </div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;u(zone(squish(%qd))/fn_get_system)))]</div><div class='line' id='LC7'><br/></div><div class='line' id='LC8'>&nbsp;[iter(timestring(mul(%qh,60,60)),</div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;if(and(f(strmatch(##,0*)), </div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f(strmatch(##,*m)),</div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;f(strmatch(##,*s))),##),,)] of IC time)]; please RP accordingly.)]</div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>[tel(%#,%qd)]</div><div class='line' id='LC14'>[remit(loc(%!),[name(%#)] leaves on a transport.)]</div><div class='line' id='LC15'>[remit(%qd,[name(%#)] arrives on a transport.)]</div><div class='line' id='LC16'>[cemit(spacemonitor,%n takes %qg.,1)]</div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/1525617/b32923a4cb8cfe50514f944b05066ec0eff1862d/FN_CMD.DO_+TRANSPORT" style="float:right;">view raw</a>
            <a href="https://gist.github.com/1525617#file_fn_cmd.do_+transport" style="float:right;margin-right:10px;color:#666">FN_CMD.DO_+TRANSPORT</a>
            <a href="https://gist.github.com/1525617">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<ul>
<li><tt>setr</tt> sets a local variable and returns that value for later use.  There doesn&#8217;t appear to be a reason to save the name of the leaving location here &#8212; looks like dead code!</li>
<li><tt>setq</tt> sets a local variable and returns nothing.  Here we set register &#8216;h&#8217; to the travel time (in hours) between the two systems.  This is mostly used to make the code more &#8216;readable&#8217; by breaking out separate concepts into their own computation.</li>
<li>The travel time between systems is computed by calling the <tt>fn_get_travel_time_between_systems</tt> on the &#8216;systems&#8217; where the different transport nodes are located.  This is an involved computation that I won&#8217;t get into.
<li>We multiply <tt>%qh</tt> by 60 minutes and 60 seconds to get the number of seconds of travel time.  (Needed to pass to <tt>timestring</tt>, which returns a nicely formatted list of days, hours, minutes, and seconds from a num of seconds.)</li>
<li>The iter over a timestring is just plucking the &#8216;hours&#8217; out of a string of the format <tt>0d  8h 47m 21s</tt> in a particularly awful way.</li>
<li><tt>tel</tt> actually teleports the player to the other location.</li>
<li><tt>remit</tt> sends a message to the former and current location of the players.</li>
<li><tt>cemit</tt> sends a message to a channel.</li>
</ul>
<p>Here setq forms the <tt>let</tt>-mechanism of the language. <tt>iter</tt> forms the standard mapping function, with the argument passed in being code that takes an argument of <tt>##</tt> &#8212; a lambda! </p>
<h3>Good Things</h3>
<p>MUSHCode made me a much better programmer, and I didn&#8217;t even notice it was happening while it was being done.  While I was working during the day on my coursework in graduate school and undergraduate, in the evenings and weekends I would hack away on building the systems to power this MUSH.</p>
<p>The everything-is-just-a-string mentality of MUSHCode made adapting to functional languages a breeze &#8212; in the <tt>iter()</tt> example above, the second argument is code that will be executed as the list of iterated through, substituting <tt>##</tt> for the current argument.</p>
<p>I came up with a code style that was my own that still looks pretty clean today.  The work that I did was also a huge help in breaking down product requirements and developing a technical plan &#8212; the kind of thing that we do every day as software developers.</p>
<p>The thing that I find so amazing looking back is how clearly learning this &#8216;language&#8217; influenced my development as a programmer &#8230; even while I didn&#8217;t think I was doing anything of the kind!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=376</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Talk: Building Killer Web Apps</title>
		<link>http://www.davehking.com/wordpress/?p=371</link>
		<comments>http://www.davehking.com/wordpress/?p=371#comments</comments>
		<pubDate>Wed, 07 Dec 2011 01:12:16 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=371</guid>
		<description><![CDATA[The slides from my talk &#8220;Building Killer Web Applications&#8221; in the University Mall are available here.]]></description>
			<content:encoded><![CDATA[<p>The slides from my talk &#8220;Building Killer Web Applications&#8221; in the University Mall are available <a href="http://davehking.com/talks/killer-web-apps.pdf">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=371</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Greenbar: Browser-Based TDD for Python</title>
		<link>http://www.davehking.com/wordpress/?p=355</link>
		<comments>http://www.davehking.com/wordpress/?p=355#comments</comments>
		<pubDate>Mon, 22 Aug 2011 01:30:35 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=355</guid>
		<description><![CDATA[I am not a fan of dynamic languages. Ultimately I believe they solve the wrong problems: static languages prevent a lot of boneheaded mistakes by allowing you to give guarantees to your code before it is even executed. I&#8217;ve written &#8230; <a href="http://www.davehking.com/wordpress/?p=355">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I am not a fan of dynamic languages.  Ultimately I believe they solve the wrong problems: static languages prevent a lot of boneheaded mistakes by allowing you to give guarantees to your code before it is even executed.  I&#8217;ve <a href=" http://www.davehking.com/wordpress/?p=59">written before</a> about how one of Java&#8217;s backdoor features is that jamming operations together becomes a mess.</p>
<p>When developing in dynamic languages like Python and Ruby, it is even more important to provide a comprehensive unit test suite describing the low-level contract of the system than usual.  You have no compiler step to save you from yourself &#8212; the interpreter assumes that you know what you&#8217;re doing, leading you to rely on tests more than ever.</p>
<p>I&#8217;m going to talk about my favorite way to write tests for dynamic languages.  I think it hits a sweet spot that is viscerally satisfying &#8212; a sweet spot that is only possible because of the absence of a compilation phase.</p>
<h2>In JavaScript</h2>
<p>One of the coolest features of JavaScript is that, because everything is in the browser, you can tie a unit test framework into a web page.  The one I&#8217;m most familiar with is <a href="http://pivotal.github.com/jasmine/">Jasmine</a>.  In writing Jasmine tests, you slowly grow a <b>Spec Runner</b>, an HTML file that points to your source files (<tt>Calculator.js</tt>) and your JavaScript specification files (<tt>CalculatorSpec.js</tt>).</p>
<p>The speed at which Jasmine specifications run is extremely satisfying, making the traditional <a href="http://c2.com/cgi/wiki?TestDrivenDevelopment">TDD cycle</a> go very fast.</p>
<ul>
<li>Write a test</li>
<li>Reload browser, see failure (<b>RED BAR</b>)</li>
<li>Write the functionality for that test</li>
<li>Reload browser, see success (<b>GREEN BAR</b>)</li>
<li>Refactor, check that all specifications still succeed</li>
</ul>
<p>In other languages, I can end up impatient with my compilers (especially when using a hog like Maven or when changing one header file causes an entire C++ project to be recompiled) and will sometimes delay writing tests knowing that it will take a ridiculous amount of time to see even the red bar.</p>
<h2>Why the Browser?</h2>
<p>I think that my generation has been conditioned to interact with the world through the browser.  Check your favorite news site/RSS feed, read through all the articles &#8212; when you run out, you want to see if there are more &#8230; refresh the browser.</p>
<p>Reloading the browser to see what&#8217;s new has a powerful psychological effect.  After years of web browsing I have been conditioned to refresh the browser to see what new goodies await.</p>
<p>When I see a failure in a browser-based testing environment, I want to fix it.  I will always have a much deeper emotional commitment to typing the &#8216;reload&#8217; key combination on my browser than I ever will to JUnit output.</p>
<h2>In Python</h2>
<p>I&#8217;ve just finished up work on the initial version of <a href="https://github.com/tildedave/greenbar">Greenbar</a>, a server that runs in the browser and runs <a href="http://readthedocs.org/docs/nose/en/latest/">nosetests</a> on the specified directory every time you reload the page.</p>
<p>Here is a failed test:</p>
<p><img src="http://github.com/tildedave/greenbar/raw/master/redbar.png" width="600"></p>
<p>Here is a successful test:</p>
<p><img src="http://github.com/tildedave/greenbar/raw/master/greenbar.png" width="600"></p>
<p>I hope that Greenbar is useful &#8212; I will definitely be trying using it for my next Python project.</p>
<p>If you haven&#8217;t tried out browser-based TDD, you are missing out &#8212; the rapid cycle makes developing extremely satisfying and TDD generates a test suite that allows for you to refactor your code without fear of breaking anything.</p>
<h2>Other Similar Projects</h2>
<ul>
<li><a href="http://pivotal.github.com/jasmine/">Jasmine</a> (JavaScript)</li>
<li><a href="http://mattmueller.me/blog/phpunit-test-report-unit-testing-in-the-browser">PHPUnit Test Report</a> (PHP)</li>
<li><a href="http://mxunit.org">MXUnit</a> (ColdFusion)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=355</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>It&#8217;s Time For You To Learn JavaScript</title>
		<link>http://www.davehking.com/wordpress/?p=339</link>
		<comments>http://www.davehking.com/wordpress/?p=339#comments</comments>
		<pubDate>Fri, 15 Jul 2011 02:12:00 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=339</guid>
		<description><![CDATA[My first job was writing C++ applications on Windows (2000-2001, 2002-2003). My second job was writing C++ applications on Linux (2002-2003). Along the way I picked up Java in classes and used that for a summer project (2003). In graduate &#8230; <a href="http://www.davehking.com/wordpress/?p=339">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My first job was writing C++ applications on Windows (2000-2001, 2002-2003).  My second job was writing C++ applications on Linux (2002-2003).  Along the way I picked up Java in classes and used that for a summer project (2003).  In graduate school I hacked with SML, OCaml, and Java, writing applications in support of programming language research.</p>
<p>The web revolution occurred without me.  I only started writing web applications a little over a year ago (PHP, then Python, then Ruby, then .NET MVC and Java).  I still have a lot to learn on how to build a web application, but I think I understand the basics now.</p>
<p>If you&#8217;re like me and have been fundamentally a &#8216;backend&#8217; programmer most of your life &#8212; if you&#8217;ve programmed more algorithms than applications and haven&#8217;t ventured into the web application world, you have probably missed out on a vital piece of the new technology stack.</p>
<p><b>It&#8217;s time for you to learn JavaScript.</b></p>
<h3>JavaScript Is Everywhere</h3>
<p>If you write an application in JavaScript, everyone can use it &#8212; technical, non-technical, developer or consumer.  Fully featured web applications are the direction that the web is going towards, and JavaScript is starting to invade the server through <a href="http://www.mozilla.org/rhino/">Rhino</a>, <a href="https://developer.mozilla.org/en/SpiderMonkey">SpiderMonkey</a> and <a href="http://nodejs.org/">Node</a>.  (Also, <a href="http://www.commonjs.org/">CommonJS</a> is attempting to define a non-browser API.)</p>
<p>It&#8217;s not as obvious that JavaScript has any advantage on the server, but if a standard for file/socket interaction that can run on both the server and the client catches on, watch out: languages don&#8217;t necessarily win because of technical merit, they win through inertia.  Running different parts on your application in different places on the same technology is a powerful argument for a technology stack.</p>
<h3>JavaScript Is Just Like Any Other Language</h3>
<p>You get to take with you all of the skills you&#8217;ve learned from developing in other languages.  Are you a Java developer?  JavaScript has some familiar syntax and some basic object-oriented boilerplate will help you along until you&#8217;re ready to tackle exactly what a &#8216;prototype&#8217; is.  Are you a functional programmer?  JavaScript gives you first class closures.  Libraries like <a href="http://documentcloud.github.com/underscore/">Underscore</a> allow you to use functional programming concepts in your applications. (sadly, no macros yet, though).</p>
<h3>JavaScript Is Getting Better</h3>
<p>Libraries like JQuery, Prototype, and Google Closure Library abstract the browser-specific ugliness of the Document-Object-Model API.  Doing a <code>jQuery.ajax</code> means you don&#8217;t have to wonder if <code>XMLHttpRequest</code> is defined or not.</p>
<p>Libraries like Google&#8217;s V8 are working to bring the speed of virtual machines (like Java&#8217;s JVM) into the browser.  Faster client applications means a more responsive GMail, Google Docs, Google Plus.</p>
<p>Developers are even starting to step in where the ECMA standards body is not, by providing tools for common language features like dependency management (<a href="http://requirejs.org/">RequireJS</a>, <a href="http://getsprockets.org/">Sprockets</a>) and static type-checking (<a href="http://code.google.com/closure/compiler/">Closure Compiler</a>).</p>
<p>There is a <a href="http://www.crockford.com/javascript/">&#8216;good JavaScript&#8217;</a> movement determined to write better JavaScript code in the same way that unit testing/clean code has aspired to make developers write better C++/Java/C# code.  </p>
<p>JavaScript faces a number of interesting challenges in the path to writing better code: inconsistent DOM API, lots of applications are basically GUIs (difficult to test in the first place), entrenched programmer beliefs about JavaScript not being a &#8216;real&#8217; application.</p>
<h3>It&#8217;s Easy To Learn</h3>
<p>Everyone already has a read-eval-print loop for playing around with JavaScript syntax &#8212; it&#8217;s their browser!  Google Chrome lets you turn on developer tools, go straight to the console and start hacking out JavaScript code.  There are also many in-browser JavaScript <a href="http://eloquentjavascript.net/paper.html">development environments</a> available for you to choose from to get immediate feedback.</p>
<p>There are a number of great resources available to help you learn JavaScript the <b>Language</b>, not simply JavaScript the browser toy.  Right now my favorite is <a href="http://eloquentjavascript.net/">Eloquent JavaScript</a> &#8212; it introduces the language by itself without appealing to any libraries like JQuery [1].  I especially like the <a href="http://eloquentjavascript.net/chapter8.html">Object Oriented Programming chapter</a> &#8212; it makes it very clear how to build objects in a way that&#8217;s familiar from my years and years of Java/C++ programming.</p>
<p>Once that&#8217;s finished, I like <a href="http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742">JavaScript: the Good Parts</a> and the <a href="http://bonsaiden.github.com/JavaScript-Garden/">JavaScript Garden</a> for rounding out the parts of the language that are a little more foreign to me.</p>
<h3>Very Flexible For Testing</h3>
<p>Because anything can be redefined at runtime, it&#8217;s easier to create seams to test poorly architected code.  At work, we&#8217;ve redefined the <code>jQuery.ajax</code> function to test parts of our code that interacts with the server from the client.</p>
<p><a href="http://pivotal.github.com/jasmine/">Jasmine</a> is my testing framework of choice for JavaScript (in part because that&#8217;s what I used first).  As a developer, the really satisfying thing for me in writing JavaScript tests is how fast they take to run.  Control-Shift-R to reload the browser, all tests ran in 0.075 seconds.  This makes doing TDD for JavaScript really easy (easy enough so that I&#8217;ll remember to do it!).</p>
<h3>Conclusion</h3>
<p>I&#8217;m not a JavaScript expert yet, but I&#8217;m trying to get better.  If you&#8217;re also looking to improve I <i>really</i> recommend that your next project be in JavaScript.  It doesn&#8217;t have to be a web application &#8212; it can be anything.  It might not even talk to the browser at all.</p>
<p>JavaScript is just a language like any other.  You still need to write tests.  You still need to write small methods, small objects, and make sure you have seams for testing through dependency injection.  Prototype-based inheritance is a little strange at first, but it&#8217;s not really too hard once you take some time to see what it&#8217;s doing.</p>
<p>As developers, we need to take all the great things we&#8217;ve learned about agile development and apply them to JavaScript development.  Having a common platform in the browser and an expanding list of full-featured JavaScript applications means that JavaScript has already won.</p>
<hr />
<p>[1] I like JQuery a lot but it&#8217;s very important to understand what in your JavaScript code is JavaScript, and what is JQuery.  JQuery is just too useful for Getting Things Done &#8212; this blurs the lines and sometimes makes me forget, yes, JavaScript has for loops!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=339</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t Use Floats or Doubles*</title>
		<link>http://www.davehking.com/wordpress/?p=310</link>
		<comments>http://www.davehking.com/wordpress/?p=310#comments</comments>
		<pubDate>Wed, 06 Jul 2011 02:37:39 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=310</guid>
		<description><![CDATA[* Obviously programs involved with computer graphics, simulations, statistics, and scientific computing need to use floats and doubles for a lot of reasons. If you&#8217;re not doing one of those things, read on! A major code smell is using IEEE &#8230; <a href="http://www.davehking.com/wordpress/?p=310">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><br />
* Obviously programs involved with computer graphics, simulations, statistics, and scientific computing need to use floats and doubles for a lot of reasons.  If you&#8217;re not doing one of those things, read on!</p>
<p>A major code smell is using IEEE 754 floating point numbers when an accurate representation is required.  Most tasks I deal with in programming customer-facing webapp require accurate representation of units and I believe most programmers are not clear on what the built-in floating point types for a language actually provide.</p>
<h2>Doubles Do Not Store Precise Values</h2>
<p>Let&#8217;s check <a href="http://en.wikipedia.org/wiki/Double_precision_floating-point_format">Wikipedia</a>.  A 64 bit floating point number is represented in the computer by:</p>
<ul>
<li>1 sign bit</li>
<li>11 exponent bits</li>
<li>53 &#8216;signficands&#8217;</li>
</ul>
<p>You get 53 bits of precision, stored in a binary format.  Specifically, if \(e\) is the exponent, \(s\) is the sign, and \(b_0, \ldots, b_{53}\) are the bits of the significand, the number \(d\) is stored as </p>
<p>$$d = (-1)^{s} * 1.b_0 b_1 b_2 \ldots b_{53} * 2^{e-1023}$$</p>
<p>This is great if the number you are storing is expressable as a whole number or a finite sum of binary fractions.  Unfortunately, most numbers do not satisfy this.  In fact, pretty much any number doesn&#8217;t satisfy this.</p>
<p>Let&#8217;s check out the Clojure REPL to see what&#8217;s going on underneath the surface of <tt>java.lang.Double</tt>.</p>
<pre class="brush: java; ">

user=&gt; (Double/toHexString 2.0)
&quot;0x1.0p1&quot;
user=&gt; (Double/toHexString 0.5)
&quot;0x1.0p-1&quot;
user=&gt; (Double/toHexString 0.2)
&quot;0x1.999999999999ap-3&quot;
user=&gt; (Double/toHexString 0.3)
&quot;0x1.3333333333333p-2&quot;
</pre>
<p>The numbers \(0.2\) and \(0.3\) have inexact representations on the machine level because they are not expressable as a finite sum of powers of 2.  Notice that the powers of 2 (\(2.0\) and \(0.5\)) do just fine.</p>
<h2>Don&#8217;t Cast Doubles to Floats</h2>
<p>This just makes a bad decision worse &#8212; you are truncating away significant digits by converting from a 64 bit representation into a 32 bit representation.</p>
<h2>Never, ever, ever use Floats or Doubles for Money</h2>
<p>Money needs to be precise.  IEEE 754 digits were never intended to serve as precise values.  Every language has an arbitrary precision arithmetic library.  Use that library instead.</p>
<p>Still bad is using floats and doubles in measuring things that result in a payment, or measure a payment.  Prefer integer/long values for this when possible, measured in atoms &#8212; the smallest unit of measurement in your system (bytes of bandwidth in, teraflops, compute cycles, whatever).</p>
<p><b>If you are writing code that involves money, never <i>ever</i> use floats or doubles.</b></p>
<h2>Do the Right Thing</h2>
<p><a href="http://docs.racket-lang.org/reference/numbers.html">Racket</a> has the concept of an exact (arbitary precision) and inexact (IEEE 754) number.  Unfortunately exact numbers can become inexact numbers when involved with certain arithmetic operations.</p>
<p>For Java, use <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html">BigDecimal</a>.  For Ruby, use <a href="http://www.ruby-doc.org/stdlib/libdoc/bigdecimal/rdoc/index.html">BigDecimal</a>.  For Haskell, use <a href="http://hackage.haskell.org/packages/archive/Decimal/latest/doc/html/Data-Decimal.html#t:DecimalRaw">Data.Decimal</a>.  For C++, consider <a href="http://gmplib.org/">GMP</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=310</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clojure: DSLs as Configuration</title>
		<link>http://www.davehking.com/wordpress/?p=278</link>
		<comments>http://www.davehking.com/wordpress/?p=278#comments</comments>
		<pubDate>Fri, 03 Jun 2011 00:35:34 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=278</guid>
		<description><![CDATA[Configuration has a place within a software project [1]. Some things are truly external to the code and should be accessed out of it. I think that dependency injection frameworks like Spring do a good job of this, allowing you &#8230; <a href="http://www.davehking.com/wordpress/?p=278">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Configuration has a place within a software project [1].  Some things are truly external to the code and should be accessed out of it.  I think that dependency injection frameworks like <a href="http://www.springsource.org/">Spring</a> do a good job of this, allowing you to specify the wiring of your objects outside of your program.</p>
<p>However, XML/JSON is just a document.  DSLs (domain-specific languages) are programmable documents.  In Java and C#, libraries like <a href="http://fluentnhibernate.org/">Fluent NHibernate</a>, <a href="http://mockito.org/">Mockito</a>, and <a href="http://www.jmock.org/">JMock</a> wrap library interaction as a psuedo-DSL, though still recognizably in their original language.  In Ruby, <a href="http://rubyonrails.org/">Rails</a> and <a href="http://wiki.opscode.com/display/chef/Home">Chef</a> allow for specifications that seem completely divorced from their original language.</p>
<p>Clojure is a LISP port for the JVM and CLR.  In LISP, macros allow for completely reprogrammable syntax, but they are one of the more advanced features of the language involving some more esoteric syntax.  (In honesty usually I don&#8217;t feel like I need to change language syntax for my programs!)</p>
<h1>Example Application: Restmock</h1>
<p><a href="https://github.com/tildedave/restmock">Restmock</a> is a server for serving mostly static content, indexed by a configuration file.  The original reason for it was during the development of a frontend for a REST backend.  During the development lifecycle for a frontend application, there is a lot of minor work that doesn&#8217;t a semantically rich backend and Restmock was developed in order to allow programmers to move faster during these tasks.</p>
<p>Serving static content is not a difficult task and is easily accomplished with many microframeworks [2] in a lot of different language.  I wanted a flexible application that could have a web &#8216;core&#8217; for which would not change often, but which could change its behavior based solely on a external configuration file.  Specifically, I didn&#8217;t want to have to change any code in the event that I needed to add another document.</p>
<p>Why Clojure?  At work, my team programs primarily in Java.  By bundling a server together with a configuration (with <code>lein uberjar</code> [3]), I could distribute a mock service backend that would work out of the box, without any need to install a new compiler or interpreter.</p>
<h1>Configuration Take 1: XML</h1>
<p>My first take on how to configure Restmock was to provide an XML file programmatically specifying routes.</p>
<pre class="brush: xml; ">

&lt;route&gt;
  &lt;id&gt;can retrieve all the kittens&lt;/id&gt;
  &lt;request&gt;
    &lt;path&gt;/kittens&lt;/path&gt;
    &lt;method&gt;:get&lt;/method&gt;
  &lt;/request&gt;
  &lt;response&gt;
    &lt;type&gt;text&lt;/type&gt;
    &lt;config&gt;
      &lt;text&gt;Some adorable kittens!&lt;/text&gt;
    &lt;/config&gt;
  &lt;/response&gt;
&lt;/route&gt;
&lt;route&gt;
  &lt;id&gt;can&#039;t make a new kitten&lt;/id&gt;
  &lt;request&gt;
    &lt;path&gt;/kittens&lt;/path&gt;
    &lt;method&gt;:post&lt;/method&gt;
  &lt;/request&gt;
  &lt;response&gt;
    &lt;type&gt;status&lt;/type&gt;
    &lt;config&gt;
      &lt;status&gt;422&lt;/status&gt;
    &lt;/config&gt;
  &lt;/response&gt;
&lt;/route&gt;
&lt;route&gt;
  &lt;id&gt;can update a kitten&lt;/id&gt;
  &lt;request&gt;
    &lt;path&gt;/kittens/([0-9]+)&lt;/path&gt;
    &lt;method&gt;:put&lt;/method&gt;
  &lt;/request&gt;
  &lt;response&gt;
    &lt;type&gt;status&lt;/type&gt;
    &lt;config&gt;
      &lt;status&gt;202&lt;/status&gt;
    &lt;/config&gt;
  &lt;/response&gt;
&lt;/route&gt;
&lt;route&gt;
  &lt;id&gt;xml representation of a kitten&lt;/id&gt;
  &lt;request&gt;
    &lt;path&gt;/kittens/([0-9]+)&lt;/path&gt;
    &lt;method&gt;:get&lt;/method&gt;
  &lt;/request&gt;
  &lt;response&gt;
    &lt;type&gt;file&lt;/type&gt;
    &lt;config&gt;
      &lt;path&gt;cute-kitten.xml&lt;/path&gt;
    &lt;/config&gt;
  &lt;/response&gt;
&lt;/route&gt;
</pre>
<p>XML-phobics may cringe, but really this is fine.  It let me achieve my initial goal to distribute a useful server to other team members.  However, it is very inflexible.  There is no way to handle server state; you will always return the same file on the same request.  There is no way to test that your backend is doing the right thing with regards to PUT, POSTs, DELETEs without checking the logs.</p>
<h1>Configuration Take 2: Clojure Macros</h1>
<p>What we are really doing in the above XML is building a server.  There are a few nouns used to build this server:</p>
<ul>
<li><i>Request criteria</i>: Does an incoming request match this route?</li>
<li><i>Response</i>: What should I respond if a request matches my request criteria?</li>
</ul>
<p>Requests, responses, and the specific types of request criteria and responses end up being the new syntax of our server specification using a Clojure DSL.  The equivalent specification of the above XML file in a macro-based DSL looks like:</p>
<pre class="brush: java; ">

(routes
 (route &quot;Can retrieve all the kittens&quot;
        (request (uri &quot;/kittens&quot;)
                 (method :get))
        (response (text &quot;Some adorable kittens!&quot;)))
 (route &quot;Can&#039;t make a new kitten&quot;
        (request (uri &quot;/kittens&quot;)
                 (method :post))
        (response (status 422)))
 (route &quot;Can update a kitten&quot;
        (request (uri &quot;/kittens/([0-9]+)&quot;)
                 (method :put))
        (response (status 202)))
 (route &quot;Kitten XML&quot;
        (request (uri &quot;/kittens/([0-9]+)&quot;))
        (response (xml-file &quot;cute-kitten.xml&quot;))))
</pre>
<p>What should this look like when it is converted into code?</p>
<ul>
<li>Request criteria should be a function that takes a request object and returns either true or false.</li>
<li>Responses should either be HTTP response objects or functions from request objects to HTTP response objects (in case we want to change how responses look for similar requests, i.e. return the ID as part of the XML for a request to <code>kittens/1</code>).</li>
<li>A collection of routes tries each route&#8217;s request criteria until one is matched, and then returns the response associated with that route.</li>
</ul>
<h2>Request Criteria Macros</h2>
<pre class="brush: java; ">

(defmacro uri
  &quot;Specifies a criteria of matching a URI&quot;
  [path]
  `(fn [req#]
     (if (nil? (:uri req#))
       false
       (not (nil? (re-matches (re-pattern ~path)
                                     (:uri req#)))))))

(defmacro method
  &quot;Specifies a criteria of matching a HTTP request&#039;s method&quot;
  [method]
  `(fn [req#]
     (= ~method (:request-method req#))))

(defmacro request
  &quot;Specifies a list of criteria to match a request on&quot;
  [&amp; criteria]
  `(fn [req#]
     (reduce #(and %1 %2)
             (map #(% req#)
                  (list ~@criteria)))))
</pre>
<p>In the above, there is some unusual syntax associated with making a macro:</p>
<ul>
<li>The <code>`</code> at the start means to replace the macro with literally the following syntactic form.</li>
<li><code>~</code> means to evaluate a symbol.</li>
<li><code>req#</code> tells the interpreter to always expand <code>req</code> to a different variable name in different locations to prevent namespace collisions.</li>
<li><code>~@criteria</code> means to take all the arguments represented by the symbol <code>criteria</code> and change them from a list back to a set of arguments.</li>
</ul>
<p>The request macro first converts each of its criteria into a function from requests to booleans and returns a function from requests to booleans that requires all request criteria to be true.  (It may look a little complicated, but it is &#8220;just&#8221; a left fold over the boolean values of applying the mapping function to each request!)</p>
<h2>Response Macros</h2>
<p>In contract to request criteria macros, response macros are very straightforward.</p>
<pre class="brush: java; ">

(defmacro response
  &quot;Specifies a response handler&quot;
  [handler]
  `(fn [req#] (~handler req#)))

(defmacro text
  &quot;Specifies a text response handler&quot;
  [text]
  `(text-handler ~text))

(defmacro xml-file
  &quot;Specifies a xml file handler&quot;
  [file]
  `(xml-handler ~file))
</pre>
<p><code>text-handler</code> and <code>xml-handler</code> are functions that just wrap the HTTP request with the appropriate headers, set Content-Type, set an appropriate status, etc.</p>
<h2>The Routes Macro</h2>
<pre class="brush: java; ">

(defn route-handler [req]
  (matching-uri-handler
   (list default-route-handler)
   req))

(defmacro routes
  &quot;A routes is a collection of route handlers&quot;
  [&amp; routes]
  `(defn route-handler [req#]
     (matching-uri-handler (list ~@routes) req#)))
</pre>
<p>Wait, what&#8217;s going on here?  The routes macro is defining a name, and not a generic name &#8212; a very specific name, <code>route-handler</code>, that already has a definition.</p>
<p>The reason we define <code>route-handler</code> is so that the interpreter knows it is a valid symbol.  The <code>routes</code> macro then redefines that symbol to be that of our server specification.  This allows the web server to use the route-handler as the function from requests to responses.</p>
<p>Loading the DSL has a trick to it because of how Clojure namespaces interact:</p>
<pre class="brush: java; ">

(defn load-restmock-config [file]
  (do
    (binding [*ns* (find-ns &#039;restmock.dsl)]
      (load-file file))))
</pre>
<p>Clojure doesn&#8217;t let macros from one namespace define symbols in another.  Therefore, in order to use our <code>route-handler</code> trick, we need to, when we load the DSL as a config file, locally bind the namespace to be the one that <code>route-handler</code> is defined in.  This is a little technical but not too ugly.</p>
<h1>Conclusion</h1>
<p>This is the same configuration, but it is more flexible.  Shared criteria can be defined once outside of the <code>routes</code> declarator and used within the specification.  You can write stateful interactions and criterias (more on this coming later!).  The good things about the XML configuration approach are still around: structured configuration that is external to the application.</p>
<p>Macros are an advanced feature of Lisp-like languages, but it is worth taking the time to wade through some more obscure syntax in order to understand when they are the correct solution to a problem.</p>
<h1>Notes</h1>
<p>[1] And yes, sometimes that configuration is in XML.<br />
[2] Sinatra (Ruby), Tornado (Python), Dancer (Perl), Ring (Clojure)<br />
[3] https://github.com/technomancy/leiningen</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=278</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Mutually Recursive Modules in OCaml (and why you might care)</title>
		<link>http://www.davehking.com/wordpress/?p=256</link>
		<comments>http://www.davehking.com/wordpress/?p=256#comments</comments>
		<pubDate>Mon, 23 May 2011 23:40:48 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=256</guid>
		<description><![CDATA[I keep looking for a new OCaml project. It hits a lot of sweet spots that are not matched by other languages: idiomatic functional programming, static types, powerful compiler, syntax extensions, and the language&#8217;s mindset allows for stateful solutions to &#8230; <a href="http://www.davehking.com/wordpress/?p=256">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I keep looking for a new OCaml project.  It hits a lot of sweet spots that are not matched by other languages: idiomatic functional programming, static types, powerful compiler, <a href="http://caml.inria.fr/pub/old_caml_site/camlp4/index.html">syntax extensions</a>, and the language&#8217;s mindset allows for stateful solutions to problems when these are the most natural.</p>
<p>Throughout this post I will use the running example of evaluating an abstract syntax tree for an imperative language.  Once a file has been lexed and parsed, the structure that you are left with is an <i>abstract syntax tree</i>, an internal data structure that encompasses what your program semantically means.</p>
<p>Evaluating an imperative language like JavaScript, Java, C, C++, etc involves separating out:</p>
<ul>
<li><i>expressions</i> that evaluate to a value: <code>1 + 1</code>, <code>ptr-&gt;field</code>.</li>
<li><i>statements</i> that change state or transfer control: <code>a = 1</code>, <code>if (!ptr) { log_error(); }</code>.</li>
</ul>
<p>Statements contain expressions: right-hand-side of the assignment <code>a = 1</code> is a integer literal.</p>
<p>JavaScript contains first class functions:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> a <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span> <span style="color: #009900;">&#40;</span>i<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// anonymous function</span>
    <span style="color: #000066; font-weight: bold;">return</span> i <span style="color: #339933;">*</span> <span style="color: #CC0000;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The enclosing <code>function</code> is an expression (a value that can be assigned and passed as an argument to another function).  The body of a function is a set of statements.  Therefore to evaluate expressions, we must evaluate statements &#8212; and to evaluate statements, we must evaluate expressions.  </p>
<p>This creates a mututal dependency between the two concepts.  Languages handle mutual recursion differently &#8212; generally the more static checking/code generation that is done, the more annoying a concept this is to solve.</p>
<ul>
<li>C and C++ require forward definitions of functions</li>
<li>It just works in Java as long as the two mutually recursive functions are part of the same compilation unit</li>
<li>Ruby, Python, and JavaScript don&#8217;t care because they don&#8217;t check your code for undefined symbols before executing</li>
</ul>
<p>Functional languages treat functions as values, and so in most languages, if two functions depend on each other they must be defined together.  This is not always the case, but it is the case for the two main statically typed functional languages, OCaml and Haskell.</p>
<p>I believe that most of the time static checking is the right thing and so when we hit these kind of obstacles we should try our best to write code in the correct fashion.</p>
<h3>Take 1: Mutually Recursive Functions</h3>
<p>A standard approach to dealing with mutually recursive concepts is to write a mutually recursive functions.  Evaluation is then a series of functions:</p>
<ul>
<li><code>val evaluate_expr : state -> expression -> value * state</code></li>
<li><code>val evaluate_stmt : state -> statement -> state</code></li>
</ul>

<div class="wp_syntax"><div class="code"><pre class="ocaml" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">let</span> <span style="color: #06c; font-weight: bold;">rec</span> evaluate_expr st expr <span style="color: #a52a2a;">=</span> 
  <span style="color: #06c; font-weight: bold;">match</span> expr <span style="color: #06c; font-weight: bold;">with</span>
   <span style="color: #a52a2a;">|</span> ExpFn <span style="color: #a52a2a;">&#40;</span>args,body<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> as_value expr
   <span style="color: #a52a2a;">|</span> ExpFnCall <span style="color: #a52a2a;">&#40;</span>rator,rands<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> 
         <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #a52a2a;">&#40;</span>ExpFn <span style="color: #a52a2a;">&#40;</span>args,body<span style="color: #a52a2a;">&#41;</span>, st<span style="color: #a52a2a;">'</span><span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">=</span> evaluate_expr st rator <span style="color: #06c; font-weight: bold;">and</span>
             evalled_rands <span style="color: #a52a2a;">=</span> <span style="color: #06c; font-weight: bold;">List</span><span style="color: #a52a2a;">.</span>map evaluate_expr st<span style="color: #a52a2a;">'</span> rands <span style="color: #06c; font-weight: bold;">in</span>
             evaluate_stmt <span style="color: #a52a2a;">&#40;</span>subst body evalled_rands args<span style="color: #a52a2a;">&#41;</span> st<span style="color: #a52a2a;">'</span>
   <span style="color: #a52a2a;">|</span> <span style="color: #5d478b; font-style: italic;">(* other stuff here *)</span>
<span style="color: #06c; font-weight: bold;">and</span> evaluate_stmt st stmt  <span style="color: #a52a2a;">=</span>
  <span style="color: #06c; font-weight: bold;">match</span> stmt <span style="color: #06c; font-weight: bold;">with</span> 
   <span style="color: #a52a2a;">|</span> StmtSeq <span style="color: #a52a2a;">&#40;</span>s1,s2<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> evaluate_stmt <span style="color: #a52a2a;">&#40;</span>evaluate_stmt s1<span style="color: #a52a2a;">&#41;</span> s2
   <span style="color: #a52a2a;">|</span> StmtVarDecl <span style="color: #a52a2a;">&#40;</span>var,<span style="color: #06c; font-weight: bold;">exp</span><span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> 
           <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #a52a2a;">&#40;</span><span style="color: #06c; font-weight: bold;">val</span>,st<span style="color: #a52a2a;">'</span><span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">=</span> evaluate_expr <span style="color: #06c; font-weight: bold;">exp</span> st <span style="color: #06c; font-weight: bold;">in</span>
               update st<span style="color: #a52a2a;">'</span> var <span style="color: #06c; font-weight: bold;">val</span> 
    <span style="color: #5d478b; font-style: italic;">(* more statement types etc *)</span></pre></div></div>

<p>Most of the time when I have written an interpreter in OCaml this has been the pattern that I&#8217;ve used.  It is straightforward and good for small language specifications.</p>
<p>However, as the language you are interpreting gets bigger, you have more problems.  Because of the recursive nature of the above setup, all of the parsing functions must be declared in the same compilation unit.  With 10-15 different types of expressions and 20 types of statements &#8212; not a ridiculous setup in most modern languages &#8212; your logic is very tied together and you will end up with some very large files.</p>
<p>Large files are bad and need to be avoided.  We need to constantly be asking ourselves: why are these different pieces of logic in the same file/class/module?</p>
<h3>Take 2: Mutually Recursive Modules</h3>
<p>In a functional programming language the main unit of abstraction is a mathematical function from inputs to outputs.  (Contrast this with other languages like Java/C# where the main unit of abstraction is an object &#8212; or C, where the language enforces hardly any units of abstraction at all.)  </p>
<p>Modules group functions together and allow for information hiding.  Here&#8217;s an example signature for our expression and statement evaluators:</p>

<div class="wp_syntax"><div class="code"><pre class="ocaml" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">module</span> <span style="color: #06c; font-weight: bold;">type</span> Expr <span style="color: #a52a2a;">=</span> 
<span style="color: #06c; font-weight: bold;">sig</span>
   <span style="color: #06c; font-weight: bold;">val</span> evaluate_expr <span style="color: #a52a2a;">:</span> state <span style="color: #a52a2a;">-&gt;</span> expression <span style="color: #a52a2a;">-&gt;</span> value <span style="color: #a52a2a;">*</span> state
<span style="color: #06c; font-weight: bold;">end</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">module</span> <span style="color: #06c; font-weight: bold;">type</span> Stmt <span style="color: #a52a2a;">=</span>
<span style="color: #06c; font-weight: bold;">sig</span>
   <span style="color: #06c; font-weight: bold;">val</span> evaluate_stmt <span style="color: #a52a2a;">:</span> state <span style="color: #a52a2a;">-&gt;</span> statement <span style="color: #a52a2a;">-&gt;</span> state
<span style="color: #06c; font-weight: bold;">end</span></pre></div></div>

<p>When modules connect with each other, the Statement evaluation module can deal with the Expression evaluate module only through a signature, rather than requiring it to know precisely which function is being invoked.</p>
<p>Our above code thus looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="ocaml" style="font-family:monospace;"><span style="color: #06c; font-weight: bold;">module</span> ExprEvaluator <span style="color: #a52a2a;">:</span> Expr <span style="color: #a52a2a;">&#40;</span>S<span style="color: #a52a2a;">:</span>Stmt<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">=</span>
<span style="color: #06c; font-weight: bold;">struct</span>
  <span style="color: #06c; font-weight: bold;">let</span> evaluate_expr st expr <span style="color: #a52a2a;">=</span> 
    <span style="color: #06c; font-weight: bold;">match</span> expr <span style="color: #06c; font-weight: bold;">with</span>
     <span style="color: #a52a2a;">|</span> ExpFn <span style="color: #a52a2a;">&#40;</span>args,body<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> as_value expr
     <span style="color: #a52a2a;">|</span> ExpFnCall <span style="color: #a52a2a;">&#40;</span>rator,rands<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> 
         <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #a52a2a;">&#40;</span>ExpFn <span style="color: #a52a2a;">&#40;</span>args,body<span style="color: #a52a2a;">&#41;</span>, st<span style="color: #a52a2a;">'</span><span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">=</span> evaluate_expr st rator <span style="color: #06c; font-weight: bold;">and</span>
             evalled_rands <span style="color: #a52a2a;">=</span> <span style="color: #06c; font-weight: bold;">List</span><span style="color: #a52a2a;">.</span>map evaluate_expr st<span style="color: #a52a2a;">'</span> rands <span style="color: #06c; font-weight: bold;">in</span>
             S<span style="color: #a52a2a;">.</span>evaluate_stmt <span style="color: #a52a2a;">&#40;</span>subst body evalled_rands args<span style="color: #a52a2a;">&#41;</span> st<span style="color: #a52a2a;">'</span>
     <span style="color: #a52a2a;">|</span> <span style="color: #5d478b; font-style: italic;">(* other stuff here *)</span>
<span style="color: #06c; font-weight: bold;">end</span>
&nbsp;
<span style="color: #06c; font-weight: bold;">module</span> StmtEvaluator <span style="color: #a52a2a;">:</span> Stmt <span style="color: #a52a2a;">&#40;</span>E<span style="color: #a52a2a;">:</span>Expr<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">=</span>
<span style="color: #06c; font-weight: bold;">struct</span> 
  <span style="color: #06c; font-weight: bold;">let</span> evaluate_stmt st stmt  <span style="color: #a52a2a;">=</span>
    <span style="color: #06c; font-weight: bold;">match</span> stmt <span style="color: #06c; font-weight: bold;">with</span> 
     <span style="color: #a52a2a;">|</span> StmtSeq <span style="color: #a52a2a;">&#40;</span>s1,s2<span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> evaluate_stmt <span style="color: #a52a2a;">&#40;</span>evaluate_stmt s1<span style="color: #a52a2a;">&#41;</span> s2
     <span style="color: #a52a2a;">|</span> StmtVarDecl <span style="color: #a52a2a;">&#40;</span>var,<span style="color: #06c; font-weight: bold;">exp</span><span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">-&gt;</span> 
           <span style="color: #06c; font-weight: bold;">let</span> <span style="color: #a52a2a;">&#40;</span><span style="color: #06c; font-weight: bold;">val</span>,st<span style="color: #a52a2a;">'</span><span style="color: #a52a2a;">&#41;</span> <span style="color: #a52a2a;">=</span> E<span style="color: #a52a2a;">.</span>evaluate_expr <span style="color: #06c; font-weight: bold;">exp</span> st <span style="color: #06c; font-weight: bold;">in</span>
               update st<span style="color: #a52a2a;">'</span> var <span style="color: #06c; font-weight: bold;">val</span> 
      <span style="color: #5d478b; font-style: italic;">(* more statement types etc *)</span>
<span style="color: #06c; font-weight: bold;">end</span>
&nbsp;
<span style="color: #5d478b; font-style: italic;">(* instantiate modules *)</span>
<span style="color: #06c; font-weight: bold;">module</span> <span style="color: #06c; font-weight: bold;">rec</span> StmtEvaluatorImpl <span style="color: #a52a2a;">=</span> StmtEvaluator<span style="color: #a52a2a;">&#40;</span>ExprEvaluatorImpl<span style="color: #a52a2a;">&#41;</span>
<span style="color: #06c; font-weight: bold;">and</span> ExprEvaluatorImpl <span style="color: #a52a2a;">=</span> ExprEvaluator<span style="color: #a52a2a;">&#40;</span>StmtEvaluatorImpl<span style="color: #a52a2a;">&#41;</span></pre></div></div>

<p>Here <code>ExprEvaluator</code> and <code>StmtEvaluator</code> are <i>functors</i>: a term&#8217;s more esoteric than it actually is.  A functor is simply a module (group of functions) that talks to a signature (a module interface).  It&#8217;s like if you had to parameterize your Java class with the interfaces it used to make an interface Impl.</p>
<p>First set up your modules with the signatures that they talk to, and then parameterize your modules via applying the functors &#8212; similar to dependency injection through <a href="http://www.springsource.org/">Spring</a> in Java or Python.</p>
<p>The recursive module syntax above binds the instantiations to each other, allowing us to completely separate the expression evaluation logic from the statement evaluation logic.  This is a feature since <a href="http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#toc75">OCaml 3.07</a>.  There is an equivalent setup in <a href="http://www.haskell.org/haskellwiki/Mutually_recursive_modules">Haskell</a>.</p>
<h3>Conclusion</h3>
<p>I think that functional languages are very good at selling the basic problems that they solve: many operations that we end up doing are more easily expressed as list operations, monads, lazy computation.  However, as they get bigger some of these more advanced language features (modules, mutual recursion) pop up and it is important to embrace and understand these concepts just as much as &#8216;simple&#8217; language concepts like first class functions.</p>
<p>Recursive modules may not be for every problem, but there are a lot of places where they are the right way to separate out dependencies between different abstract concepts.  We should use abstraction and information hiding in functional languages as much as we stick to abstraction and information hiding in object oriented languages.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=256</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Programming Sins</title>
		<link>http://www.davehking.com/wordpress/?p=226</link>
		<comments>http://www.davehking.com/wordpress/?p=226#comments</comments>
		<pubDate>Wed, 27 Apr 2011 02:06:40 +0000</pubDate>
		<dc:creator>dave</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.davehking.com/wordpress/?p=226</guid>
		<description><![CDATA[Often in many writings on the internet, you see the notion that all we need to do to teach computer science is to follow some awesome true method. Sometimes (often) this is C, sometimes this is some wonderful platonic world &#8230; <a href="http://www.davehking.com/wordpress/?p=226">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Often in many writings on the internet, you see the notion that all we need to do to teach computer science is to follow some awesome true method.  Sometimes (often) this is <a href="http://www.reddit.com/r/programming/comments/gxkus/cruelty_redefined_undergraduates_vs_c_on_linux/">C</a>, sometimes this is some wonderful platonic world of <a href="http://existentialtype.wordpress.com/2011/03/16/what-is-a-functional-language/">functional programming</a>.</p>
<p>I firmly believe that in order to be a good programmer you need to have been a really awful programmer first.  However, you need to be a special kind of awful programmer:</p>
<ul>
<li>don&#8217;t listen to anyone</li>
<li>don&#8217;t try to figure out why something was done the first time</li>
<li>don&#8217;t write any tests</li>
<li>don&#8217;t ever clean anything up, ever (putting <code>// TODO: refactor</code> comments everywhere gives extra demerits)</li>
<li>just get it working and then ship it</li>
</ul>
<p>Once you have done everything wrong, then the real learning can begin.  This is where the benefits of a classical computer science education stand out: you have learned essentially the full stack of the computer, the whys and traceoffs of each level &#8212; at least, in theory (don&#8217;t ask me to calculate how a cache lookup happens in an M-bit N-size L2 cache).</p>
<p>I&#8217;ve written a lot of code that I&#8217;m not proud of that got me to where I am today.  Luckily my thesis code is a special brand of awful that makes it an eternal spring of crappiness to revisit over and over again.</p>
<p>If I was to be punished for my programming sins, the list of offenses would definitely include:</p>
<p><i>(Not a comprehensive list)</i></p>
<h2>Way too many data structures</h2>
<div id="gist-943547" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">Node</span><span class="o">&gt;</span> <span class="n">variableToNodeMap</span><span class="o">;</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="kd">protected</span> <span class="n">MultiMap</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">JLiftVarLabel</span><span class="o">&gt;</span> <span class="n">directVariableAffectMap</span><span class="o">;</span></div><div class='line' id='LC4'><span class="kd">protected</span> <span class="n">MultiMap</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">JLiftVarLabel</span><span class="o">&gt;</span> <span class="n">directVariableAffectingMap</span><span class="o">;</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="kd">protected</span> <span class="n">MultiMap</span><span class="o">&lt;</span><span class="n">Node</span><span class="o">,</span> <span class="n">Label</span><span class="o">&gt;</span> <span class="n">specialSinks</span><span class="o">;</span></div><div class='line' id='LC7'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">Node</span><span class="o">,</span> <span class="n">JLiftVarLabel</span><span class="o">&gt;</span> <span class="n">nodeToVariableMap</span><span class="o">;</span></div><div class='line' id='LC8'><br/></div><div class='line' id='LC9'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">Collection</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">&gt;&gt;</span> <span class="n">cacheVarLabelAffectMap</span><span class="o">;</span></div><div class='line' id='LC10'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">Collection</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">&gt;&gt;</span> <span class="n">cacheVarLabelAffectingMap</span><span class="o">;</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">Node</span><span class="o">,</span> <span class="n">Collection</span><span class="o">&lt;</span><span class="n">Node</span><span class="o">&gt;&gt;</span> <span class="n">cacheNodeAffectMap</span><span class="o">;</span></div><div class='line' id='LC13'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">Node</span><span class="o">,</span> <span class="n">Collection</span><span class="o">&lt;</span><span class="n">Node</span><span class="o">&gt;&gt;</span> <span class="n">cacheNodeAffectingMap</span><span class="o">;</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'><span class="kd">protected</span> <span class="n">DFSGraph</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">&gt;</span> <span class="n">varGraph</span><span class="o">;</span></div><div class='line' id='LC16'><span class="kd">protected</span> <span class="n">DFSGraph</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">&gt;</span> <span class="n">mirrorVarGraph</span><span class="o">;</span></div><div class='line' id='LC17'><span class="kd">protected</span> <span class="n">CacheCallBack</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">&gt;</span> <span class="n">callBackObject</span><span class="o">;</span></div><div class='line' id='LC18'><br/></div><div class='line' id='LC19'><span class="kd">protected</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">Label</span><span class="o">&gt;</span> <span class="n">lvarMap</span><span class="o">;</span></div><div class='line' id='LC20'><br/></div><div class='line' id='LC21'><span class="kd">private</span> <span class="kd">final</span> <span class="n">Map</span><span class="o">&lt;</span><span class="n">JLiftVarLabel</span><span class="o">,</span> <span class="n">JLiftLabelConstraint</span><span class="o">&gt;</span> <span class="n">variableToConstraintMap</span><span class="o">;</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/943547/10e14c302459b5f344e147568f537ea77bd28fcf/TooManyMembers.java" style="float:right;">view raw</a>
            <a href="https://gist.github.com/943547#file_too_many_members.java" style="float:right;margin-right:10px;color:#666">TooManyMembers.java</a>
            <a href="https://gist.github.com/943547">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I&#8217;m sure there&#8217;s some reason that the class needed 14 private members, but I can&#8217;t remember it any more!</p>
<h2>Lots of commented out code</h2>
<div id="gist-943551" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="cm">/*</span></div><div class='line' id='LC2'><span class="cm">private boolean isSinkConstraint(LabelConstraint c) {</span></div><div class='line' id='LC3'><span class="cm">    return containsPairLabel(getSinkLabelForConstraint(c));</span></div><div class='line' id='LC4'><span class="cm">}</span></div><div class='line' id='LC5'><br/></div><div class='line' id='LC6'><span class="cm">private boolean isSourceConstraint(LabelConstraint c) {</span></div><div class='line' id='LC7'><span class="cm">    return containsPairLabel(getSourceLabelForConstraint(c));</span></div><div class='line' id='LC8'><span class="cm">}</span></div><div class='line' id='LC9'><br/></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'><span class="cm">private Label getSinkLabelForConstraint(LabelConstraint c) {</span></div><div class='line' id='LC12'><span class="cm">    // tau &lt;= c &lt;&lt;-  c is the sink</span></div><div class='line' id='LC13'><span class="cm">    // v == tau &lt;&lt;-  tau is the sink</span></div><div class='line' id='LC14'><span class="cm">    if (c.kind() == LabelConstraint.LEQ || c.kind() == LabelConstraint.EQUAL)</span></div><div class='line' id='LC15'><span class="cm">        return c.rhs();</span></div><div class='line' id='LC16'><span class="cm">    // v ==_{def} tau ||--&gt; tau &lt;= v &lt;&lt;-- v is the sink (a define should not be a sink)</span></div><div class='line' id='LC17'><span class="cm">    else if (c.kind() == LabelConstraint.DEFINE)</span></div><div class='line' id='LC18'><span class="cm">        return c.lhs();</span></div><div class='line' id='LC19'><br/></div><div class='line' id='LC20'><span class="cm">    return null;</span></div><div class='line' id='LC21'><span class="cm">}</span></div><div class='line' id='LC22'><br/></div><div class='line' id='LC23'><span class="cm">private Label getSourceLabelForConstraint(LabelConstraint c) {</span></div><div class='line' id='LC24'><span class="cm">    // v == tau &lt;&lt;-  tau is the source</span></div><div class='line' id='LC25'><span class="cm">    if (c.kind() == LabelConstraint.EQUAL)  {</span></div><div class='line' id='LC26'><span class="cm">        return c.rhs();</span></div><div class='line' id='LC27'><span class="cm">    }</span></div><div class='line' id='LC28'><span class="cm">    // tau &lt;= v &lt;&lt;-  tau is the source</span></div><div class='line' id='LC29'><span class="cm">    if (c.kind() == LabelConstraint.LEQ)</span></div><div class='line' id='LC30'><span class="cm">        return c.lhs();</span></div><div class='line' id='LC31'><span class="cm">    // v ==_{def} tau ||--&gt; tau &lt;= v &lt;&lt;-- tau is the source</span></div><div class='line' id='LC32'><span class="cm">    if (c.kind() == LabelConstraint.DEFINE)</span></div><div class='line' id='LC33'><span class="cm">        return c.rhs();</span></div><div class='line' id='LC34'><br/></div><div class='line' id='LC35'><span class="cm">    return null;</span></div><div class='line' id='LC36'><span class="cm">}</span></div><div class='line' id='LC37'><br/></div><div class='line' id='LC38'><span class="cm">private boolean foundPairLabel;</span></div><div class='line' id='LC39'><br/></div><div class='line' id='LC40'><span class="cm">private boolean containsPairLabel(Label lhs) {</span></div><div class='line' id='LC41'><span class="cm">    foundPairLabel = false;</span></div><div class='line' id='LC42'><br/></div><div class='line' id='LC43'><span class="cm">    LabelSubstitution ls = new LabelSubstitution() {</span></div><div class='line' id='LC44'><span class="cm">            @Override</span></div><div class='line' id='LC45'><span class="cm">                public Label substLabel(Label L) throws SemanticException {</span></div><div class='line' id='LC46'><span class="cm">                if (L instanceof PairLabel) {</span></div><div class='line' id='LC47'><span class="cm">                    foundPairLabel = true;</span></div><div class='line' id='LC48'><span class="cm">                }</span></div><div class='line' id='LC49'><span class="cm">                return L;</span></div><div class='line' id='LC50'><span class="cm">            }</span></div><div class='line' id='LC51'><span class="cm">        };</span></div><div class='line' id='LC52'><br/></div><div class='line' id='LC53'><span class="cm">    try {</span></div><div class='line' id='LC54'><span class="cm">        lhs.subst(ls);</span></div><div class='line' id='LC55'><span class="cm">    } catch (SemanticException e) {</span></div><div class='line' id='LC56'><span class="cm">        throw new InternalCompilerError(e);</span></div><div class='line' id='LC57'><span class="cm">    }</span></div><div class='line' id='LC58'><br/></div><div class='line' id='LC59'><span class="cm">    return foundPairLabel;</span></div><div class='line' id='LC60'><span class="cm">}</span></div><div class='line' id='LC61'><span class="cm">*/</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/943551/844fe333b3eac2cae20bb937e42b80d925b51d1e/TooManyComments.java" style="float:right;">view raw</a>
            <a href="https://gist.github.com/943551#file_too_many_comments.java" style="float:right;margin-right:10px;color:#666">TooManyComments.java</a>
            <a href="https://gist.github.com/943551">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>But I might need it later! (and I probably did at some point, commenting and uncommenting things until they worked again)</p>
<h2>What the hell are you trying to do?</h2>
<div id="gist-943558" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">public</span> <span class="nf">JLiftCallHelper</span><span class="o">(</span><span class="n">Label</span> <span class="n">receiverLabel</span><span class="o">,</span></div><div class='line' id='LC2'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Receiver</span> <span class="n">receiver</span><span class="o">,</span></div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ReferenceType</span> <span class="n">calleeContainer</span><span class="o">,</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">JifProcedureInstance</span> <span class="n">pi</span><span class="o">,</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">List</span> <span class="n">actualArgs</span><span class="o">,</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">Position</span> <span class="n">position</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">super</span><span class="o">(</span><span class="n">receiverLabel</span><span class="o">,</span> <span class="n">receiver</span><span class="o">,</span> <span class="n">calleeContainer</span><span class="o">,</span> <span class="n">pi</span><span class="o">,</span> <span class="n">actualArgs</span><span class="o">,</span> <span class="n">position</span><span class="o">);</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">receiverLabel</span> <span class="o">=</span> <span class="n">receiverLabel</span><span class="o">;</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">calleeContainer</span> <span class="o">=</span> <span class="n">calleeContainer</span><span class="o">;</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="o">(</span><span class="n">receiver</span> <span class="k">instanceof</span> <span class="n">Expr</span><span class="o">)</span> <span class="o">{</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">receiverExpr</span> <span class="o">=</span> <span class="o">(</span><span class="n">Expr</span><span class="o">)</span><span class="n">receiver</span><span class="o">;</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">else</span> <span class="o">{</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">receiverExpr</span> <span class="o">=</span> <span class="kc">null</span><span class="o">;</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">actualArgs</span> <span class="o">=</span> <span class="k">new</span> <span class="n">ArrayList</span><span class="o">(</span><span class="n">actualArgs</span><span class="o">);</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">pi</span> <span class="o">=</span> <span class="n">pi</span><span class="o">;</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">position</span> <span class="o">=</span> <span class="n">position</span><span class="o">;</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">this</span><span class="o">.</span><span class="na">callChecked</span> <span class="o">=</span> <span class="kc">false</span><span class="o">;</span></div><div class='line' id='LC20'><br/></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">if</span> <span class="o">(</span><span class="n">pi</span><span class="o">.</span><span class="na">formalTypes</span><span class="o">().</span><span class="na">size</span><span class="o">()</span> <span class="o">!=</span> <span class="n">actualArgs</span><span class="o">.</span><span class="na">size</span><span class="o">())</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">throw</span> <span class="k">new</span> <span class="nf">InternalCompilerError</span><span class="o">(</span><span class="s">&quot;Wrong number of args.&quot;</span><span class="o">);</span></div><div class='line' id='LC23'><span class="o">}</span></div><div class='line' id='LC24'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/943558/96fc4b89f035a0e9bbb4ce1393b580581fc45cd1/ConstructorWtf.java" style="float:right;">view raw</a>
            <a href="https://gist.github.com/943558#file_constructor_wtf.java" style="float:right;margin-right:10px;color:#666">ConstructorWtf.java</a>
            <a href="https://gist.github.com/943558">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>Demerits:</p>
<ul>
<li>Throwing an exception from a constructor</li>
<li>Incomprehensible choice of constructor arguments</li>
<li><code>instanceof</code> check</li>
<li>setting something to <code>null</code> if the <code>instanceof</code> check fails
<li>boolean flag initialized to <code>false</code> on object creation (explicit state!  agh!)
<li>recasting a <code>List</code> into an <code>ArrayList</code> (I guess I wanted to use this as a vector, despite it starting with no structure?)
<li>raw Java pre-1.5 types (<code>ArrayList</code> and <code>List</code> instead of <code>ArrayList&lt;&gt;</code> and <code>List&lt;&gt;</code>)</li>
</ul>
<p>Really this is awful code and it&#8217;s doing less than any of the other snippets here (including the commented block).</p>
<p>At least the method signature problems were inherited from the superclass.</p>
<h2>Copy and Pasted Code</h2>
<div id="gist-943564" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">JLiftConstructorDecl_c</span> <span class="kd">extends</span> <span class="n">JifConstructorDecl_c</span> <span class="o">{</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'>	<span class="nd">@Override</span></div><div class='line' id='LC4'>	<span class="kd">public</span> <span class="n">Node</span> <span class="nf">typeCheck</span><span class="o">(</span><span class="n">TypeChecker</span> <span class="n">tc</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">SemanticException</span> <span class="o">{</span></div><div class='line' id='LC5'>		<span class="k">if</span> <span class="o">(!((</span><span class="n">JLiftTypeSystem</span><span class="o">)</span> <span class="n">tc</span><span class="o">.</span><span class="na">typeSystem</span><span class="o">()).</span><span class="na">allowSmallLeaks</span><span class="o">())</span></div><div class='line' id='LC6'>			<span class="k">return</span> <span class="kd">super</span><span class="o">.</span><span class="na">typeCheck</span><span class="o">(</span><span class="n">tc</span><span class="o">);</span></div><div class='line' id='LC7'>		<span class="k">else</span> <span class="o">{</span></div><div class='line' id='LC8'>			<span class="c1">// HACK: copy/pasted from ConstructorDecl_c</span></div><div class='line' id='LC9'>			<span class="n">Context</span> <span class="n">c</span> <span class="o">=</span> <span class="n">tc</span><span class="o">.</span><span class="na">context</span><span class="o">();</span></div><div class='line' id='LC10'>			<span class="n">TypeSystem</span> <span class="n">ts</span> <span class="o">=</span> <span class="n">tc</span><span class="o">.</span><span class="na">typeSystem</span><span class="o">();</span></div><div class='line' id='LC11'><br/></div><div class='line' id='LC12'>			<span class="n">ClassType</span> <span class="n">ct</span> <span class="o">=</span> <span class="n">c</span><span class="o">.</span><span class="na">currentClass</span><span class="o">();</span></div><div class='line' id='LC13'><br/></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/943564/cf2e18ba29694fb715604bd0bb6807bd0bdbe100/CantSuperSuperInJava.java" style="float:right;">view raw</a>
            <a href="https://gist.github.com/943564#file_cant_super_super_in_java.java" style="float:right;margin-right:10px;color:#666">CantSuperSuperInJava.java</a>
            <a href="https://gist.github.com/943564">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>For this one I at least had an excuse.  C extends B extends A; all of them implement <code>foo</code>.  Sometimes we want C to call A&#8217;s <code>foo</code>, sometimes we want to call B&#8217;s <code>foo</code>.  Unfortunately, Java&#8217;s inheritance model doesn&#8217;t support that. Solution: copy and paste some code!</p>
<h2>Method that&#8217;s Way Way Way Too Long</h2>
<div id="gist-943571" class="gist">

        <div class="gist-file">
          <div class="gist-data gist-syntax">
              <div class="highlight"><pre><div class='line' id='LC1'><span class="k">let</span> <span class="n">constraint_set_to_flowgraph</span> <span class="n">cl</span> <span class="n">lattice</span> <span class="o">=</span> </div><div class='line' id='LC2'>&nbsp;&nbsp;<span class="k">match</span> <span class="n">cl</span> <span class="k">with</span> </div><div class='line' id='LC3'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|</span> <span class="bp">[]</span> <span class="o">-&gt;</span> <span class="nn">G</span><span class="p">.</span><span class="n">create</span> <span class="bp">()</span></div><div class='line' id='LC4'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">|</span> <span class="o">_</span>  <span class="o">-&gt;</span> </div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">atoms</span> <span class="o">=</span> <span class="n">timeThunk</span> <span class="o">(</span><span class="k">fun</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">atoms_in_conslist</span> <span class="n">cl</span><span class="o">)</span> <span class="o">(</span><span class="nn">SimpTimer</span><span class="p">.</span><span class="n">record_time</span> <span class="s2">&quot;get atoms in constaint list&quot;</span><span class="o">)</span> <span class="k">in</span> </div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="o">_</span> <span class="o">=</span> </div><div class='line' id='LC7'>	<span class="k">begin</span></div><div class='line' id='LC8'>	  <span class="nn">Printf</span><span class="p">.</span><span class="n">printf</span> <span class="o">(</span><span class="s2">&quot;%d atoms</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">)</span> <span class="o">(</span><span class="nn">LexpSet</span><span class="p">.</span><span class="n">cardinal</span> <span class="n">atoms</span><span class="o">);</span></div><div class='line' id='LC9'>	  <span class="n">flush</span> <span class="n">stdout</span></div><div class='line' id='LC10'>	<span class="k">end</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">in</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">g</span> <span class="o">=</span> <span class="nn">G</span><span class="p">.</span><span class="n">create</span> <span class="o">~</span><span class="n">size</span><span class="o">:(</span><span class="nn">LexpSet</span><span class="p">.</span><span class="n">cardinal</span> <span class="n">atoms</span><span class="o">)</span> <span class="bp">()</span> <span class="k">in</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">get_sub_lv_node</span> <span class="n">s</span> <span class="n">lexp</span> <span class="o">=</span></div><div class='line' id='LC14'>	<span class="k">match</span> <span class="n">lexp</span> <span class="k">with</span> </div><div class='line' id='LC15'>	  <span class="o">|</span> <span class="o">(</span><span class="nc">LVar</span> <span class="o">(</span><span class="n">lv</span><span class="o">,</span><span class="n">t</span><span class="o">))</span> <span class="o">-&gt;</span> <span class="nc">LVar</span> <span class="o">(</span><span class="n">lv</span><span class="o">,</span><span class="n">s</span> <span class="o">::</span> <span class="n">t</span><span class="o">)</span> </div><div class='line' id='LC16'>	  <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="k">raise</span> <span class="o">(</span><span class="nc">Failure</span> <span class="s2">&quot;cannot get sub lv node for non-lvar&quot;</span><span class="o">)</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">in</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">get_incoming_lv_node</span> <span class="o">=</span> <span class="n">get_sub_lv_node</span> <span class="o">`</span><span class="nc">Incoming</span> <span class="ow">and</span></div><div class='line' id='LC19'>	  <span class="n">get_outgoing_lv_node</span> <span class="o">=</span> <span class="n">get_sub_lv_node</span> <span class="o">`</span><span class="nc">Outgoing</span> <span class="k">in</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">let</span> <span class="n">get_incoming_node</span> <span class="n">a</span> <span class="o">=</span> </div><div class='line' id='LC21'>	<span class="k">match</span> <span class="n">a</span> <span class="k">with</span> </div><div class='line' id='LC22'>	  <span class="o">|</span> <span class="nc">LVar</span> <span class="o">(</span><span class="nc">ExpLVar</span> <span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">get_incoming_lv_node</span> <span class="n">a</span></div><div class='line' id='LC23'>	  <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">a</span> </div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="ow">and</span></div><div class='line' id='LC25'>	  <span class="n">get_outgoing_node</span> <span class="n">a</span> <span class="o">=</span> </div><div class='line' id='LC26'>	<span class="k">match</span> <span class="n">a</span> <span class="k">with</span> </div><div class='line' id='LC27'>	  <span class="o">|</span> <span class="nc">LVar</span> <span class="o">(</span><span class="nc">ExpLVar</span> <span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">)</span> <span class="o">-&gt;</span> <span class="n">get_outgoing_lv_node</span> <span class="n">a</span></div><div class='line' id='LC28'>	  <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">a</span></div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">in</span></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">begin</span></div><div class='line' id='LC31'>	<span class="n">timeThunk</span> </div><div class='line' id='LC32'>	  <span class="o">(</span><span class="k">fun</span> <span class="o">_</span> <span class="o">-&gt;</span></div><div class='line' id='LC33'>	    <span class="nn">LexpSet</span><span class="p">.</span><span class="n">iter</span> </div><div class='line' id='LC34'>	      <span class="o">(</span><span class="k">function</span> </div><div class='line' id='LC35'>		<span class="o">|</span> <span class="nc">LVar</span> <span class="o">(</span><span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">)</span> <span class="o">-&gt;</span> </div><div class='line' id='LC36'>		  <span class="o">(</span><span class="k">match</span> <span class="n">l</span> <span class="k">with</span> </div><div class='line' id='LC37'>		    <span class="o">|</span> <span class="nc">ExpLVar</span> <span class="n">e</span> <span class="o">-&gt;</span> </div><div class='line' id='LC38'>		      <span class="k">let</span> <span class="n">incoming_l</span> <span class="o">=</span> <span class="n">get_incoming_lv_node</span> <span class="o">(</span><span class="nc">LVar</span> <span class="o">(</span><span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">))</span> <span class="ow">and</span></div><div class='line' id='LC39'>			  <span class="n">outgoing_l</span> <span class="o">=</span> <span class="n">get_outgoing_lv_node</span> <span class="o">(</span><span class="nc">LVar</span> <span class="o">(</span><span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">))</span> <span class="k">in</span> </div><div class='line' id='LC40'>		      <span class="k">let</span> <span class="n">nodeId</span> <span class="o">=</span> <span class="n">id_for_lexp</span> <span class="n">incoming_l</span> <span class="k">in</span></div><div class='line' id='LC41'>		      <span class="k">let</span> <span class="n">incoming_tag</span> <span class="o">=</span> <span class="nn">GraphLabel</span><span class="p">.</span><span class="n">tagForNode</span> <span class="n">incoming_l</span> <span class="ow">and</span></div><div class='line' id='LC42'>			  <span class="n">outgoing_tag</span> <span class="o">=</span> <span class="nn">GraphLabel</span><span class="p">.</span><span class="n">tagForNode</span> <span class="n">outgoing_l</span> <span class="k">in</span></div><div class='line' id='LC43'>		      <span class="k">begin</span></div><div class='line' id='LC44'>				      <span class="c">(*Printf.printf (&quot;incoming: %d, outgoing: %d\n&quot;) incoming_tag outgoing_tag;*)</span></div><div class='line' id='LC45'>			<span class="n">timeThunk</span> <span class="o">(</span><span class="k">fun</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="o">(</span><span class="nn">G</span><span class="p">.</span><span class="n">add_vertex</span> <span class="n">g</span> <span class="n">incoming_tag</span><span class="o">;</span></div><div class='line' id='LC46'>					     <span class="nn">G</span><span class="p">.</span><span class="n">add_vertex</span> <span class="n">g</span> <span class="n">outgoing_tag</span><span class="o">))</span></div><div class='line' id='LC47'>			  <span class="o">(</span><span class="nn">SimpTimer</span><span class="p">.</span><span class="n">record_time</span> <span class="o">~</span><span class="n">silent</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;graph building (add_vertex)&quot;</span><span class="o">);</span></div><div class='line' id='LC48'>			<span class="k">let</span> <span class="n">edgeWeight</span> <span class="o">=</span> <span class="k">match</span> <span class="n">nodeId</span> <span class="k">with</span> </div><div class='line' id='LC49'>			  <span class="o">|</span> <span class="nc">Some</span> <span class="n">id</span> <span class="o">-&gt;</span></div><div class='line' id='LC50'>			    <span class="k">if</span> <span class="o">(</span><span class="nn">StringSet</span><span class="p">.</span><span class="n">mem</span> <span class="n">id</span> <span class="o">(!</span><span class="nn">XmlConstraintReader</span><span class="p">.</span><span class="n">nvNoDeclassify</span><span class="o">))</span> <span class="k">then</span></div><div class='line' id='LC51'>			      <span class="n">infinity_hack</span></div><div class='line' id='LC52'>			    <span class="k">else</span></div><div class='line' id='LC53'>			      <span class="o">(</span><span class="k">match</span> <span class="o">(</span><span class="n">weight_for_lexp</span> <span class="o">(</span><span class="nc">LVar</span> <span class="o">(</span><span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">)))</span> <span class="k">with</span></div><div class='line' id='LC54'>				<span class="o">|</span> <span class="nc">None</span> <span class="o">-&gt;</span> <span class="mi">1</span></div><div class='line' id='LC55'>				<span class="o">|</span> <span class="nc">Some</span> <span class="n">n</span> <span class="o">-&gt;</span> <span class="n">n</span><span class="o">)</span></div><div class='line' id='LC56'>			  <span class="o">|</span> <span class="nc">None</span> <span class="o">-&gt;</span> <span class="mi">1</span></div><div class='line' id='LC57'>			<span class="k">in</span></div><div class='line' id='LC58'>			<span class="nn">G</span><span class="p">.</span><span class="n">add_edge_e</span> <span class="n">g</span> <span class="o">(</span><span class="nn">G</span><span class="p">.</span><span class="nn">E</span><span class="p">.</span><span class="n">create</span> <span class="n">incoming_tag</span> <span class="n">edgeWeight</span> <span class="n">outgoing_tag</span><span class="o">);</span></div><div class='line' id='LC59'>					  <span class="c">(*Printf.printf(&quot;\tadded vertices to graph\n&quot;);</span></div><div class='line' id='LC60'><span class="c">					    flush stdout;*)</span> <span class="bp">()</span></div><div class='line' id='LC61'>		      <span class="k">end</span></div><div class='line' id='LC62'>		    <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> </div><div class='line' id='LC63'>		      <span class="k">let</span> <span class="n">lvar_tag</span> <span class="o">=</span> <span class="nn">GraphLabel</span><span class="p">.</span><span class="n">tagForNode</span> <span class="o">(</span><span class="nc">LVar</span> <span class="o">(</span><span class="n">l</span><span class="o">,</span><span class="n">t</span><span class="o">))</span></div><div class='line' id='LC64'>		      <span class="k">in</span></div><div class='line' id='LC65'>		      <span class="k">begin</span></div><div class='line' id='LC66'>			<span class="n">timeThunk</span> <span class="o">(</span><span class="k">fun</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="nn">G</span><span class="p">.</span><span class="n">add_vertex</span> <span class="n">g</span> <span class="n">lvar_tag</span><span class="o">)</span> <span class="o">((</span><span class="nn">SimpTimer</span><span class="p">.</span><span class="n">record_time</span> <span class="o">~</span><span class="n">silent</span><span class="o">:</span><span class="bp">true</span> <span class="s2">&quot;graph building (add_vertex)&quot;</span><span class="o">));</span></div><div class='line' id='LC67'>				      <span class="c">(*Printf.printf (&quot;added tag for %s\n&quot;) (lexp_to_string (LVar (l,t)));</span></div><div class='line' id='LC68'><span class="c">				        flush stdout;*)</span> <span class="bp">()</span></div><div class='line' id='LC69'>		      <span class="k">end</span></div><div class='line' id='LC70'>		  <span class="o">)</span></div><div class='line' id='LC71'>		<span class="o">|</span> <span class="nc">Label</span> <span class="n">n</span> <span class="o">-&gt;</span> </div><div class='line' id='LC72'>		  <span class="k">let</span> <span class="n">lab_tag</span> <span class="o">=</span> <span class="nn">GraphLabel</span><span class="p">.</span><span class="n">tagForNode</span> <span class="o">(</span><span class="nc">Label</span> <span class="n">n</span><span class="o">)</span></div><div class='line' id='LC73'>		  <span class="k">in</span></div><div class='line' id='LC74'>		  <span class="nn">G</span><span class="p">.</span><span class="n">add_vertex</span> <span class="n">g</span> <span class="n">lab_tag</span></div><div class='line' id='LC75'>		<span class="o">|</span> <span class="nc">Join</span> <span class="o">(_,_)</span> <span class="o">-&gt;</span> <span class="k">raise</span> <span class="o">(</span><span class="nc">Failure</span> <span class="s2">&quot;graph contains non-atomic node&quot;</span><span class="o">))</span></div><div class='line' id='LC76'>	      <span class="n">atoms</span><span class="o">)</span></div><div class='line' id='LC77'>	  <span class="o">(</span><span class="nn">SimpTimer</span><span class="p">.</span><span class="n">record_time</span> <span class="s2">&quot;building graph (add nodes)&quot;</span><span class="o">);</span></div><div class='line' id='LC78'>	<span class="nn">Printf</span><span class="p">.</span><span class="n">printf</span> <span class="o">(</span><span class="s2">&quot;added each atom to the graph as a node -- graph size %d nodes</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">)</span> <span class="o">(</span><span class="nn">G</span><span class="p">.</span><span class="n">nb_vertex</span> <span class="n">g</span><span class="o">);</span></div><div class='line' id='LC79'>	<span class="n">flush</span> <span class="n">stdout</span><span class="o">;</span></div><div class='line' id='LC80'>	<span class="n">timeThunk</span> </div><div class='line' id='LC81'>	  <span class="o">(</span><span class="k">fun</span> <span class="o">_</span> <span class="o">-&gt;</span> </div><div class='line' id='LC82'>	    <span class="nn">List</span><span class="p">.</span><span class="n">iter</span></div><div class='line' id='LC83'>	      <span class="o">(</span><span class="k">fun</span> <span class="o">(</span><span class="nc">Leq</span> <span class="o">(</span><span class="n">le</span><span class="o">,</span><span class="n">rhsA</span><span class="o">))</span> <span class="o">-&gt;</span></div><div class='line' id='LC84'>			  <span class="c">(* add variable connections -- note that don&#39;t care if something flows to top or from bottom! *)</span></div><div class='line' id='LC85'>		<span class="k">let</span> <span class="n">lhsAtoms</span> <span class="o">=</span> <span class="n">atoms_in_lexp</span> <span class="n">le</span> <span class="k">in</span></div><div class='line' id='LC86'>		<span class="nn">LexpSet</span><span class="p">.</span><span class="n">iter</span> </div><div class='line' id='LC87'>		  <span class="o">(</span><span class="k">fun</span> <span class="n">a</span> <span class="o">-&gt;</span></div><div class='line' id='LC88'>		    <span class="k">let</span> <span class="n">add_edge_thunk</span> <span class="o">=</span> </div><div class='line' id='LC89'>		      <span class="k">fun</span> <span class="o">_</span> <span class="o">-&gt;</span> </div><div class='line' id='LC90'>			<span class="k">let</span> <span class="n">e</span> <span class="o">=</span> <span class="nn">G</span><span class="p">.</span><span class="nn">E</span><span class="p">.</span><span class="n">create</span></div><div class='line' id='LC91'>			  <span class="o">(</span><span class="nn">GraphLabel</span><span class="p">.</span><span class="n">tagForNode</span> <span class="o">(</span><span class="n">get_outgoing_node</span> <span class="n">a</span><span class="o">))</span> </div><div class='line' id='LC92'>			  <span class="o">(</span><span class="n">infinity_hack</span><span class="o">)</span> </div><div class='line' id='LC93'>			  <span class="o">(</span><span class="nn">GraphLabel</span><span class="p">.</span><span class="n">tagForNode</span> <span class="o">(</span><span class="n">get_incoming_node</span> <span class="n">rhsA</span><span class="o">))</span></div><div class='line' id='LC94'>			<span class="k">in</span></div><div class='line' id='LC95'>				  <span class="c">(*Printf.printf (&quot;edge: (%s,%s)\n\tconstraint: %s\n&quot;) (lexp_to_string a) (lexp_to_string rhsA) (cons_to_string (Leq (le,rhsA)));*)</span></div><div class='line' id='LC96'>			<span class="nn">G</span><span class="p">.</span><span class="n">add_edge_e</span> <span class="n">g</span> <span class="n">e</span> </div><div class='line' id='LC97'>		    <span class="k">in</span></div><div class='line' id='LC98'>		    <span class="k">match</span> <span class="n">a</span> <span class="k">with</span></div><div class='line' id='LC99'>		      <span class="o">|</span> <span class="nc">Label</span> <span class="n">id</span> <span class="o">-&gt;</span> <span class="k">if</span> <span class="o">(</span><span class="nn">LatticeGraph</span><span class="p">.</span><span class="n">is_bottom</span> <span class="n">lattice</span> <span class="n">id</span><span class="o">)</span> <span class="k">then</span> <span class="bp">()</span> <span class="k">else</span> <span class="n">add_edge_thunk</span> <span class="bp">()</span></div><div class='line' id='LC100'>		      <span class="o">|</span> <span class="o">_</span> <span class="o">-&gt;</span> <span class="n">add_edge_thunk</span> <span class="bp">()</span><span class="o">)</span></div><div class='line' id='LC101'>		  <span class="n">lhsAtoms</span><span class="o">)</span></div><div class='line' id='LC102'>	      <span class="n">cl</span><span class="o">)</span></div><div class='line' id='LC103'>	  <span class="o">(</span><span class="nn">SimpTimer</span><span class="p">.</span><span class="n">record_time</span> <span class="s2">&quot;building graph (add edges)&quot;</span><span class="o">);</span></div><div class='line' id='LC104'>	<span class="nn">Printf</span><span class="p">.</span><span class="n">printf</span> <span class="o">(</span><span class="s2">&quot;added edges between each atom to the graph -- graph size %d vertices, %d edges</span><span class="se">\n</span><span class="s2">&quot;</span><span class="o">)</span> <span class="o">(</span><span class="nn">G</span><span class="p">.</span><span class="n">nb_vertex</span> <span class="n">g</span><span class="o">)</span> <span class="o">(</span><span class="nn">G</span><span class="p">.</span><span class="n">nb_edges</span> <span class="n">g</span><span class="o">);</span></div><div class='line' id='LC105'>	<span class="n">flush</span> <span class="n">stdout</span><span class="o">;</span></div><div class='line' id='LC106'>	<span class="n">g</span></div><div class='line' id='LC107'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">end</span></div></pre></div>
          </div>

          <div class="gist-meta">
            <a href="https://gist.github.com/raw/943571/dfe92fb0851f0b3b2dbba0c27e5470f5872e6764/omg-end-the-function.ml" style="float:right;">view raw</a>
            <a href="https://gist.github.com/943571#file_omg_end_the_function.ml" style="float:right;margin-right:10px;color:#666">omg-end-the-function.ml</a>
            <a href="https://gist.github.com/943571">This Gist</a> brought to you by <a href="http://github.com">GitHub</a>.
          </div>
        </div>
</div>

<p>I have no idea what this function is doing either.</p>
<h2>No Unit Tests</h2>
<p>Nothing here because I didn&#8217;t write anything!</p>
<p>(I did end up with several integration-level tests that were essentially glued-together bash scripts but that will not come to my rescue here)</p>
<h1>Being a Recovering Horrible Programmer</h1>
<p>Well, I&#8217;d like to think the moral is that nobody&#8217;s perfect and that everyone writes bad code and that if I had to do it all over again I&#8217;d be sure to fix all the sins that I&#8217;ve documented here, do it more cleanly, etc., etc., but that&#8217;s a lie.</p>
<p>I had to get stuff done and I did it.  The code wasn&#8217;t pretty but it worked well enough to generate publishable results.</p>
<p>However, all this bad code ended up being the best kind of teacher:</p>
<ul>
<li>I didn&#8217;t realize how important modules and small classes were until I had classes that spanned hundreds of lines</li>
<li>I didn&#8217;t learn how important short methods were until I had to debug a bunch of long methods</li>
<li>I didn&#8217;t learn how important regression tests were until I changed something in the morning and had to spend the afternoon restoring my compiler</li>
<li>I didn&#8217;t realize how important distinct units of computation were until I spent about a month chasing down performance problems in my OCaml code.  (These problems were determined to either be in a library or my integration with the library.  I gave up and rewrote the OCaml code in C++ in about a week.)</li>
</ul>
<p>Throughout all this I could never blame anyone except for myself.  I let the code get too big, too unwieldy, too impenetrable to change, and the programmer that I was always cleaning up after was me.</p>
<p>Lessons learned.  I regret nothing!  (except for not writing unit tests)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.davehking.com/wordpress/?feed=rss2&#038;p=226</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

