<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>A Day In The Lyf</title>
	<atom:link href="http://brandonbyars.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://brandonbyars.com</link>
	<description>...the lyf so short, the craft so longe to lerne</description>
	<lastBuildDate>Mon, 12 Dec 2011 00:52:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='brandonbyars.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>A Day In The Lyf</title>
		<link>http://brandonbyars.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://brandonbyars.com/osd.xml" title="A Day In The Lyf" />
	<atom:link rel='hub' href='http://brandonbyars.com/?pushpress=hub'/>
		<item>
		<title>Introducing httpmock</title>
		<link>http://brandonbyars.com/2011/05/30/introducing-httpmock/</link>
		<comments>http://brandonbyars.com/2011/05/30/introducing-httpmock/#comments</comments>
		<pubDate>Tue, 31 May 2011 03:48:11 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[node.js]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://brandonbyars.com/?p=271</guid>
		<description><![CDATA[node.js is simply too cool to ignore. I find the trick to learning any new cool framework is to find a new cool project to write, and use the framework to write it in. httpmock is my cool new project. I tend to work in large&#8217;ish programs of work with lots of teams. One recurring [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=271&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p><a href="http://nodejs.org/">node.js</a> is simply too cool to ignore.  I find the trick to learning any new cool framework is to find a new cool project to write, and use the framework to write it in.  <a href="https://github.com/bbyars/httpmock">httpmock</a> is my cool new project.</p>
<p>I tend to work in large&#8217;ish programs of work with lots of teams.  One recurring pain point in such an environment is dealing with other teams.  Sure, <em>your</em> code is fine, but what happens if you have to integrate with <em>their</em> code?  These days, that tends to be through web services, and it&#8217;s never pretty.  Your team writes integration tests, verify they work, and commit the changes.  Three days later, for no apparent reason, your build goes red.  It turns out that <em>other</em> team broke their code again.</p>
<p>httpmock is a network server stubbing tool.  I say &#8220;network,&#8221; primarily because I&#8217;ve got my dreaming hat on.  At the moment, it&#8217;s an HTTP stubbing tool, but I&#8217;d like to add other protocols, especially SMTP.  httpmock exposes a RESTful API that lets you spin up HTTP servers that you can control, and that helpully record how they were used so you can make useful test assertions.  In other words, httmock expects you to execute your code full-stack, including making a full TCP handshakes across the network. httpmock just lets you control both hands involved in the handshake, and it does so in a way transparent to your code; you just have to point your configuration to the stub servers httpmock creates.  I find this quite useful for functional testing.</p>
<p>Don&#8217;t get me wrong.  Integration tests are important, and you should still have a set of tests that exercise the actual system, but expect some fragility in those tests.  If they break, it doesn&#8217;t necessarily mean <em>you</em> broke them.  Therefore, they should be in a separate build, one that may not have the same &#8220;stop the line&#8221; implications when it goes red. httpmock should not be used only for builds that are entirely in control of your team..</p>
<p>When I say that httpmock exposes a RESTful API, I mean it&#8217;s a truly RESTful API.  There&#8217;s only one published URL, and hypermedia drives the interaction from there.  This makes it easy to evolve the server while maintaining a stable client-side API.  At the moment, I have only a Java binding, but I have intentions for more (and I&#8217;d love some help on the issue!).  The idea of the language bindings is to present to the developer a friendly API that approximates normal unit-testing mocking frameworks without having to write your tests in a language different from your production stack.</p>
<h3>Examples</h3>
<pre><code class="java">
@Test
public void showVerificationAPI()
{
    StubServer stub = ControlServer.at("http://localhost:3000").setupPort(3001);
    SystemUnderTest yourCode = new SystemUnderTest();
    
    yourCode.doSomethingThatCallsAWebService();
    
    assertThat(stub, wasCalled("POST", "/endpoint")
                        .withHeader("Content-Type", "text/plain")
                        .withHeader("Accept", "text/plain")
                        .withBodyContaining("TEST"));
    stub.close();
}
</code></pre>
<p>The code above shows the Java assertions.  The first line actually makes two network calls; one to talk to the well-known httpmock URL (in this case, http://localhost:3000) to get the hypermedia.  The second one tells httpmock to set up a new server for stubbing purposes, which is then spun down on the last call in the method.  For performance reasons, you may want to do some of these administrative tasks once for the test suite, particularly retrieving the initial hypermedia.  The <code>wasCalled</code> method also talks to httpmock to perform the verification.  The <code>SystemUnderTest</code> should expect to base its web service calls to http://localhost:3001.</p>
<pre><code class="java">
@Test
public void showStubbingAPI()
{
    StubServer stub = ControlServer.at("http://localhost:3000").setupPort(3001);
    stub.on("GET", "/").returns(new Stub().withStatus(200).withBody("BODY"));
    SystemUnderTest yourCode = new SystemUnderTest();
    
    yourCode.doSomethingThatShouldCall("http://localhost:3001/");
    
    stub.close();
}
</code></pre>
<p>Like typical stubbing libraries, httpmock allows you to set up stubs that will be executed if the server receives the expected call.</p>
<h3>Installing</h3>
<p>You need node.js to run the server.  You can download httpmock from the incredibly ugly <a href="http://bbyars.github.com/httpmock/">downloads</a> page.  Untar the server, and run <code>bin/httpmock start</code>.</p>
<p>This will run the control server on port 3000. You can optionally pass a <code>--port</code> command line argument to change the port and a <code>--pidfile</code> argument to use a non-default pidfile (useful if you&#8217;re running multiple instances). If you run the server in a background job, <code>bin/httpmock stop</code> will kill it.</p>
<p>If you&#8217;re using <a href="https://github.com/isaacs/npm">npm</a>, you can install httpmock with <code>sudo npm install -g httpmock</code>.  Installing it globally allows you to simply say <code>httpmock start</code> on the command line, which feels quite sexy.</p>
<p>The client bindings will simply be a library. For Java, add <a href="http://bbyars.github.com/httpmock/artifacts/v0.2.0/httpmock.jar">httpmock.jar</a> to your classpath.</p>
<h3>Roadmap</h3>
<p>The following are the features I&#8217;d like to add to httpmock:</p>
<ul>
<li>Support for multiple protocols, at least for verification if stubbing doesn&#8217;t make sense (SMTP, FTP, perhaps even things like printer protocols).  It appears at the moment easy enough to support a plugin mechanism where the same REST API will work for multiple protocols, but I won&#8217;t know for sure until getting around to a second protocol.</li>
<li>Support for HTML.  Right now, there is a JSON-based content type used for all communication, which is great for progammatic manipulation.  I think it would also be quite nice to allow QA&#8217;s to manually set up stubs and perform verifications through a web browser.</li>
<li>A more robust stubbing mechanism.  It&#8217;d be nice, for example, to only conditionally execute stubs if a specific request header was set.</li>
<li>More language bindings.</li>
</ul>
<p>Want to contribute?  I&#8217;d love the help.  Send me a pull request at <a href="https://github.com/bbyars/httpmock">github</a>.<br />
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/271/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=271&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2011/05/30/introducing-httpmock/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>The Fundamental Theorem of Renting</title>
		<link>http://brandonbyars.com/2011/01/08/the-fundamental-theorem-of-renting/</link>
		<comments>http://brandonbyars.com/2011/01/08/the-fundamental-theorem-of-renting/#comments</comments>
		<pubDate>Sat, 08 Jan 2011 18:40:44 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Media]]></category>
		<category><![CDATA[Renting]]></category>

		<guid isPermaLink="false">http://brandonbyars.com/?p=254</guid>
		<description><![CDATA[I should start by saying that I&#8217;m not a videophile. My TV is color, but it&#8217;s at least as deep as it is wide, and it&#8217;s certainly not high-def. But I do know this: DVDs suck, and the DVD rental industry is broken. Trying to improve DVDs by making them higher resolution is like trying [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=254&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I should start by saying that I&#8217;m not a videophile.  My TV <em>is</em> color, but it&#8217;s at least as deep as it is wide, and it&#8217;s certainly not high-def.</p>
<p>But I do know this: DVDs suck, and the DVD rental industry is broken.</p>
<p>Trying to improve DVDs by making them higher resolution is like trying to fix ice sculptures by making them prettier.  It works great, until summer rolls around.</p>
<p>As far as I can tell, the media industry (which includes both video and audio media) has been moving towards higher resolution at the expense of longevity.  LP&#8217;s, in case you didn&#8217;t know, stand for &#8220;long-playing,&#8221; and I can still play some of my grandma&#8217;s.  You could literally do jumping jacks on eight tracks and they&#8217;d be fine.  Tapes might get out of sorts from time to time, but you could fix them by sticking a pencil in the cogs and getting the tape wound correctly again.</p>
<p>Then the music industry came out with CDs, and the digital revolution began.  Fast forward a bit, and here we stand.</p>
<blockquote><p>Luke, I am your, your, your, your, your, your, your</p></blockquote>
<p>Damn, just when I was getting into it, too.  I haven&#8217;t been keeping strict tabs on it, largely because I don&#8217;t keep strict tabs on anything, but I&#8217;d guess that approximately two videos out of every one I rent has a significant scratch, strategically located right at the climax of the movie.  Not at the beginning, mind you, because then the previous renter would have failed at maximizing the amount of time you waste.  If they put the scratch at the beginning of the movie, you might even still be sober enough to storm back to the movie store and demand another copy.  Put the scratch at the end, and most movie-goers will just assume that they saw the good parts anyhow, and forget about it.  But climatic scratches leave scars.  By the time the scratch actually <em>does</em> manifest itself, you&#8217;re expected to suffer through the still-frame slideshow, under the delusional hopes than in just a couple of minutes, the show will resume as normal.</p>
<p>When that fails, naturally, you&#8217;re supposed to resign yourself to the fact that you&#8217;ll have to skip to the next chapter, and backtrack to just after the scratched area of the disk.  That probably takes a while, on account of your excessive optimism of just how insignificant the scratch is.  Eventually, you just skip the chapter you were on altogether, hoping you didn&#8217;t miss any Oscar moments.</p>
<p>(By &#8220;you,&#8221; I mean my wife, at least when <em>I</em> watch DVDs, because I still haven&#8217;t figured out how to navigate the arcane series of steps required to coerce the remote control into skipping past the affected area.  And, by this point, I&#8217;m usually too drunk to learn.)</p>
<p>As the next chapter begins, you realize that, while you (or my wife) has succesfully crossed the Grand Canyon, several minor fault lines still emanate from the crevasse.  Eventually, my much soberer wife decides that it is no longer worth her time babysitting the remote, gives up, and hands control over to me.  <em>Damn.</em>  I should really learn how to use that remote one day.</p>
<p>The funny thing about all of this is that the movie industry wants us to upgrade our DVDs to Blu-rays.  The demos I see at electronics stores really are spectacular, too.  But what the marketing fails to mention is the economics of renting, as summarized by the Fundamental Theorem of Renting:</p>
<blockquote><p>Renters demand to rent products that are in better shape than when they return them.</p></blockquote>
<p>Like all deep truths of the universe, this Fundamental Theorem has a number of interesting corollaries, such as the fact that, to be true, every renter must find ways to return the product in <em>worse</em> shape than when they rented it.  Car renters intuitively know this, and home renters are required to pay a deposit to combat the Fundamental Theorem, but movie renters pretend that renting is a harmless affair.</p>
<p>It doesn&#8217;t matter anyway.  Blu Ray is too late.  By the time it came out, physical media was no longer that important.  Now I just have to wait until my wife figures out how to stream Netflix&#8230;</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/254/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/254/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=254&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2011/01/08/the-fundamental-theorem-of-renting/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>RestMvc &#8211; RESTful Goodies for ASP.NET MVC</title>
		<link>http://brandonbyars.com/2011/01/06/restmvc/</link>
		<comments>http://brandonbyars.com/2011/01/06/restmvc/#comments</comments>
		<pubDate>Fri, 07 Jan 2011 00:02:11 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[REST]]></category>

		<guid isPermaLink="false">http://brandonbyars.com/?p=236</guid>
		<description><![CDATA[Last summer, I found myself building a RESTful ASP.NET MVC service that had an HTML admin UI. Oftentimes, the resource that was being edited in HTML was the same resource that needed to be sent out in XML via the service, which mapped nicely to the REST &#8216;multiple representations per resource&#8217; philosophy. There are obviously [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=236&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Last summer, I found myself building a RESTful ASP.NET MVC service that had an HTML admin UI.  Oftentimes, the resource that was being edited in HTML was the same resource that needed to be sent out in XML via the service, which mapped nicely to the REST &#8216;multiple representations per resource&#8217; philosophy.</p>
<p>There are obviously some very nice RESTful libraries for ASP.NET MVC, but none quite met my needs.  <a href="http://abombss.com/blog/2007/12/10/ms-mvc-simply-restful-routing/">Simply Restful Routing</a>, which comes with <a href="http://mvccontrib.codeplex.com/">MVC Contrib</a>, takes a Rails-inspired approach of handing you a pre-built set of routes that more or less match a RESTful contract for a resource.  While obviously convenient, that&#8217;s never been my preferred way to manage routing.  It adds a bunch of routes that you probably have no intention of implementing.  It keeps the routes centralized, which never seemed to read as well to me as the way <a href="http://www.sinatrarb.com/">Sinatra</a> keeps the routing configuration next to the block that handles requests to that route.</p>
<p>Additionally, one of the problems I encountered with other routing libraries like Simply Restful is that they define the <code>IRouteHandler</code> internally, which removes your ability to add any custom hooks into the routing process.  I needed just such a hook to add content negotiation.  I also wanted some RESTful goodies, like responding with a 405 instead of a 404 status code if we did route to a resource (identified by a URI template), but not to a requested HTTP verb on that resource.  I wanted the library to automatically deal with HEAD and OPTIONS requests.  In the end, I created my own open-source library called <a href="https://github.com/bbyars/RestMvc/">RestMvc</a> which provides such goodies with Sinatra-like routing and content negotiation.</p>
<h3>Routing</h3>
<pre><code class="csharp">public class OrdersController : Controller
{
    [Get("/orders")]
    public ActionResult Index() { ... }

    [Post("/orders"]
    public ActionResult Create() { ... }

    [Get("/orders/{id}.format", "/orders/{id}")]
    public ActionResult Show(string id) { ... }

    [Put("/orders/{id}")]
    public ActionResult Edit(string id) { ... }

    [Delete("/orders/{id}")]
    public ActionResult Destroy(string id) { ... }
}</code></pre>
<p>Adding the routes for the attributes above is done in Global.asax.cs, in a couple of different ways:</p>
<pre><code class="csharp">
RouteTable.Routes.Map();
// or RouteTable.Routes.MapAssembly(Assembly.GetExecutingAssembly());
</code></pre>
<p>That is, in effect, the entire routing API of RestMvc.  The <code>Map</code> and <code>MapAssembly</code> extension methods will do the following:</p>
<ul>
<li>Create the routes defined by the HTTP methods and URI templates in the attributes.  Even though <code>System.Web.Routing</code> does not allow you to prefix URI templates with either / or ~/, I find allowing those prefixes can enhance readability, and thus they are allowed.</li>
<li>Routes HEAD and OPTIONS methods for the two URI templates (&#8220;orders&#8221; and &#8220;orders/{id}&#8221;) to a method within RestMVC capable of handling those methods intelligently.</li>
<li>Routes PUT and DELETE for /orders, and POST for /orders/{id}, to a method within RestMvc that knows to return a 405 HTTP status code (Method Not Supported) with an appropriate Allow header.  This method and the ones that handle HEAD and OPTIONS, work without any subclassing for the <code>Controller</code> as shown above.  However, if you need to customize their behavior &#8212; for example, to add a body to OPTIONS &#8212; you can subclass <code>RestfulController</code> and override the appropriate method.</li>
<li>Adds routes for tunnelling PUT and DELETE through POST for HTML browser support.  RestMvc takes the Rails approach of looking for a hidden form field called <code>_method</code> set to either PUT or DELETE.  If you don&#8217;t want the default behavior, or you do want the tunnelling but with a different form field, you can call <code>ResourceMapper</code> directly instead of accepting the defaults that the <code>Map</code> and <code>MapAssembly</code> extension methods provide.</li>
<li>Notice the optional <code>format</code> parameter on the <code>Get</code> attribute above the <code>Show</code> method.  Routes with an extension are routed such that the extension gets passed as the <code>format</code> parameter, if the resource supports multiple representations (e.g. /orders/1.xml routes to <code>Show</code> with a <code>format</code> of xml).  The ordering of the URI templates in the <code>Get</code> attribute is important.  Had I reversed the order, /orders/1.xml would have matched with an id of &#8220;1.xml&#8221; and an empty format</li>
<p>The last point is a convenient way to handle multiple formats for a resource.  Since it&#8217;s in the URL, it can be bookmarked and emailed, or tested through a browser, with the same representation regardless of the HTTP headers.  Even if content negotiation is used, it allows you to bypass the standard negotiation process.  Note that having different URLs for different representations of the same resource is generally frowned upon by REST purists.  RestMvc does not automatically provide these routes for you, but lets you add them if you want.</p>
<h3>Content Negotiation</h3>
<p>Content negotiation is provided as a decorator to the standard <code>RouteHandler</code>.  Doing it this way allows you to compose additional custom behavior that needs access to the <code>IRouteHandler</code>.</p>
<pre><code class="csharp">// In Global.asax.cs
var map = new MediaTypeFormatMap();
map.Add(MediaType.Html, "html");
map.Add(MediaType.Xhtml, "html");
map.Add(MediaType.Xml, xml");

var connegRouter = new ContentNegotiationRouteProxy(new MvcRouteHandler(), map);

RouteTable.Routes.MapAssembly(Assembly.GetExecutingAssembly(), connegRouter);</code></pre>
<p>In the absence of a route URI template specifying the format explicitly, the <code>connegRouter</code> will examine the Accept request header and pick the first media type supported in the map.  Wildcard matches are supported (e.g. text/* matches text/html).  The <code>format</code> parameter will be set for the route, based on the value added in the <code>MediaTypeFormatMap</code>.</p>
<p>The content negotiation is quite simple at the moment.  The <code>q</code> parameter in the Accept header is completely ignored.  By default, it tries to abide by the Accept header prioritization inferred from the order of the MIME types in the header.  However, you can change it to allow the server ordering, as defined by the order MIME types are added to the MediaTypeFormatMap, to take priority.  This was added to work around what I consider to be a bug in Google Chrome &#8211; despite being unable to natively render XML, it prioritizes XML over HTML in its Accept header.  The library does not currently support sending back a 406 (Not Acceptable) HTTP status code when no acceptable MIME type is sent in the Accept header.</p>
<h3>Next Steps</h3>
<p>I haven&#8217;t worked on RestMvc in a few months, largely because I shifted focus at work and haven&#8217;t done any .NET programming in a while.  However, I had planned on doing some automatic etagging, and to make the content negotiation more robust.</p>
<p>Contributors welcome!  The code can be found on <a href="https://github.com/bbyars/restmvc">github</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/236/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/236/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=236&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2011/01/06/restmvc/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Picking Up The Pen Again</title>
		<link>http://brandonbyars.com/2011/01/04/picking-up-the-pen-again/</link>
		<comments>http://brandonbyars.com/2011/01/04/picking-up-the-pen-again/#comments</comments>
		<pubDate>Tue, 04 Jan 2011 19:43:39 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Writing]]></category>

		<guid isPermaLink="false">http://brandonbyars.com/?p=226</guid>
		<description><![CDATA[800. That&#8217;s the number of days my Muse has slumbered. That&#8217;s the number of days since I set my pen down. 800 days ago, I wrote my last blog post. Quite a bit has happened since then. The economy fell out from under us. The US elected its first black President in history. Michael Jackson [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=226&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>800.</p>
<p>That&#8217;s the number of days my Muse has slumbered.  That&#8217;s the number of days since I set my pen down.  800 days ago, I wrote my last blog post.</p>
<p>Quite a bit has happened since then.  The economy fell out from under us.  The US elected its first black President in history.  Michael Jackson died.</p>
<p>718 days ago, my wife delivered our second son, 3,622 days after she delivered our first son.  520 days ago, my family moved to another country.  And, yesterday, my Muse awoke.</p>
<p>My Muse surveyed the landscape after shaking off his hibernation languor, and decided that my old blog just looked, like, so last decade.  So, I moved it, and I updated it, and I changed the DNS to point to the new location<sup>1</sup>.</p>
<p>800 days after setting my pen down, I have a new blog.  And tomorrow, my Muse and I start discussing what to do about that.</p>
<p class="small"><sup>1</sup>While most of the links moved over fine, the <a href="http://brandonbyars.com/feed/">RSS feed</a> has changed.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/226/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/226/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=226&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2011/01/04/picking-up-the-pen-again/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Funcletize This!</title>
		<link>http://brandonbyars.com/2008/10/26/funcletize-this/</link>
		<comments>http://brandonbyars.com/2008/10/26/funcletize-this/#comments</comments>
		<pubDate>Sun, 26 Oct 2008 18:13:00 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[SQL Server]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I was recently involved in troubleshooting a bug in our staging environment. We had some code that worked in every environment we had put it in, except staging. Once there, you perform the equivalent of an update on a field (using LINQ in C#), only to be greeted by a ChangeConflictException. I&#8217;m embarrassed by how [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=51&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I was recently involved in troubleshooting a bug in our staging environment.  We had some code that worked in every environment we had put it in, <em>except</em> staging.  Once there, you perform the equivalent of an update on a field (using LINQ in C#), only to be greeted by a <code>ChangeConflictException</code>.</p>
<p>I&#8217;m embarrassed by how long it took to figure out what was wrong.  It was obviously an optimistic locking problem, and I even mentioned that it was because the <code>UPDATE</code> statement wasn&#8217;t updating anything once I first saw the exception.  Optimistic locking works by adding extra fields to the <code>WHERE</code> clause to make sure that the data hasn&#8217;t changed since you loaded it.  If one of those fields had changed, the <code>WHERE</code> clause wouldn&#8217;t match anything, and the O/RM would assume that somebody&#8217;s changed the data behind your back and throw an exception.</p>
<p>It turns out that failing to match any rows with the given filter isn&#8217;t the only way that LINQ will think no rows were updated; it&#8217;s also dependent on the <code>NOCOUNT</code> option in SQL Server.  If the database is configured to have <code>NOCOUNT ON</code>, then the number of rows affected by each query won&#8217;t be sent back to the client.  LINQ interprets this lack of information as 0 rows being updated, and thus throws the <code>ChangeConflictException</code>.</p>
<p>In itself, the bug wasn&#8217;t very interesting.  What <em>is</em> interesting is what we saw when we opened Reflector to look at the LINQ code around the exception:</p>
<pre>
<code class="csharp">IExecuteResult IProvider.Execute(Expression query)
{
    // …
    query = Funcletizer.Funcletize(query);
}</code>
</pre>
<p>Love it.  <code>Uniquifiers</code>, <code>Funcletizers</code>, and <code>Daemonizers</code> of the world unite.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/51/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/51/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=51&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2008/10/26/funcletize-this/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Windows is a Ghetto</title>
		<link>http://brandonbyars.com/2008/10/19/windows-is-a-ghetto/</link>
		<comments>http://brandonbyars.com/2008/10/19/windows-is-a-ghetto/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 06:20:00 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Operating Systems]]></category>
		<category><![CDATA[OS X]]></category>
		<category><![CDATA[Unix]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Over the years, I&#8217;ve tolerated a lot of operating system abuse. Earlier in my career, I tended to keep my mouth shut (mainly because I didn&#8217;t know any better), but over time, the annoyances have been building up into a crescendo of anger, such that at the end of the day I consistently find myself [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=50&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Over the years, I&#8217;ve tolerated a lot of operating system abuse.  Earlier in my career, I tended to keep my mouth shut (mainly because I didn&#8217;t know any better), but over time, the annoyances have been building up into a crescendo of anger, such that at the end of the day I consistently find myself red-faced, foaming at the mouth, and screaming adjective interjection adjective noun, exclamation<sup>1</sup> at my monitor.  As the blood boils and the temper flares at the inanity I find myself forced to endure, I&#8217;ve consoled myself by deciding that I would some day vent my frustrations to the world at large.</p>
<p>This is that rant.</p>
<h3>The Actors</h3>
<p>I&#8217;ve used variants of two main operating systems.  I&#8217;ve decided to give them fake names to protect the guilty.</p>
<p>The first operating system, the older of the two, is known as Eunuchs.  The first time I used Eunuchs, I found it strange and cryptic.  I couldn&#8217;t understand its attachment to the command line, nor could I grasp why so many developers and universities were so enamored with it.  My very first paid programming project involved me writing a deployment tool that was used to release Eunuchs applications to production.  However (and I found this quite strange at the time), the developers wanted the tool written in that <em>other</em> operating system, so they could get a nice usable GUI for it.</p>
<p>That other operating system, which I&#8217;ll call MacroHard Windows, was all about the GUI.  <em>Their</em> command line was terrible, and it is terrible still.  Back then, being paid to write a GUI deployment tool, I didn&#8217;t see why that mattered.</p>
<p>I&#8217;ve written a lot of code since then, both in Eunuchs and with MacroHard tools, and I&#8217;ve decided that MacroHard is appropriately named.  It&#8217;s hard.  <em>Really</em> hard.</p>
<h3>The Rant</h3>
<p><em>Windows is the worst development environment on the face of the planet</em></p>
<p>To be clear, I mean that without the slightest hint of exaggeration.  For example, I understand times were hard in the early days of computing.  I never had the opportunity to work on the <a href="http://en.wikipedia.org/wiki/ENIAC">ENIAC</a>, but apparently it once went almost 5 days without a failure, something I have yet to achieve on any MacroHard platform.  The first time I ever programmed <em>anything</em>, it was a blackjack program on my calculator.   Programming on Windows makes me yearn for those halcyon calculator days of yesteryear.</p>
<p><em>For example?</em></p>
<p>Eunuchs has files and processes.  Sure, it has pipes and sockets and runtime process information too, but those are just files, really.  Sure it has network servers and daemons and startup commands, but those are nothing more than processes, and configuring them means putting a bunch of stuff in a bunch of files.  If you want to manage them, you use file commands.  Or process commands.  Yes, sometimes they&#8217;re cryptic, and sometimes the names of things look like they were invented by 19 year old kids whose idea of social interaction was playing World of Warcraft, but it&#8217;s really not that hard to figure out once you get the hang of it.</p>
<p>Windows has files and processes and registry hives and COM+ catalogs and IIS metabases and app pools and Active Directory stores and Windows services and performance counters and event logs and global assembly caches.  If you want to manage them, you open a barely usable GUI, and if you click into enough nested dialog boxes, you might get lucky and find the setting you need.  Or you buy &#8220;enterprise&#8221; tools to manage them like Macrohard Operations Manager<sup>TM</sup>, which has an entirely different maze of dialog boxes to follow.  A <a href="http://www.aliaghareza.com/">colleague</a> once put it better than I possibly could: The solution to MacroHard problems is to buy more MacroHard solutions.</p>
<p>Somehow, far too many IT executives have been sold on the idea that <em>this</em> is easier for people to understand.  It isn&#8217;t.</p>
<p>Oh sure you can script these multitude of entities that Windows supports, if you have a new enough version of Windows.  Of course, every component has a different scriptable interface.  Hell, even IIS has <em>multiple</em> scriptable interfaces.  You can use ADSI or WMI, but only WMI if you&#8217;re configuring an IIS 6.0 server.  You can use C++ or VB to use ABO (admin base objects), or C++ to use specialized COM interfaces.</p>
<p>And sometimes, the canonical UIs that MacroHard want you to use interact with the subsystem you&#8217;re trying to script in such a way as to effectively remove any confidence in your scripts.  For example, it&#8217;s possible to <a href="http://whattodowearelikethatonly.blogspot.com/2008/09/developing-on-windows-reinstalling.html">script your way into a disabled Windows service</a>, where apparently the only way to remove the service is to shut down the services MacroHard Management Console Snap-In<sup>TM</sup>.  If you&#8217;re a Eunuchs developer, you may want to re-read that last sentence, because it probably doesn&#8217;t appear even remotely possible to you that having a GUI open could prevent you from scripting the removal of a daemon.</p>
<p><em>But aren&#8217;t you being too hard on MacroHard?</em>
<p>I suppose there are <em>some</em> things that MacroHard has done better than Eunuchs.  For example, MacroHard has Active Directory, which is an enterprise-ready LDAP security solution, not something you get out of the box in Eunuchs.  And with Active Directory comes Windows Integration, where a bunch of applications that MacroHard wrote are integrated into the operating system in such a way that they automatically authenticate based on your Windows login.  For example, they wrote one application (a particularly bad one, but quite widely used) called Internet Destroyer.  It&#8217;s possible, as a web developer, for you to set your web site up requiring integrated Windows authentication.  Anyone using Internet Destroyer to visit your website will automatically authenticate against your domain controller, which is occasionally quite handy.</p>
<p>However, the magic that makes that work is sometimes too obscure to fathom.  For example, you can set up system-wide database settings in Windows called DSN&#8217;s.  The DSN gives you two ways to connect to the database &#8211; using Windows Authentication, or using a SQL login.  MacroHard also has a component called perfmon, that collects performance information for you, which has an option to log that information to a database given a DSN.  Strangely, using a SQL login doesn&#8217;t work with perfmon, although good luck finding documentation that says so.  If you&#8217;re a Eunuchs developer, you might want to re-read that last sentence, since it probably doesn&#8217;t appear even remotely possible that a process can&#8217;t connect to a database using a connection string with a database login.</p>
<p><em>Ok, but why are you really mad?</em></p>
<p>I&#8217;m mad because once upon a time, I wanted to know why a build failed, and that build happened to be using the MacroHard test framework called MHTest, as opposed to the open source alternatives, which are known for their annoying insistence to tell you <em>why</em> your build fails when it does fail.  Here&#8217;s what I got with MHTest:</p>
<p>Test Failure: VerifyLogFilePath</p>
<p>At first I just found it amusing that MHTest told me <em>what</em> failed, but not <em>why</em> it failed.  After all, that annoyance only manifests itself on the command line; if I used Visual Studio to run the MHTests, it&#8217;ll give me more information.</p>
<p>After a while, I thought it&#8217;d be nice to see how much of our code was actually covered by MHTest.  Naturally, I tried to integrate that feedback into our build, which meant calling it on the command line.  It turns out that MHTest&#8217;s code coverage spits out a binary file.  If you want to interpret it, you&#8217;ll need to use Visual Studio.</p>
<p>But the good news is that, unlike the open source alternatives, MHTest randomly adds files to your projects and only works if you add magic GUIDs to your project files.  This is actually a great feature if, like me, you get billed by the hour and you want large checkins to pretend that you accomplished a lot.</p>
<p>I&#8217;m mad because I wanted to run both versions 1 and 2 of Powershell on my machine (Powershell is MacroHard&#8217;s attempt at a less sucky command line), so that we could test against both versions, but MacroHard won&#8217;t let you run both on them on one machine.  I&#8217;m mad because, for years, I thought that the Windows command line would randomly hang, but recently I discovered that <em>if</em> you accidentally click a mouse in a command window while it&#8217;s running a process spitting out console messages, <em>and</em> you happen to be in Quick Edit Mode (which is a Windows command line euphemism for completely unusable, but less so than the alternative), <em>then</em> the process will be paused, <em>until</em> you right click in the same command window.  I&#8217;m mad because I like to test websites with multiple versions of Internet Destroyer, but without some <a href="http://tredosoft.com/Multiple_IE">crazy hackery</a>, it&#8217;s not possible to run multiple versions on one machine.  I&#8217;m mad because I installed MacroHard .NET 3.5 Service Pack 1, which forced me to close down every application on my machine &#8211; yes, forced, not asked &#8211; and reboot my machine, only to find out that it&#8217;s buggy enough that MacroHard feels compelled to supercede it with .NET 3.5 Service Pack 1 Service Release 1.</p>
<p>I&#8217;m mad because when I finally figure out the right combination of nested modal dialog boxes to pop up to configure IIS, I find a text box into which I cannot paste and from which I cannot copy, and whose &#8216;OK&#8217; button is only enabled after accidentally clicking in the upper left hand quadrant of grayspace on the form.  I&#8217;m mad because when I want to add a keyboard shortcut to Visual Studio I get a box showing me 3.87 commands at a time (out of hundreds) from which to select the command to assign the shortcut to, with no way to expand my view.  I&#8217;m mad because I have absolutely no clue what error 0&#215;00001ad59add means, and I <em>am</em> the goddamned system administrator I&#8217;m supposed to contact.</p>
<p>Mainly I&#8217;m mad because I love software development, and MacroHard has done much to lessen the joy that comes with hacking.</p>
<p><em>Reasons for optimism</em></p>
<p>Eunuchs is indeed an ironic name, given that modern derivatives can claim a veritable biblical list of progenitors: Eunuchs beget Minix, which beget Linux, which beget Knoppix&#8230;  Those children have traditionally been considered as a better server platform than MacroHard, although MacroHard has made unfortunate inroads (in part thanks to one good thing MacroHard did &#8211; they were the first to realize that a &#8220;server&#8221; didn&#8217;t have to mean big iron).  But the traditional advantage of MacroHard came from its desktop market, where until recently it had no competitors.  It is one of the ironies of our industry that the competitor that now exists is the same one which MacroHard, in its infancy, was commissioned to help, and that the competitor now runs a derivative of Eunuchs.</p>
<p>OS X is becoming the de facto operating system for those who want to continue having fun developing software, but who like pretty and usable GUIs.  It will never have much of a server market, but it doesn&#8217;t matter: what you develop on a Mac can be deployed to a Linux server with only minor gotchas like filename case-sensitivity.  Many developers have never needed GUIs, or have been satisfied with the uglier (but improving) ones found in the Linux world, and they continue to have fun developing software.  But I understand now why those developers who acted as the customers for my first paid project wanted a GUI: the command line is <em>absolutely essential</em> to development, but GUIs are helpful from time to time as well.  Large portions of the Linux world have understood that principle for a long time, but it took Apple&#8217;s expertise on usability and their operating system&#8217;s Eunuchs heritage to provide the first OS that was both user-friendly <em>and</em> developer friendly.</p>
<p>Unfortunately for MacroHard, they are too weighted down by the enormous size of Windows to respond effectively.  It took them five years to get Vista out the door, and that was only after removing every interesting feature from it.  And even now, nobody uses it.  As a software consultant with a history of working on MacroHard platforms, you&#8217;d think <em>I&#8217;d</em> know something about Vista, but honestly, I haven&#8217;t even seen it.</p>
<p>The development world is changing, and that&#8217;s a good thing.  I have a feeling that the future of software development will be much more <em>fun</em> than it is now.</p>
<p><sup>1</sup>This clever phrase was stolen from Steve Yegge: http://steve-yegge.blogspot.com/2008/09/programmings-dirtiest-little-secret.html</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/50/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/50/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=50&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2008/10/19/windows-is-a-ghetto/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Orthogonality</title>
		<link>http://brandonbyars.com/2008/07/21/orthogonality/</link>
		<comments>http://brandonbyars.com/2008/07/21/orthogonality/#comments</comments>
		<pubDate>Tue, 22 Jul 2008 04:36:00 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Eiffel]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Smalltalk]]></category>
		<category><![CDATA[VB]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[Orthogonality means that features can be used in any combination, that the combinations all make sense, and that the meaning of a given feature is consistent, regardless of the other features with which it is combined. The name is meant to draw an explicit analogy to orthogonal vectors in linear algebra: none of the vectors [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=49&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<blockquote><p>
Orthogonality means that features can be used in any combination, that the combinations all make sense, and that the meaning of a given feature is <em>consistent</em>, regardless of the other features with which it is combined.  The name is meant to draw an explicit analogy to orthogonal vectors in linear algebra: none of the vectors in an orthogonal set depends on (or can be expressed in terms of) the others, and all are needed in order to describe the vector space as a whole.</p>
<div class="quote_attribution">&#8211; Michael Scott (Programming Language Pragmatics)</div>
</blockquote>
<div class="clear"></div>
<p></p>
<p>I&#8217;ve used Delphi and Visual Basic at previous jobs.  I disliked both of them.  VB has this annoying distinction between objects and primitives, so I&#8217;d consistently type</p>
<pre>
<code class="vb">Dim server
server = &quot;localhost&quot;

Dim catalog
catalog = CreateObject(&quot;MyCompany.MyObject&quot;)</code>
</pre>
<p>&#8230;only to be greeted by an ugly Windows popup box that <code>Object doesn't support this property or method</code>.  The problem, as all you grizzled VB programmers no doubt spotted immediately, is the last line should start with the keyword <code>Set</code>.  VB requires you to prefix assignments on &#8220;objects&#8221; with <code>Set</code>.  But if you try to put a <code>Set</code> in front of assignments on what VB considers primitives (like the first assignment above), you get an error that reads <code>Object required: '[string: "localhost"]'</code>.</p>
<p>Delphi likewise frustrated me with mundane annoyances:</p>
<pre>
<code class="delphi">DoOneThing();

if value = goal then
    DoSomething();
else
    DoSomethingElse();</code>
</pre>
<p>The code above doesn&#8217;t compile, and it won&#8217;t compile until you remove the semicolon from the call to <code>DoSomething()</code>.  Semicolons complete a statement, and the statement is the entire <code>if-else</code> clause.</p>
<p>These problems in VB and Delphi are related to the concept of <em>orthogonality</em> mentioned in the opening quote.  VB doesn&#8217;t let you compose assignment to objects the same way it lets you compose assignment to primitives.  Delphi doesn&#8217;t let you end an <code>if</code> clause the same way it lets you end an <code>else</code> clause.  These inconsistencies encourage even experienced programmers to make silly syntax mistakes and make the language harder to use.</p>
<h3>What is orthogonality?</h3>
<p>The key principles I extracted from Michael Scott&#8217;s quote listed above are <em>consistency</em> and <em>composability</em>.  Composability means that features can be combined, and consistency stands in for the <a href="http://en.wikipedia.org/wiki/Principle_of_least_astonishment">Principle of Least Surprise</a>&#8212;features act how you expect they would, regardless of how they&#8217;re being combined.  VB&#8217;s assignments lack consistency.  Delphi&#8217;s semicolon parsing doesn&#8217;t act consistently when composed within a surrounding statement.</p>
<p>Scott claims that a highly orthogonal language is easier to understand and easier to use.  Nowhere does he mention that it&#8217;s easier to <em>implement</em>.  I&#8217;m sure the Delphi grammar was simplified considerably by refusing to allow the <code>DoSomething</code> statement to end in a semicolon when contained within an outer <code>if-else</code> clause.  It&#8217;s also likely that the implementation of Visual Basic was simplified by having the programmer tell the compiler whether an assignment referred to an object or a primitive.</p>
<p>I suspect many non-orthogonal aspects of languages are there to make them easier to implement.  However, some languages that are trivially easy to implement can also be amazingly orthogonal.  Lisp is a prime example; it is a highly orthogonal language, and yet an entire Lisp interpreter written in Lisp fits on just <a href="http://bc.tech.coop/blog/080101.html">one page</a> of the Lisp 1.5 Programmer&#8217;s Manual.</p>
<p>I found it instructive to list out syntactic constructs that make languages less orthogonal.  It&#8217;s amazing how mainstream most of them are:</p>
<h4>Statements</h4>
<p>Statements aren&#8217;t necessary, and a number of languages avoid them altogether.  Having only expressions makes the language easier to work in.  Compare the inconsistency of Delphi&#8217;s statement parsing to the composability of Ruby&#8217;s expressions:</p>
<pre>
<code class="ruby">puts if x == 0
  "Zero"
else
  "Not Zero"
end</code>
</pre>
<p>The <code>if</code> clause is an expression; it returns the last value evaluated (e.g., either &#8220;Zero&#8221; or &#8220;Not Zero&#8221;).  And that value can be composed within another expression.</p>
<p>So what happens when you don&#8217;t have a reasonable return value?  Smalltalk always returns <code>self</code>, which is convenient because it allows method chaining.  In the Ruby example above, the entire expression returns the result of the call to <code>puts</code>, which happens to be <code>nil</code>.</p>
<p>The beauty of expressions is that the composability doesn&#8217;t just go one level deep:</p>
<pre>
<code class="ruby">x = if a == 1; 1; else; 2 end

y = x = if a == 1; 1; else; 2; end

puts y = x = if a == 1; 1; else; 2; end

puts "returns nil" if (puts y = x = if a == 1; 1; else; 2; end).nil?</code>
</pre>
<p>As the example above shows, orthogonality doesn&#8217;t guarantee good code.  However, it allows the language to be used in unanticipated ways, which is A Good Thing.  Moreover, since everything is an expression, you can put expressions where you wouldn&#8217;t normally expect them.  For example, in Ruby, the <code>&lt;</code> operator represents inheritance when the receiver is a class, but the superclass could be an expression:</p>
<pre>
<code class="ruby">class Test &lt; if x == 1; OneClass; else; TwoClass
end</code>
</pre>
<p>Pushing a language like this, only to find that it&#8217;s <a href="http://en.wikipedia.org/wiki/Turtles_all_the_way_down">turtles</a> <a href="http://www.cincomsmalltalk.com/userblogs/avi/blogView?showComments=true&#038;entry=3284695382">all the way down</a>, is a signpost for orthogonality.</p>
<h4>Primitives</h4>
<p>We already saw the clumsiness of VB primitives, but most mainstream languages share a similar problem.  Java, for example, has a confusing dichotomy of <code>long</code>s and <code>Long</code>s, the first a primitive and the second a full-fledged object.  C has stack-allocated primitives, which are freed automatically when they fall out of scope, and heap-allocated variables, which you have to free yourself.  C# has value types, which force another abstraction &#8211; boxing &#8211; into the programmer&#8217;s lap.</p>
<pre>
<code class="csharp">private static object DBNullIf(int value, int nullValue)
{

    return (value != nullValue) ? (object)value : DBNull.Value;

}</code>
</pre>
<p>The code above should be a head-scratcher.  Isn&#8217;t <code>object</code> the superclass of all other types?  And if so, why do we have to explicitly cast our <code>int</code> variable to an <code>object</code> to make this code compile?  Why don&#8217;t we have to do the same for the <code>DBNull</code>?</p>
<p>I mentioned above that ease of implementation is a common source of non-orthogonality.  With primitives, we can see another, more legitimate reason: performance.  There is a cost to keeping primitives out of the language.  Below, we&#8217;ll see several more non-orthogonal language features that make performance easier to optimize.</p>
<h4>Nulls</h4>
<p>Nulls have been problematic enough that an entire <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">design pattern</a> has been created to avoid them.  Access violations and object reference exceptions are some of the most common programmer errors.  Most languages divide object references into two types: those that point to an object, and those that point to nothing.  There&#8217;s nothing intrinsically non-orthogonal about that division, except that in most languages the references that point to nothing <em>work differently</em>.  Instead of returning a value, they throw an exception when dereferenced.</p>
<p>In Ruby, the division is still more or less there &#8212; some references point to objects, and some point to nothing &#8212; <em>but both types of references still return a value.</em>  In effect, Ruby has built the Null Object pattern into the language, as the references that point to nothing return a <code>nil</code> value.  But, like everything else in Ruby, <code>nil</code> is an object (of type <code>NilClass</code>), and can be used in expressions:</p>
<pre>
<code class="ruby">1.nil?      # returns false
nil.nil?    # returns true</code>
</pre>
<p>You never get an <code>NullReferenceException</code> in Ruby.  Instead, you get a <code>NoMethodError</code> when you try to call a method on <code>nil</code> that doesn&#8217;t exist, which is exactly the same error you&#8217;d get if you called a method on any object that didn&#8217;t exist.</p>
<h4>Magic Functions</h4>
<p>Most object-oriented languages have certain functions that aren&#8217;t really methods.  Instead, they&#8217;re special extensions to the language that make the class-based approach work.</p>
<pre>
<code class="csharp">public class Magic
{
    public static void ClassMethod()
    {
    }

    public Magic()
    {
    }

    public void NormalMethod()
    {
    }
}

Magic.ClassMethod();
Magic magic = new Magic(5);
magic.NormalMethod();</code>
</pre>
<p>Notice the context shift we make when constructing new objects.  Instead of making method calls via the normal syntax (<code>receiver.method()</code>), we use the keyword <code>new</code> and give the class name.  But what is the class but a factory for instances, and what is the constructor but a creation method?  In Ruby, the constructor is just a normal class-level method:</p>
<pre>
<code class="ruby">regex = Regexp.new(phone_pattern)</code>
</pre>
<p>Typically, the <code>new</code> class-level method allocates an instance and delegates to the newly created instance&#8217;s <code>initialize</code> method (which is what most Ruby programmers call the &#8220;constructor&#8221;).  But, since <code>new</code> is just a normal method, if you <em>really</em> wanted to, you could override it and do something different:</p>
<pre>
<code class="ruby">class Test
  def self.new
    2 + 2
  end
end

Test.new    # returns 4!!</code>
</pre>
<p>Operators also tend to be magic methods in many languages.  Ruby more or less treats them just like other methods, except the interpreter steps in to break the elegant consistency of everything-as-a-method to provide operator precedence.  Smalltalk and Lisp, two other highly orthogonal languages, do not provide operator precedence.  Operators are just normal methods (functions in Lisp), and work with the same precedence rules as any other method.</p>
<p>So here we have yet another reason, on top of ease of language implementation and performance, to add non-orthogonality to a language.  Ruby adds operator precedence, even though it adds an element of inconsistency, presumably because it makes the language more intuitive.  Since intuitiveness is one of the purported benefits of orthogonality, there is a legitimate conflict of interest here.  I think I would prefer <em>not</em> having operator precedence, and leaving the language consistent, but it seems more of a question of style than anything else.</p>
<h4>Static and sealed Methods</h4>
<p>Class-based object-oriented languages impose a dichotomy between classes and instances of those classes.  Most of them still allow behavior to exist on classes, but that behavior is treated differently than instance behavior.  By declaring class methods as <code>static</code>, you&#8217;re telling the compiler that it&#8217;s free to compute the address of this function at compile-time, instead of allowing the dynamic binding that gives you polymorphism.</p>
<p>Ruby gives you some degree of polymorphism at the class level (although you can&#8217;t call superclass methods, for obvious reasons):</p>
<pre>
<code class="ruby">class Animal
  def self.description
    "kingdom Animalia"
  end
end

class Person &lt; Animal
  def self.description
    &quot;semi-evolved simians&quot;
  end
end</code>
</pre>
<p>In most mainstream languages, not even all instance methods are polymorphic.  They are by default in Java, although you can make them statically-bound by declaring them <code>final</code>.  C# and C++ take a more extreme approach, forcing you to declare them <code>virtual</code> if you want to use them polymorphically.</p>
<p>Behavior cannot be combined consistently between <code>virtual</code> and <code>sealed</code> (or <code>final</code>) methods.  It&#8217;s a common complaint when developers try to extend a framework only to find out that the relevant classes are <code>sealed</code>.</p>
<h4>Instance Variables</h4>
<p>Only the pure functionalists can get by without state; the rest of us need to remember things.  But there&#8217;s no reason why the mechanism of retrieving stored values has to be treated differently from the mechanism of calling a parameter-less function that computes a value, nor is there a reason that the mechanism for storing a value has to be different from the mechanism of calling a setter function to store the value for you.</p>
<p>It is common OO dogma that state should be private, and if you need to expose it, you should do so through getters and setters.  The evolution of the popular Rails framework recently reaffirmed this dogma.  In prior versions, sessions were exposed to the controllers via the <code>@session</code> instance variable.  When they needed to add some logic to storing and retrieving, they could no longer expose the simple variable, and refactored to a getter/setter attribute access.  They were able to do so in a backward-compatible way, by making the <code>@session</code> variable a proxy to an object that managed the logic, but it was still a process that a more orthogonal language wouldn&#8217;t have required.  <em>The language should not force you to distinguish between field access and method access.</em></p>
<p>Both Lisp and Eiffel treat instance variables equivalently to function calls (at least when it comes to rvalues).  Lisp simply looks up atoms in the environment, and if that atom is a function (lambda), then it can be called to retrieve the value no differently than if the atom is a variable containing the value.  Eiffel, an object-oriented language, declares variables and methods using the same keyword (<code>feature</code>), and exposes them  &#8211; both to the outside world and to the class itself &#8211;  the same way (Bertrand Meyer called this the Uniform Access principle):</p>
<pre>
<code class="eiffel">class POINT
feature
    x, y: REAL
            -- Abscissa and ordinate

    rho: REAL is
            -- Distance to origin (0,0)
        do
            Result := sqrt(x^2 + y^2)
        end</code>
</pre>
<p>Once you get passed Eiffel&#8217;s tradition of YELLING TYPES at you and hiding the actual code, Uniform Access makes a lot of sense.  Instance variables are just like features without bodies.  C# has properties, which provide similar benefits, but force you to explicitly declare them.  Instead of a <code>getRho</code> and <code>setRho</code> method, you can have a property that allows clients to use the same syntax regardless of whether they&#8217;re using a property or a field.  Because Ruby allows the = symbol as part of a method name, it allows a similar syntax.</p>
<p>However, the separation between variables and properties is superfluous.  For example, there&#8217;s no need for them to have separate access levels.  If other classes need the state exposed, then declare it public.  If the language doesn&#8217;t offer instance variables, then you&#8217;re simply exposing a property method.  If you run into the same problem that Rails ran into, and suddenly need to add behavior around exposed state, refactoring should be easy.  Just add a private property method that is now the state, and leave the public property method.</p>
<p>So, in my hypothetical language, we might have the following:</p>
<pre>
<code>class Controller
  public feature session
end</code>
</pre>
<p>And when you feel you need to add behavior around the exposed <code>session</code> dictionary, it should be easy:</p>
<pre>
<code>class Controller
  public feature session
    # added behavior goes here
    private_session
  end

  private feature private_session
end</code>
</pre>
<p>One thing that this hypothetical syntax doesn&#8217;t allow is separate access levels for getting and setting, but it shows the basic idea.</p>
<h4>Inconsistent Access Levels</h4>
<p>Since we&#8217;re on the subject of access levels, Ruby&#8217;s <code>private</code> access level is not very orthogonal at all.  Unlike C++ derived languages, Ruby&#8217;s <code>private</code> is object-level, not class-level, which means that even other instances of the same class can&#8217;t directly access the <code>private</code> method.  That&#8217;s a reasonable constraint.</p>
<p>However, instead of making object-level <code>private</code> access level orthogonal, the implementors simply disallowed developers to specify the receiver for <code>private</code> methods.  This undoubtedly made implementing object-level <code>private</code> access much easier.  Unfortunately, it means that you can&#8217;t even use <code>self</code> as the receiver within the object itself, which makes moving a method from <code>public</code> or <code>protected</code> to <code>private</code> non-transparent, even if all references to the method are within the class itself:</p>
<pre>
<code class="ruby">class TestAccessLevels
  def say_my_name
    puts self.name
  end

  private
  def name
    "Snoopy"
  end
end

# The following line throws an exception
TestAccessLevels.new.say_my_name</code>
</pre>
<h4>Second class types</h4>
<p>Having special types, like null, is a special case of having primitives, and it&#8217;s a common performance optimization.  Being a <a href="http://en.wikipedia.org/wiki/First-class_object">first-class type</a> has a well-defined meaning.  Specifically, its instances can:</p>
<ul>
<li>be passed to functions as parameters</li>
<li>be returned from functions</li>
<li>be created and stored in variables</li>
<li>be created anonymously</li>
<li>be created dynamically</li>
</ul>
<p>It&#8217;s becoming increasingly common for modern languages to move towards first-class functions.  In the <a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html">Execution in the Land of the Nouns</a>, Steve Yegge parodied the typical transmogrifications Java programmers had accustomed themselves to in order to sidestep the language&#8217;s lack of first-class functions.  Java&#8217;s cousin (descendant?), C#, has <a href="/2007/11/05/using-closures-to-implement-undo">more or less</a> had them since .NET 2.0 in the form of anonymous delegates.</p>
<p>What neither Java nor C# have are first-class classes.  Both have reflection, and even allow you to create new types at runtime (painfully&#8230;).  But, because both languages are statically typed, you can&#8217;t access these runtime-created types the same way you can access normal types.  Assuming <code>Foo</code> is a runtime-created type, the following code won&#8217;t compile:</p>
<pre>
<code class="csharp">Foo foo = new Foo();</code>
</pre>
<p>The only way to make it work is by heavy use of reflection.  Ruby, on the other hand, makes it trivially easy to add types at runtime.  In fact, <em>all</em> types are added at runtime, since it&#8217;s an interpreted language.</p>
<h4>Single Return Values</h4>
<p>Since you can pass more than one argument <em>to</em> functions, why should you only be allowed to return one value <em>from</em> functions?  Languages like ML add orthogonality by returning tuples.  Ruby works similarly, unpacking arrays automatically for you if you use multiple lvalues in one expression.</p>
<pre>
<code class="ruby">def duplicate(value)
  [value, value]
end

first, second = duplicate("hi there")</code>
</pre>
<p>This feature allows you to combine lvalues and rvalues more consistently.</p>
<h4>Inconsistent Nesting</h4>
<p>Nesting is the standard programming trick of limiting scope, and most languages provide blocks that you can nest indefinitely if you want to limit scope.  For example, in C#:</p>
<pre>
<code class="csharp">public void TestNest()
{
    string outer = "outer";
    {
        string middle = "middle";
        {
            string inner = "inner";
        }
    }
}</code>
</pre>
<p>In addition to blocks, Ruby allows you to nest functions, but the nesting doesn&#8217;t work in an orthogonal way:</p>
<pre>
<code class="ruby">def outer
  inner_var = "inner variable"

  def inner
    "inner method"
  end
end

outer
puts inner
puts inner_var</code>
</pre>
<p>In this example, the last line will throw a <code>NameError</code>, complaining that <code>inner_var</code> is undefined.  This is as we should expect &#8211; since it&#8217;s defined inside an inner scope from where we&#8217;re calling it, we should not be able to access it.  However, the same is not true for the <code>inner</code> method defined in the call to <code>outer</code>.  Despite the fact that it&#8217;s defined within a nested scope, it actually has the same scoping as <code>outer</code>.</p>
<p>Ruby&#8217;s scoping gets even weirder:</p>
<pre>
<code class="ruby">def outer
  begin
    inner_var = "inner"
  end

  inner_var
end

puts outer</code>
</pre>
<p>This code works, printing &#8220;inner&#8221; to the console.  It shouldn&#8217;t.</p>
<p>JavaScript similarly suffers from strange scoping rules.  Because all variables have function scope, and not block scope, a variable is available everywhere within a function regardless of where it is defined:</p>
<pre>
<code class="javascript">function testScoping(predicate) {
  if (predicate) {
    var test = "in if block";    
  }
  alert(test);    // works, even though it's in an outer block
}</code>
</pre>
<h4>Fixing your mistakes</h4>
<p>Speaking of JavaScript, few things bug me more about programming languages than those that try to fix your mistakes for you.  JavaScript automatically appends semicolons for you at the end of a line if you forget to.  Most of the time, that works fine, but every now and then it creates a ridiculously hard bug to diagnose:</p>
<pre>
<code class="javascript">return
{
  value: 0
}</code>
</pre>
<p>The <code>return</code> statement above looks like it returns an object with a single property.  What it <em>really</em> does, though, is simply return.  The semicolon was appended on your behalf at the end of the <code>return</code> keyword, turning the following three lines into dead code.  It is for this reason that Douglas Crockford recommends always using K&#038;R style braces in JavaScript in <a href="http://oreilly.com/catalog/9780596517748/">JavaScript: The Good Parts</a>.</p>
<h4>Summary</h4>
<p>Orthogonality makes the language easier to extend in ways that the language implementors didn&#8217;t anticipate.  For example, Ruby&#8217;s first-class types, combined with its duck-typing, allows the popular mocking framework <a href="http://where">Mocha</a> to have a very nice syntax:</p>
<pre>
<code class="ruby">logger = stub
logger.expects(:error).with("Execution error")

do_something(:blow_up, logger)</code>
</pre>
<p>The fact that classes in Ruby are also objects means that the same syntax works for classes:</p>
<pre>
<code class="ruby">File.stubs(:exists?).returns(true)</code>
</pre>
<p>I picked on JavaScript a couple times, but it did a better job of any other language I know of with literals.  JavaScript has literal numbers and strings, like most languages.  It has literal regular expressions and lists like Perl and Ruby.  But where it really shines is in it&#8217;s literal object syntax.  Objects are basically dictionaries, and Ruby and Perl have hash literals, but JavaScripts objects include function literals:</p>
<pre>
<code class="javascript">function ajaxSort(columnName, sortDirection) {
    setNotice('Sorting...');
    new Ajax.Request("/reports/ajaxSort", {
            method: "get",
            parameters: { sort: columnName, sortDir: sortDirection },
            onSuccess: function (transport) { 
                $("dataTable").innerHTML = transport.responseText;
            },
            onComplete: function () { clearNotice(); }
        }
    );
}</code>
</pre>
<p>In time, that syntax was leveraged to form the JSON format.</p>
<p>In a more dramatic example, when object-orientation became all the rage, Lisp was able to add object-orientation to the language <em>without changing the language</em>.  The <a href="http://en.wikipedia.org/wiki/Common_Lisp_Object_System">Common Lisp Object System</a> (CLOS) is written entirely in Lisp.  The reason Lisp was able absorb an entire new paradigm is largely due to the language&#8217;s orthogonality.  Not all function-like calls work the same way; some are called &#8220;special forms&#8221; because they act differently (for example, by providing lazy evaluation of the arguments).  However, Lisp allows the programmer to create their own special forms by writing <a href="/2008/02/12/understanding-syntactic-macros">macros</a>, which are themselves written in Lisp.</p>
<p>It helps to have turtles all the way down.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/brandonbyars.wordpress.com/49/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/brandonbyars.wordpress.com/49/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/49/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/49/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=49&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2008/07/21/orthogonality/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Coding Values</title>
		<link>http://brandonbyars.com/2008/07/14/coding-values/</link>
		<comments>http://brandonbyars.com/2008/07/14/coding-values/#comments</comments>
		<pubDate>Mon, 14 Jul 2008 13:56:00 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Values]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I always enjoy reading Kent Beck&#8217;s books. In a way, they remind me of a poster my mom has hanging in her house: All I Really Need to Know I Learned in Kindergarten. With the frenzied pace of change in software development, it&#8217;s easy to forget about the basics. A good remedy for that is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=48&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I always enjoy reading Kent Beck&#8217;s books.  In a way, they remind me of a poster my mom has hanging in her house: <a href="http://www.peace.ca/kindergarten.htm">All I Really Need to Know I Learned in Kindergarten</a>.  With the frenzied pace of change in software development, it&#8217;s easy to forget about the basics.  A good remedy for that is to sit down and read one of Beck&#8217;s books.</p>
<p>Recently, I read <a href="http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091">Implementation Patterns</a>, and while I enjoyed <a href="http://www.amazon.com/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X/ref=pd_bbs_sr_1?ie=UTF8&#038;s=books&#038;qid=1216036677&#038;sr=1-1">Smalltalk Best Practice Patterns</a> more, I still got something out of the book (despite being neither a Java nor a Smalltalk developer).  As with XP, Beck explains his programming practices in terms of values and principles.  I always appreciated that, in <a href="http://www.amazon.com/Extreme-Programming-Explained-Embrace-Change/dp/0201616416">Extreme Programming Explained</a> (both editions), he not only described his values, but laid out concrete practices that embodied those values.  In <em>Implementation Patterns</em>, he takes a similar approach, claiming the three values of Communication, Simplicity, and Flexibility are what inspire his programming practices.</p>
<p>He describes them as listed in priority order.  Where they clash, which is rare, it is better to be communicative than overly simple.  And simplicity trumps flexibility.  Too much terrible software is written under the presupposition that it must be flexible.</p>
<p>What Beck did <em>not</em> write about were values that run counter-productive to quality code.  I tried coming up some as an exercise &#8211; those that I&#8217;ve witnessed in myself and others.  I was able to come up with the following:</p>
<h3>Ownership</h3>
<p>I&#8217;ve worked with one developer who held on to code he had written so tightly that, even after we had instituted a code-sharing policy, it took an enormous amount of effort to loosen his grip.  We&#8217;d go and refactor his code, and he&#8217;d come in after us and refactor it back.  We&#8217;d add functionality to his code, and he&#8217;d come in after us and change it.</p>
<p>There were certain very odd aspects of his behavior:</p>
<ul>
<li>His code was <em>really</em> bad, so it was strange that he resisted outside help so much</li>
<li>Even after we started rotating coding tasks to get people involved in parts of the code they had previously not touched, he showed little interest in actually <em>doing</em> any of those tasks</li>
<li>He didn&#8217;t care to hear any suggestions about how to improve the system where it involved changing &#8220;his&#8221; code, because, as he like to say, &#8220;it&#8217;s complicated.&#8221;</li>
</ul>
<p>His behavior ultimately got him fired, but not before he had time to leave a legacy of terrible code that others now struggle to maintain.  In his defense, his sense of ownership exhibited a high degree of pride and aesthetics.  Unfortunately, his sense of aesthetics was also quite poor, and his refusal to allow feedback meant that it&#8217;s unlikely improved much today.</p>
<h3>Cleverness</h3>
<p>I&#8217;ve found myself guilty of this sin a few too many times.  Cleverness often manifests itself in extraordinarily terse code, using some backdoor of the language.  It&#8217;s become pass&eacute; these days to show off clever Ruby code, as it once was in Perl, but overly clever solutions can be found in all languages.</p>
<p>A related value is Knowledge, or the verisimilitude thereof.  Often I find myself (or others) eager to show off that they know obscure parts of a language and use them for some temporary benefit.  Knowledge-Show-Offs are easy to spot: look for phrases like &#8220;verisimilitude thereof.&#8221;</p>
<p>Both Ownership and Cleverness run counter to Beck&#8217;s primary value of Communication.</p>
<h3>Comfort</h3>
<p>How often have you seen C code in Java?  Or Java code in Ruby?  We are creatures of habit, and it often takes a conscious effort to break out of your comfort zone.  Too often, we hold on to old ideas because they&#8217;re comfortable ideas, and label new ideas as &#8220;passing fads,&#8221; a particularly common slur in our industry.</p>
<p>Why is it so hard to make unit testing mainstream?  Why don&#8217;t more people pair program?  Both practices remove people from their comfort zone, and require learning a new way of programming.</p>
<p>Note that none of these values are bad in the general sense.  I&#8217;d like to feel a sense of ownership about my work, to be clever, and to feel comfortable.  But values collide, and we need to understand that certain values are more applicable in certain aspects of our lives than others.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/brandonbyars.wordpress.com/48/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/brandonbyars.wordpress.com/48/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/48/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/48/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=48&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2008/07/14/coding-values/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Beating Sapir-Whorf</title>
		<link>http://brandonbyars.com/2008/05/13/beating-sapir-whorf/</link>
		<comments>http://brandonbyars.com/2008/05/13/beating-sapir-whorf/#comments</comments>
		<pubDate>Wed, 14 May 2008 05:09:00 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[The Sapir-Whorf hypothesis is a famous linguistic theory that postulates that what you think is constrained by what you can say. In other words, the way you understand the world is limited by the language(s) you speak. The hypothesis is regarded as incorrect by modern linguists. However, the spirit of the theory appears to be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=47&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>The <a href="http://en.wikipedia.org/wiki/Sapir-Whorf_hypothesis#Computer_coding_language_conceptual_correlate">Sapir-Whorf hypothesis</a> is a famous linguistic theory that postulates that what you think is constrained by what you can say.  In other words, the way you understand the world is limited by the language(s) you speak.</p>
<p>The hypothesis is regarded as incorrect by modern linguists.  However, the spirit of the theory appears to be largely true if we refer only to computer languages &#8211; our solution space is limited to the number of ways we know to express solutions.  Paul Graham was indirectly talking about Sapir-Whorf when he described the <a href="http://www.paulgraham.com/avg.html">Blub Paradox</a>.  Blub, the language that sits halfway up the hypothetical totem pole that represents the relative power of computer languages, has certain constructs that make languages lower on the pole seem downright dysfunctional.  The Blub programmer would look down, realize that the language he&#8217;s looking at doesn&#8217;t even have some language feature X, and scoff at how much extra work it would be to write programs without X.  X, the Blub programmer argues, is so fundamental to designing your application that it would criminal to use any languages without X.</p>
<p>When the Blub programmer looks up the totem pole, though, he just sees weird languages.  What he doesn&#8217;t realize, of course, is that programmers in those languages are looking down at Blub and wondering how anybody could possibly program without language feature Y.</p>
<p>The Blub paradox makes a nice story, and while it has value, it oversimplifies the language landscape.  There isn&#8217;t a linear totem pole for expressive power when it comes to languages.  Graham suggests looking at the size of the parse tree, which is indeed a useful single metric, but ignores aspects like long-term maintainability, readability, syntactic sugar, etc.  The computer language landscape is diverse precisely because there are different opinions on the best way to solve different problems.</p>
<p>What should be obvious is that not all software problems should be solved with the same tool.  Too many programmers go down that path, and use Java (or C#, or C++&#8230;) as the hammer and let everything become a nail.</p>
<p>Granted, we don&#8217;t always have control over which language we use.  We write programs in Java (or C#, or C++&#8230;) because that&#8217;s our job, even though we may suspect that it&#8217;s not always the best tool.  Fair enough.  But if our ability to describe solutions to a problem is constrained by the programming languages we know, doesn&#8217;t it make sense to learn other languages even if we <em>can&#8217;t</em> use them on the job?</p>
<p>Knowing a diverse set of programming paradigms can help you become a better programmer.  It&#8217;s helped me.  For example, I wrote a <a href="/2007/11/05/using-closures-to-implement-undo">closure-based undo</a> in C#.  A more typical OO-based undo would have resorted to the <a href="http://en.wikipedia.org/wiki/Command_pattern">command design pattern</a>, but the closure-based implementation required much fewer changes to the codebase.  I don&#8217;t think I would have come up with the solution if I had not had some prior exposure to functional languages.</p>
<p>The key is to make sure that when you pick up a new language, that it&#8217;s different <em>enough</em> from languages you already know that you force yourself to wrap your head around some new concept.  You don&#8217;t get that, for instance, going from Java to C#.  I&#8217;ve tried learning at least a little about several languages, and found useful new concepts in the following:</p>
<p>In the object-oriented space:</p>
<ul>
<li>C# / Java (statically typed OO)</li>
<li>Eiffel (design-by-contract, anchored types)</li>
<li>Ruby (open classes, incredible reflection, metaprogramming)</li>
<li>Smalltalk (like Ruby, but with keyword arguments and a very lightweight syntax)</li>
</ul>
<p>In the hybrid OO space</p>
<ul>
<li>Perl / Python (dynamic typing, default variables, list comprehensions)</li>
<li>C++ / Delphi (destructors)</li>
<li>JavaScript (prototypes instead of classes, hybrid functional)</li>
</ul>
<p>In the procedural space:</p>
<ul>
<li>C (weak typing, systems level procedural, teaches good understanding of computer memory)</li>
</ul>
<p>In the functional space:</p>
<ul>
<li>Scheme / Common Lisp (homoiconic, syntactic macros, multiple dispatch, continuations, no penalty for tail recursion)</li>
<li>Erlang (nice distributed model, pattern matching)</li>
</ul>
<p>In the &#8220;everything-else&#8221; space:</p>
<ul>
<li>shell scripting (using processes as the unit of abstraction)</li>
<li>SQL (yes, even the much-maligned relational, set-based model provides another, occasionally superior, way of solving problems)</li>
<li>XSLT (declarative)</li>
</ul>
<p>In the &#8220;I wish I could speak intelligently about&#8221; space:</p>
<ul>
<li>Prolog (propositional logic programming)</li>
<li>Forth (stack-based programming)</li>
</ul>
<p><a href="http://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X/ref=pd_bbs_sr_1?ie=UTF8&#038;s=books&#038;qid=1210523355&#038;sr=8-1">PragDave</a> recommends that you learn a new programming language each year.  It&#8217;s terrific advice.  Pick a language, find some coding exercises, and try to wrap your head around solving those problems idiomatically in the new language.  Don&#8217;t be surprised if you start out solving them the same way you would have in a language you already knew, but remember the end goal is to learn new problem solving techniques, not just new syntax.  Since you probably won&#8217;t be using the language on the job, you&#8217;ll almost certainly forget the syntax after a while.  Start posting questions to mailing lists, blog about some of your sample work, and don&#8217;t be afraid to make a fool of yourself.  The way I see it, if you&#8217;re still afraid to make a fool of yourself, then you clearly haven&#8217;t made a fool of yourself enough.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/brandonbyars.wordpress.com/47/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/brandonbyars.wordpress.com/47/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/47/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/47/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=47&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2008/05/13/beating-sapir-whorf/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
		<item>
		<title>Code Generation and Metaprogramming</title>
		<link>http://brandonbyars.com/2008/03/29/code-generation-and-metaprogramming/</link>
		<comments>http://brandonbyars.com/2008/03/29/code-generation-and-metaprogramming/#comments</comments>
		<pubDate>Sun, 30 Mar 2008 00:00:00 +0000</pubDate>
		<dc:creator>Brandon Byars</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Code Generation]]></category>
		<category><![CDATA[Lisp]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Macros]]></category>
		<category><![CDATA[Metaprogramming]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I wanted to expand upon an idea that I first talked about in my previous post on Common Lisp. There is a common pattern between syntactic macros, runtime metaprogramming, and static code generation. Runtime metaprogramming is code-generation. Just like C macros. Just like CL macros. Ok, that&#8217;s a bit of an overstatement. Those three things [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=45&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I wanted to expand upon an idea that I first talked about in my previous post on <a href="/2008/02/12/understanding-syntactic-macros">Common Lisp</a>.  There is a common pattern between syntactic macros, runtime metaprogramming, and static code generation.</p>
<p>Runtime metaprogramming is code-generation.  Just like C macros.  Just like CL macros.</p>
<p>Ok, that&#8217;s a bit of an overstatement.  Those three things aren&#8217;t <em>really</em> just like each other.  But they are definitely related&#8212;they all write code that you&#8217;d rather not write yourself.  Because it&#8217;s boring.  And repetitious.  And ugly.</p>
<p>In general, there are three points at which you can generate code in the development process, although the terminology leaves something to be desired: before compilation, during compilation (or interpretation), and during runtime.  In the software development vernacular, only the first option is typically called code-generation (I&#8217;ll call it static code generation to avoid confusion).  Code generation during compilation goes under the moniker of a &#8216;syntactic macro,&#8217; and I&#8217;m calling runtime code generation &#8216;runtime metaprogramming.&#8217;</p>
<p>Since the &#8220;meta&#8221; in metaprogramming implies writing code that writes code, all three forms of code generation can be considered metaprogramming, which is why I snuck the &#8220;runtime&#8221; prefix into the third option above.  Just in case you were wondering&#8230;</p>
<h3>Static Code Generation</h3>
<p>Static code generation is the easiest to understand and the weakest of the three options, but it&#8217;s often your only option due to language limitations.  C macros are an example of static code generation, and it is the only metaprogramming option possible with C out-of-the box.</p>
<p>To take an example, on a previous project I generated code for lazy loading proxies in C#.  A proxy, one of the standard GoF design patterns, sits in between a client and an object and intercepts messages that the client sends to the object.  For lazy loading, this means that we can instantiate a proxy in place of a database-loaded object, and the client can use it without even knowing that it&#8217;s using a proxy.  For performance reasons, the actual database object will only be loaded on first access of the proxy.  Here&#8217;s a truncated example:</p>
<pre>
<code class="csharp">public class OrderProxy : IOrder
{
    private IOrder proxiedOrder = null;
    private long id;
    private bool isLoaded = false;

    public OrderProxy(long id)
    {
        this.id = id;
    }

    private void Load()
    {
        if (!isLoaded)
        {
           proxiedOrder = Find();
           isLoaded = true;
        }
    }

    private IOrder Find()
    {
        return FinderRegistry.OrderFinder.Find(id);
    }

    public string OrderNumber
    {
        get
        {
           Load();
           return proxiedOrder.OrderNumber;
        }
        set
        {
           Load();
           proxiedOrder.OrderNumber = value;
        }
    }

    public DateTime DateSubmitted
    {
        get
        {
           Load();
           return proxiedOrder.DateSubmitted;
        }
    }
}</code>
</pre>
<p>This code is boring to write and boring to maintain.  Every time the interface changes, a very repetitious change has to be made in the proxy.  To make it worse, we have to do this for <em>every</em> database entity we&#8217;ll want to load (at least those we&#8217;re worried about lazy-loading).  All I&#8217;d really like to say is &#8220;make this class implement the appropriate interface, and make it a lazy-loading proxy.&#8221;  Fortunately, since the proxy is supposed to be a drop-in replacement for any other class implementing the same interface, we can use reflection to query the interface and statically generate the proxy.</p>
<p>There&#8217;s an important limitation to generating this code statically.  Because we&#8217;re doing this before compilation, this approach requires a separated interfaces approach, where the binary containing the interfaces is separate from the assembly we&#8217;re generating the proxies for.  We&#8217;ll have to compile the interfaces, use reflection on the compiled assembly to generate the source code for the proxies, and compile the newly generated source code.</p>
<p>But it&#8217;s do-able.  Simply load the interface using reflection:</p>
<pre>
<code class="csharp">public static Type GetType(string name, string nameSpace, string assemblyFileName)
{
    if (!File.Exists(assemblyFileName))
        throw new IOException("No such file");

    Assembly assembly = Assembly.LoadFile(Path.GetFullPath(assemblyFileName));
    string qualifiedName = string.Format(“{0}.{1}”, nameSpace, name);
    return assembly.GetType(qualifiedName, true, true);
}</code>
</pre>
<p>From there it&#8217;s pretty trivial to loop through the properties and methods and recreate the source code for them on the proxy, with a call to <code>Load</code> before delegating to the proxied object.</p>
<h3>Runtime Metaprogramming</h3>
<p>Now it turns out that when I wrote the code generation code above, there weren&#8217;t very many mature object-relational mappers in the .NET space.  Fortunately, that&#8217;s changed, and the code above is no longer necessary.  <a href="http://www.hibernate.org/343.html">NHibernate</a> will lazy-load for you, using a similar proxy approach that I used above.  Except, NHibernate will write the proxy code <em>at runtime</em>.</p>
<p>The mechanics of how this work are encapsulated in a nice little library called <a href="http://www.castleproject.org/dynamicproxy/index.html">Castle.DynamicProxy</a>.  NHibernate uses reflection to read interfaces (or virtual classes) and calls DynamicProxy to runtime generate code using the <code>Reflection.Emit</code> namespace.  In C#, that&#8217;s a difficult thing to do, which is why I wouldn&#8217;t recommend doing it unless you use DynamicProxy.</p>
<p>This is a much more powerful technique than static code generation.  For starters, you no longer need two assemblies, one for the interfaces, and one for the proxies.  But the power of runtime metaprogramming extends well beyond saving you a simple .NET assembly.</p>
<p>Ruby makes metaprogramming much easier than C#.  The standard Rails object-relational mapper also uses proxies to manage associations, but the metaprogramming applies even to the model classes themselves (which are equivalent to the classes that implement our .NET interfaces).  The truncated <code>IOrder</code> implementation above showed 3 properties: <code>Id</code>, <code>OrderNumber</code>, and <code>DateSubmitted</code>.  Assuming we have those columns in our <code>orders</code> table in the database, then the following Ruby class <em>completely</em> implements the same interface:</p>
<pre>
<code class="ruby">class Order &lt; ActiveRecord::Base
end</code>
</pre>
<p>At runtime, The <code>ActiveRecord::Base</code> superclass will load the schema of the <code>orders</code> table, and for each column, add a property to the <code>Order</code> class of the same name.  Now we really see the power of metaprogramming: it helps us keep our code DRY.  If it&#8217;s already specified in the database schema, why should we have to specify it in our application code as well?</p>
<h3>Syntactic Macros</h3>
<p>It probably wouldn&#8217;t make much sense to generate lazy-loading proxies at compile time, but that doesn&#8217;t mean syntactic macros don&#8217;t have their place.  Used appropriately, they can DRY up your code in ways that even runtime metaprogramming cannot.</p>
<p><a href="http://www.gigamonkeys.com/book/">Peter Seibel</a> gives a good example of building a unit test framework in Common Lisp.  The idea is that we&#8217;d like to assert certain code is true, but also show the asserted code in our report.  For example:</p>
<pre>
<code>pass ... (= (+ 1 2) 3)
pass ... (= (+ 1 2 3) 6)
pass ... (= (-1 -3) -4)</code>
</pre>
<p>The code to make this work, assuming <code>report-result</code> is implemented correctly, looks like this:</p>
<pre>
<code class="commonlisp">(defun test-+ ()
  (report-result (= (+ 1 2) 3) '(= (+ 1 2) 3))
  (report-result (= (+ 1 2 3) 6) '(= (+1 2 3) 6))
  (report-result (= (+ -1 -3) -4) '(= (+ -1 -3) -4)))</code>
</pre>
<p>Notice the ugly duplication in each call to <code>report-result</code>.  We have the code that&#8217;s actually executed (the first parameter), and the quoted list to report (the second parameter).  Runtime metaprogramming could not solve the problem because the first parameter will be evaluated before being passed to <code>report-result</code>.  Static code-generation <em>could</em> remove the duplication, but would be ugly.  We could DRY up the code at compile time, if only we had access to the abstract syntax tree.  Fortunately, in CL, the source code is little more than a textual representation of the AST.</p>
<p>Here&#8217;s the macro that Seibel comes up with:</p>
<pre>
<code class="commonlisp">(defmacro check (&amp;body forms)
  `(progn
    ,@(loop for f in forms collect `(report-result ,f ',f))))</code>
</pre>
<p>Notice how the source code within the list (represented as the loop variable <em>f</em>) is both executed and quoted.  The test now becomes much simpler:</p>
<pre>
<code class="commonlisp">(defun test-+ ()
  (check (= (+ 1 2) 3))
  (check (= (+ 1 2 3) 6))
  (check (= (+ -1 -3) -4)))</code>
</pre>
<h3>Summary</h3>
<p>Finding ways to eliminate duplication is always A Good Thing.  For a long time, if you were programming in a mainstream language, then static code generation was your only option when code generation was needed.  Things changed with the advent of reflection based languages, particularly when Java and C# joined the list of mainstream languages.  Even though their metaprogramming capability isn&#8217;t as powerful as languages like Smalltalk and Ruby, they at least introduced metaprogramming techniques to the masses.</p>
<p>Of course, Lisp has been around since, say, the 1950&#8217;s (I&#8217;m not sure how long macros have been around, however).  Syntactic macros provide a very powerful way of generating code, even letting you change the language.  But until more languages implement them, they will never become as popular as they should be.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/brandonbyars.wordpress.com/45/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/brandonbyars.wordpress.com/45/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brandonbyars.wordpress.com/45/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brandonbyars.wordpress.com/45/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brandonbyars.com&#038;blog=16817319&#038;post=45&#038;subd=brandonbyars&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brandonbyars.com/2008/03/29/code-generation-and-metaprogramming/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/af39d2aa33b25424499beea2d3dda8a9?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">brandonbyars</media:title>
		</media:content>
	</item>
	</channel>
</rss>