<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[searls]]></title><description><![CDATA[the software blog of @searls]]></description><link>http://searls.testdouble.com</link><generator>NodeJS RSS Module</generator><lastBuildDate>Fri, 21 Jun 2013 16:04:10 GMT</lastBuildDate><atom:link href="http://searls.testdouble.com/index.xml" rel="self" type="application/rss+xml"/><item><title><![CDATA[unrequired love - a discussion on javascript and dependency management]]></title><description><![CDATA[<p>This post presumes you&#39;re familiar with the concept of tools that introduce a module format (whether it&#39;s <a href="http://requirejs.org">Require.js</a>, <a href="http://browserify.org">Browserify</a>, or something else) to JavaScript code that runs in the browser. I&#39;ll arbitrarily refer to the over-arching meme as capital-R &quot;Require&quot; for the rest of this post.</p>
<p>Also, keep in mind that this post is only discussing &quot;JavaScript that runs in browsers&quot;. It&#39;s not at all concerned with Node.js or npm or anything having to do with dependency management of JavaScript in that ecosystem.</p>
<h1>ground rule</h1>
<p>Because lots of people use Require and report back that they&#39;re getting a lot of value out of it, I think it&#39;s important to lay down a quick ground rule before I dive into this post:</p>
<p><strong>There are are many ways to write working software.</strong></p>
<p>Arguments about some tool X that follow &quot;X saved my life!&quot;, &quot;I didn&#39;t have a need for X&quot;, or &quot;X is bad and people who like it should feel bad&quot; are generally <em>not constructive</em>, because—since there are so many ways to write working software—they&#39;re all unfalsifiable claims. That is to say, without knowing every detail of one&#39;s situation and experience, there&#39;s usually no reasonable way to disprove such a statement.</p>
<p>If you&#39;re using Require and it&#39;s helping you deliver great software, then rock on! That&#39;s fantastic. Please keep diving deeper into whatever you do that&#39;s working, and keep searching wider for even better methods.</p>
<h1>Require is not required</h1>
<p>Given that there are many ways to write working software, it should be obvious that working JavaScript-heavy web applications <em>can and are</em> being written without adopting a 3rd-party dependency management system. In fact, I&#39;ve written some of them!</p>
<p>Because Require seems to have gained so much mindshare this year, I want to spend a few paragraphs exploring my (Require-free) experience to help establish context, then ask some open questions about what value people see in Require, and finally spin a few of my own crackpot conspiracy theories about what&#39;s driving Require&#39;s success.</p>
<h1>my own experience</h1>
<p>For some context before talking about Require, I&#39;ll talk about the basic structure of most of the JavaScript code I write. The punchline is that in spite of not using Require, I really love almost every aspect of my client-side application development. I simply don&#39;t find myself yearning for a third-party dependency management tool.</p>
<h2>tiny units</h2>
<p>I write <em>really tiny units</em> (whether the unit being considered is a framework&#39;s pseudo-class, an anonymous object, or a bag of functions). Usually every method is less than five lines, every file is less than forty lines, and every unit has at most three or four dependencies on other units.</p>
<h2>namespaces</h2>
<p>I build a namespace as I grow my code and attach it to the window. I usually use my little <a href="https://github.com/searls/extend.js/">extend.js</a> library to build namespaces as I go. I pick some brief top-level namespace based on the app name (like &quot;ou&quot; for an app called &quot;Oh, You!&quot;) and then I drill-down from there.</p>
<p>For instance, if I was going to declare a new calculator for an invoice report, I might do this:</p>
<pre><code class="lang-coffeescript">extend(<span class="string">'ou.reports.invoices.CalculatesTotals'</span>, <span class="reserved">function</span>(){
  <span class="regexp">//</span> imagine an awesome constructor <span class="reserved">function</span> here
  <span class="regexp">//</span> ...
})</code></pre>
<p>When extend.js is invoked with a namespace, it will ensure that <code>window.ou.reports.invoices</code> is a JavaScript object, then it will set onto it a property named <code>CalculatesTotals</code> with the supplied function (which could just as well be an object, or CoffeeScript class, or arbitrary value). The important part is that it won&#39;t matter what order this file appears in the concatenated source; it should work so long as it&#39;s loaded after any 3rd-party vendor libs.</p>
<p>As a result, in a typical large application, the order that scripts are loaded in will usually only matter to two or three (non-third party) files.</p>
<p>Aside from defusing a lot of the risk that load order might otherwise pose, this (very simple and hardly novel) approach to namespacing has a few advantages:</p>
<ul>
<li>It&#39;s eminently greppable. If I want to access the <code>CalculatesTotals</code> function in the future, I&#39;m probably going to use its fully-qualified name, and I&#39;m <em>certainly</em> going to refer to it as <code>CalculatesTotals</code>. This means I&#39;ll always be able to find all references to it in my codebase. (I mention this because I&#39;ve seen Require used to greatly decrease the greppability of code references because one could write <code>totalCalculator = require(&#39;path/to/calculates_totals&#39;)</code>, which would make refactoring more error-prone.)</li>
<li>Files can be split up in a more granular fashion than individual objects. If I were to have one file add some functions to an object with <code>extend(&#39;uo.util.sigh&#39;, {add: function(){}})</code>, I could add more functions to the same namespace from some other file by calling <code>extend(&#39;uo.util.sigh&#39;, {subtract: function(){}})</code> (extend.js will just merge the objects). This is only of moderate utility, but can be really handy during extract &amp; contract refactor operations where needing to keep units &amp; files in lock-step is inconvenient.</li>
</ul>
<h2>feedback-driven code design</h2>
<p>I&#39;m really mindful of how each unit depends on each other unit in the systems I write. Out-of-the-blue references to an object property-chain as lengthy as <code>uo.reports.invoices.CalculatesTotal</code> <em>feel weird</em> when they&#39;re littered all over a file listing. I appreciate that discomfort, because it forces me to be more thoughtful about my design (whether my reaction will be to decrease the unit&#39;s collaborator-count or to inject dependencies as opposed to always explicitly referencing them).</p>
<p>When a load-order bug arises that&#39;s above-and-beyond the namespacing strategy above, I know that means <em>I have a code design problem</em>, and I use that bug as feedback that I need to clean up how my units relate to one another at runtime. I&#39;m very confident that this particular design pressure has resulted in better-factored code, particularly code concerned with application initialization that runs as the page finishes loading.</p>
<h2>minimal 3rd party dependencies</h2>
<p>As I&#39;ve grown more skilled with JavaScript, the number of tools I keep in my toolbox has gotten smaller, not bigger. I have a handful of libraries I typically reach for, but I&#39;ve written large applications having only accumulated five or six 3rd party libraries over the course of months.</p>
<p>Not surprisingly, folks who are less proficient with JavaScript tend to grasp eagerly to third party libraries to solve the problems that they encounter, for lack of any alternative. If my app had dozens of uncontrolled third-party libraries all trampling on the global namespace, then a formal module system would probably appeal more to me. As it is, I actually consider as <em>healthy</em> the pressure to hesitate before adding third party libraries. (Besides, the best libraries have a no-conflict mode that yields the namespace control back to the user.)</p>
<h2>lots of tests</h2>
<p>I love test-driving all those tiny JavaScript units. I personally use Jasmine and a concoction of Jasmine helpers I&#39;ve written. I&#39;m not even sure why this should be relevant to the discussion of Require, but for the fact I seem to get a lot of e-mail and Github Issues from people trying (and struggling) to use various testing and build tools in the context of apps that use Require.</p>
<h2>great build tools</h2>
<p>At <a href="http://testdouble.com">test double</a>, we wrote <a href="http://www.linemanjs.com">Lineman</a> to be a hassle-free way to write fat-client JavaScript apps. It finds and concatenates all of my source files, so I don&#39;t have to. I typically don&#39;t configure a thing, I just create files and keep working. Whenever I veer off the beaten path, I might have to configure a change in the load order, but it&#39;s usually only something I encounter once or twice a month (and hardly a big enough pain to warrant orienting my entire application around Require).</p>
<h1>open questions</h1>
<p>I&#39;m curious why so many folks adopt Require, especially when they do so on their first JavaScript rodeo.</p>
<h2>what value does it add for you?</h2>
<p>Given everything I&#39;ve said above, I&#39;m really curious to know:</p>
<p><em>What value does Require provide that isn&#39;t also met by the (pretty minimal) safeguards I put in place for myself, which I detailed above?</em></p>
<p>I&#39;d love to see a response post that specifically addresses what <em>someone like me</em> would get out of using Require that I&#39;m currently not getting some other way. Whatever that benefit is, I&#39;ve so far failed to find it.</p>
<h2>why break from the default?</h2>
<p>A whole bunch of testing, productivity, build, and deploy tools don&#39;t work out-of-the-box with Require. I know, because I maintain a few of them! I feel nothing but sympathy for novice JavaScript developers that open issues while trying to figure out how to use a tool in conjunction with Require, but my more immediate impulse is to ask <em>why</em>?</p>
<p><em>Why adopt a not-yet-standard approach to developing client-side apps, when every tool and morsel of information you seek will need to be framed within the constraints that Require places on you? Especially if you&#39;re new enough to JavaScript that you&#39;re not capable of working around the corner cases on your own, why make life more difficult for yourself?</em></p>
<p>I think about this a lot, because I&#39;ve found the easiest way to write great code in any given ecosystem is to choose my battles carefully. In general, going with the flow and following defaults &amp; conventions frees me up to spend my intelligence capital on harder, more worthwhile questions.</p>
<p>As a result, if a true AMD standard were to emerge and browsers all incorporated it, I&#39;d absolutely adopt it—even if it was crap! I&#39;ve convinced myself to love JavaScript (well, CoffeeScript) in spite of its myriad flaws, because I know it&#39;s the only show in town if I want to build great experiences on the web. I&#39;d do the same if a standard packaging &amp; dependency management system were to emerge for the browser. (And I hope one does, because having a ubiquitous system for packaging, discovering, and resolving dependencies could drastically improve the infrastructure of the web.)</p>
<h1>conspiracy theories</h1>
<p>All of my conspiracy theories as to why Require has become popular are rooted in a suspicion that folks are <strong>cargo-culting</strong> the dependency management systems from languages with which they&#39;re more familiar.</p>
<p>The reason I bring up cargo-culting is that most of the developers I see embracing Require are actually <em>novice</em> JavaScript developers coming from another programming ecosystem. This realization was the impetus of my concern that what Require actually addresses is a gap in the understanding of many inexperienced JavaScript developers.</p>
<h2>misunderstood weirdness</h2>
<p>Everyone knows that JavaScript is weird in relation to other languages, but few can articulate clearly <em>how</em> it is weird. Without clearly understanding what makes JavaScript unusual, it&#39;s not surprising that folks exert a lot of effort to attempt to normalize it to meet their expectations.</p>
<p>In this instance, the oddity that Require attempts to normalize is that <em>a JavaScript application is equivalent to the concatenation of its source files</em>.</p>
<p>If you aren&#39;t fully cognizant of this aspect of JavaScript&#39;s relationship with the browser, then the prospect of going back to a more familiar code organization mechanism would certainly be appealing! That said, I&#39;ve found this very simple rule to be a liberating constraint. I&#39;m able to visualize front-end JavaScript applications much more efficiently from this frame of mind than I can of the import/require schemes made possible by Java&#39;s classpath and Ruby&#39;s load paths.</p>
<h2>tool envy</h2>
<p>Another conspiracy theory of mine is that Require doesn&#39;t solve any &quot;real&quot; problem that can&#39;t also be solved with a better understanding of JavaScript, and that in general the masses would far prefer to be handed a tool than to be asked to think harder. In this case, that problem being how to design code that&#39;s load-order agnostic and doesn&#39;t abuse the global namespace.</p>
<p>In software, we see <a href="http://www.infoq.com/presentations/Simple-Made-Easy">convenience beat simplicity</a> in mindshare all the time, so it&#39;s valuable to be mindful of which is being offered by any given tool or method.</p>
<p>In my own experience, any time I&#39;ve been faced with solving a problem through either (a) &quot;greater understanding&quot; or (b) &quot;adoption of a tool&quot;, the increased time investment required by the former has always paid off, whereas the initial convenience of the latter has always cost me down the road. As a result, unless Require solves a problem that&#39;s not also solved by &quot;thinking harder about the design of my code&quot;, I wouldn&#39;t feel an urgency to adopt it.</p>
<h2>unabashed cargo-culting</h2>
<p>While the previous two examples are derived from the impulse to carry our practices from one ecosystem to another (even if they don&#39;t jive with the standards and conventions of the target ecosystem), I think there&#39;s a nontrivial number of people who just hate JavaScript and will adopt anything that makes it feel less like JavaScript. I hereby dub this &quot;unabashed&quot; cargo-culting.</p>
<p>That is to say that such people are entirely aware that they&#39;re trying to impose their will on a foreign ecosystem and have made up their mind as to the appropriateness and effectiveness of such a strategy. Require definitely makes JavaScript feel more like (most) other environments, and if that&#39;s someone&#39;s chief consideration, they won&#39;t mind paying the price of either a higher cognitive load or tool compatibility issues.</p>
<p>There&#39;s really not much more to say about or to this group, as I doubt I&#39;m going to convince them to spend time soaking in JavaScript and learning to love working in the browser.</p>
<h1>conclusion</h1>
<p>One of the reasons this issue doesn&#39;t sit well with me is that I see a lot of people advocating Require to others, but for their own benefit and not for the benefit of the listener. It often feels like Require&#39;s fans push for greater adoption in hopes of more first-class support among third-party libraries or more AMD-awareness to be built-into front-end tooling. That wouldn&#39;t bother me so much if Require&#39;s value proposition was overwhelming and clear, but it really isn&#39;t for me.</p>
<p>All of the above said, I&#39;m very much open to persuasion. Consider this post an open invitation to try to sway me on this issue. Feel free to shoot me an <a href="mailto:justin@testdouble.com">e-mail</a>, <a href="http://twitter.com/searls">tweet at me</a>, or author a response post and send me a link. If you do, I&#39;ll have been super grateful for your time and thoughts!</p>
]]></description><link>http://searls.testdouble.com/posts/2013-06-16-unrequired-love.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2013-06-16-unrequired-love.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Sun, 16 Jun 2013 00:00:00 GMT</pubDate></item><item><title><![CDATA[jasmine tactics screencast]]></title><description><![CDATA[<p>Today, I had the good fortune to visit my friends at <a href="http://seesparkbox.com">Sparkbox</a>, where they host a Dayton JavaScript user group called <a href="http://gemcityjs.com/">Gem City JS</a>. Today, I showed up to share some perspective on how to test JavaScript with Jasmine.</p>
<p>Folks have been asking me to share a screencast of how I write Jasmine tests for a few years, so I recorded the session and am providing it online, completely unedited:</p>
<div class="hd-video">
<div class="video-container">
  <iframe width="1280" height="720" src="http://www.youtube.com/embed/PWHyE1Ru4X0?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
</div>

<p>This screencast (<a href="http://www.youtube.com/watch?v=PWHyE1Ru4X0">YouTube</a>) is merely a conversation to provide an answer to the question, &quot;Hey Justin, how would you write a test for <em>__</em> JavaScript code?&quot; where that blank might be filled with &quot;interacting with the DOM&quot;, or &quot;binding user events&quot;, or &quot;making AJAX requests&quot;. I cover each of those in a way that&#39;s similar to how I do it today; I trust that in six months, I&#39;ll have evolved and changed my tastes somewhat, but this reflects where I&#39;m at right now.</p>
<p>It&#39;s a pretty thorough stream of consciousness—in fact, it&#39;s nearly <strong>feature-length</strong>. That&#39;s pretty long for a web video, but if you&#39;ve struggled to figure out how to write tests for real-world JavaScript (or, if you&#39;re just interested in getting inside the head of someone else on the topic), then perhaps 75 minutes will be a reasonable investment of your time.</p>
<h2>overview</h2>
<p>Now, a few brief notes on the presentation itself.</p>
<p>First, the sample code is hosted on Github at <a href="https://github.com/searls/refactor-to-backbone-example">searls/refactor-to-backbone-example</a>. The anonymous jQuery and the Backbone specs can be found on the <code>master-specs</code> and <code>backbone-specs</code> branches, respectively. The application is a Lineman app, and you can find out how to install and run it on <a href="https://github.com/testdouble/lineman">Lineman&#39;s README</a>.</p>
<p>Second, the presentation is not intended to discuss the values and virtues of either the broader topic of unit testing or these particular tests. Instead, my primary goal was to convey <em>specific testing tactics</em> that can be employed to write <em>unit</em> tests for common JavaScript patterns. It&#39;s absolutely the case that some of these tests aren&#39;t particularly valuable, but the skill to be able to write them absolutely is.</p>
<p>Finally, there&#39;s a logical division that isn&#39;t apparent as the video begins, so I&#39;ll provide some overview. The first half focuses on going through the <em>admittedly arduous</em> process of characterizing a big ball of anonymous JavaScript with Jasmine tests. The code under test is crufty, so the tests are naturally painful to write—even to me, with several years of daily experience writing Jasmine.</p>
<p>The second half of the presentation is intended to serve as a contrast, because here it&#39;s spent characterizing code that&#39;s at least been broken up into small(er) units with a named, usable API. In what should shock no one, slightly simpler units lead to slightly simpler tests. This codebase could use even more refactoring, but that&#39;s beyond the scope of this discussion.</p>
<h2>libraries</h2>
<p>I used and described several libraries during the presentation, you can find them here:</p>
<ul>
<li><a href="https://github.com/searls/jasmine-fixture">jasmine-fixture</a></li>
<li><a href="https://github.com/searls/jasmine-given">jasmine-given</a></li>
<li><a href="https://github.com/searls/jasmine-stealth">jasmine-stealth</a></li>
<li><a href="https://github.com/testdouble/lineman">Lineman</a></li>
<li>included with Lineman, <a href="https://github.com/airportyh/testem">testem</a></li>
</ul>
]]></description><link>http://searls.testdouble.com/posts/2013-03-21-jasmine-tactics-screencast.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2013-03-21-jasmine-tactics-screencast.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Thu, 21 Mar 2013 00:00:00 GMT</pubDate></item><item><title><![CDATA[an includes trap]]></title><description><![CDATA[<p>Funny how just this week I felt compelled to <a href="/2013/01/21/explicit-vs-implicit-knowledge">blog about implicit knowlege</a>, because a terrific example of the possible consequences of too much implicit knowledge came up yesterday.</p>
<p>Please forgive me for the length of this post, because this is a surprisingly subtle problem. As with most subtle problems, the context and relevant background knowledge are necessary to arrive at a clear understanding of both the problem itself and the causes.</p>
<h1>rails background</h1>
<p>Ruby on Rails&#39; applications are well-known for being addled with implicit knowledge. The framework itself aims to increase productivity and developer happiness by moving many pieces of knowledge out of the application&#39;s source code and into our collective consciousness. Much of this was made possible by Ruby&#39;s flexibility, by way of its introspection capabilities (like <code>define_method</code> and <code>method_missing</code>). Even more of this was made possible by establishing a conventional approach to most common tasks. Put another way, to most frameworks, writing no code results in no behavior; in frameworks like Rails, writing no code results in <em>default</em> behavior.</p>
<p>This high-implicit-knowledge environment becomes comfortable with time, and genuinely helps increase productivity (especially at the outset) by helping you to focus on how your application is unique, as opposed to rotely defining how it <em>is not</em>.</p>
<p>It&#39;s really quite delightful to become accustomed to the &quot;magical&quot; sensation of the power that negative space has in a Rails application. One becomes used to making significant changes to the appliction by invoking only a single method or adding just one extra entry to an options hash.</p>
<h1>falling into the trap</h1>
<p>I&#39;m hardly an ActiveRecord expert. I&#39;m not terrifically familiar with its (most recent incarnation&#39;s) internals, so I often find myself stumbling around a bit to find a working solution.</p>
<p>This week we found a bug in a very complex chain of <a href="https://github.com/rails/arel">Arel</a> scopes. We added a new scope to the chain and in some very narrow situation, we found that our scope wasn&#39;t successfully narrowing down the results.</p>
<p>Explaining the entire chain of scopes isn&#39;t worth your time, so I&#39;ll only give an example of the sort of scope we added. It originally looked like this:</p>
<pre><code><span class="function"><span class="keyword">def</span> <span class="title"><span class="keyword">self</span></span>.<span class="title">with_unpaid_invoices</span></span>
  joins(<span class="symbol">:invoices</span>).
    where(<span class="string">'invoices.paid = ?'</span>, <span class="keyword">false</span>)
<span class="keyword">end</span></code></pre>
<p>But since that wasn&#39;t working in our case, we toyed around a bit and we found a quite easy fix. We just changed &quot;joins&quot; to &quot;includes&quot;, like so:</p>
<pre><code><span class="function"><span class="keyword">def</span> <span class="title"><span class="keyword">self</span></span>.<span class="title">with_unpaid_invoices</span></span>
  includes(<span class="symbol">:invoices</span>).
    where(<span class="string">'invoices.paid = ?'</span>, <span class="keyword">false</span>)
<span class="keyword">end</span></code></pre>
<p>This change fixed the immediate problem we were dealing with. It also turned out to be a bad idea, in no small part because we didn&#39;t understand the documented purpose of <code>includes</code> before we put it to use.</p>
<h1>joins vs. includes</h1>
<p>I&#39;m going to refer to the <a href="http://guides.rubyonrails.org/active_record_querying.html">Rails guide on ActiveRecord querying</a> to shed a little light on the background of <code>joins</code> and <code>includes</code>.</p>
<ul>
<li><code>joins</code> is provided for the purpose of adding <code>JOIN</code> clauses to the SQL that AR generates. This is most often used to narrow results based on some condition(s) of its associated models.</li>
<li><code>includes</code> is provided as a solution to the classic &quot;N + 1&quot; query problem that plagues most ORM libraries. Per the guide, &quot;<em>Active Record lets you specify in advance all the associations that are going to be loaded. This is possible by specifying the <code>includes</code> method of the Model.find call.</em>&quot;</li>
</ul>
<p>As is patently obvious by juxtaposing the purpose of these two methods, it&#39;s clear that their motivations are entirely unrelated. The former seeks to improve the expressiveness of your queries, the latter seeks to improve the performance of your queries.</p>
<p>There&#39;s a lurking danger that users might conflate the two (as we did), in that these two features are both used in the same context (when finding records) and both use similar tools to accomplish their task (SQL&#39;s <code>INNER JOIN</code> and <code>LEFT OUTER JOIN</code>, respectively).</p>
<p>As is often the case, Rails provides us just enough rope with which to hang ourselves, as is suggested in this section of the guide that immediate follows its descriptions of <code>joins</code> and <code>includes</code>:</p>
<blockquote>
<p><strong> 12.2 Specifying Conditions on Eager Loaded Associations </strong></p>
<p>Even though Active Record lets you specify conditions on the eager loaded associations just like joins, the recommended way is to use <code>joins</code> instead.</p>
<p>However if you must do this, you may use <code>where</code> as you would normally.</p>
</blockquote>
<p>It warns against specifying conditions when using <code>includes</code>, but it doesn&#39;t go on to give a compelling reason. Let&#39;s continue, and discover why the guide warns us of specifying conditions when using <code>includes</code>.</p>
<h1>the includes() side effect</h1>
<p>The two methods&#39; apparent similarity begged the question &quot;why, after all, did switching a <code>joins</code> to an <code>includes</code> fix our scope? That smells wrong.&quot;</p>
<p>It turned out that the pre-existing lengthy chain of scopes had been using <code>includes</code> and <code>where</code> <em>for their side effect</em>.</p>
<p>You see, because <code>includes</code> uses outer joins to grab your models&#39; associated records in one big query, any conditions that you place on those associations will filter them down, too.</p>
<p>Here&#39;s our example domain: <code>Clients</code> have many <code>Invoices</code> which may or may not be <code>paid</code>. Pretend as well that our system has two clients: one with an unpaid invoice and one with no unpaid invoices.</p>
<p>To illustrate, here are some example queries:</p>
<pre><code>&gt; Client.all
=&gt; [#<span class="tag">&lt;<span class="title">Client</span> <span class="attribute">id:</span> <span class="attribute">1</span>&gt;</span>, #<span class="tag">&lt;<span class="title">Client</span> <span class="attribute">id:</span> <span class="attribute">2</span>&gt;</span>]
&gt; Client.joins(:invoices).where('invoices.paid = ?', false)
=&gt; [#<span class="tag">&lt;<span class="title">Client</span> <span class="attribute">id:</span> <span class="attribute">2</span>&gt;</span>]
&gt; Client.includes(:invoices).where('invoices.paid = ?', false)
=&gt; [#<span class="tag">&lt;<span class="title">Client</span> <span class="attribute">id:</span> <span class="attribute">2</span>&gt;</span>]</code></pre>
<p>So, as we can see, <code>joins</code> and <code>includes</code> both filter the results as we would expect.</p>
<p>But there is an interesting, subtle difference between the nature of those <code>Client</code> instances.</p>
<p>First, here is what the <code>invoices</code> relationship looks like if we use <code>joins</code>, the recommended means of querying based on associations&#39; criteria:</p>
<pre><code>&gt; clients = <span class="class">Client</span>.joins(:invoices).where(<span class="string">'invoices.paid = ?'</span>, <span class="keyword">false</span>)
&gt; clients.first.invoices
=&gt; [#&lt;<span class="class">Invoice</span> <span class="method">id:</span> <span class="number">2</span>, <span class="method">paid:</span> <span class="keyword">true</span>, <span class="method">client_id:</span> <span class="number">2</span>&gt;,
    #&lt;<span class="class">Invoice</span> <span class="method">id:</span> <span class="number">3</span>, <span class="method">paid:</span> <span class="keyword">false</span>, <span class="method">client_id:</span> <span class="number">2</span>&gt;]</code></pre>
<p>As you can see, we searched for &quot;clients with unpaid invoices&quot;, and when we actually go look at the invoices of such a client, we get back both its paid and unpaid invoices. This makes sense because the client object is presented to us completely and accurately.</p>
<p>Second, let&#39;s look at how this differs when using <code>includes</code>:</p>
<pre><code>&gt; clients = Client.includes(:invoices).where('invoices.paid = ?', false)
=&gt; [#<span class="tag">&lt;<span class="title">Client</span> <span class="attribute">id:</span> <span class="attribute">2</span>&gt;</span>]
&gt; clients.first.invoices
=&gt; [#<span class="tag">&lt;<span class="title">Invoice</span> <span class="attribute">id:</span> <span class="attribute">3</span>, <span class="attribute">paid:</span> <span class="attribute">false</span>, <span class="attribute">client_id:</span> <span class="attribute">2</span>&gt;</span>]</code></pre>
<p>When we use <code>includes</code>, we not only get the &quot;clients with unpaid invoices&quot;, we also receive &quot;only the unpaid invoices for each client&quot;. At first blush, that can seem pretty cool! If our true intent was to present a list of all of the unpaid invoices of all of our clients, this could actually be quite convenient. We&#39;d fetch everything up front in one big query and the hydrated objects would allow us to present the results just as we wished without further modification.</p>
<p>Obviously, leveraging this side effect intentionally would bear with it a little extra implicit knowledge: the <code>clients</code> returned by such a query wouldn&#39;t be &quot;real&quot; clients per se, because their associations won&#39;t reflect reality. If we were to pass those clients to another object (or another developer) that was unaware of the nature of these filtered associations, difficult-to-discern bugs might emerge.</p>
<p>And apart from that caveat, there&#39;s a catch.</p>
<h1>the catch</h1>
<p>If one decides to (or merely happens to) take advantage of this side effect, there&#39;s a worrisome catch: if the filtered association is subsequently scoped, all of the original filtering <em>disappears</em>.</p>
<p>Take the above example:</p>
<pre><code>&gt; clients = Client.includes(:invoices).where('invoices.paid = ?', false)
=&gt; [#<span class="tag">&lt;<span class="title">Client</span> <span class="attribute">id:</span> <span class="attribute">2</span>&gt;</span>]
&gt; invoices = clients.first.invoices
=&gt; [#<span class="tag">&lt;<span class="title">Invoice</span> <span class="attribute">id:</span> <span class="attribute">3</span>, <span class="attribute">paid:</span> <span class="attribute">false</span>, <span class="attribute">client_id:</span> <span class="attribute">2</span>&gt;</span>]</code></pre>
<p>Next, suppose we want to filter <code>invoices</code> down <em>just a little bit more</em>, in this case we decide to exclude the invoices less than $50:</p>
<pre><code>&gt; invoices.where(<span class="string">'amount &gt; ?'</span>, <span class="number">50</span>)
=&gt; [#&lt;<span class="class">Invoice</span> <span class="method">id:</span> <span class="number">2</span>, <span class="method">paid:</span> <span class="keyword">true</span>, <span class="method">amount:</span> <span class="number">100.0</span>, <span class="method">client_id:</span> <span class="number">2</span>&gt;,
    #&lt;<span class="class">Invoice</span> <span class="method">id:</span> <span class="number">3</span>, <span class="method">paid:</span> <span class="keyword">false</span>, <span class="method">amount:</span> <span class="number">100.0</span>, <span class="method">client_id:</span> <span class="number">2</span>&gt;]</code></pre>
<p>Woah, woah, woah. That paid invoice came back! That&#39;s not what we wanted at all!</p>
<p>As it turns out, by scoping on the filtered association we&#39;ve lost any filtering-as-side-effect that we attained from <code>includes</code>. And it&#39;s not because of how we searched, either; invoking <code>scoped</code> or <code>count</code> on the associated array will have the same effect:</p>
<pre><code>&gt; invoices.count
=&gt; <span class="number">2</span>
&gt; invoices.scoped
=&gt; [#&lt;<span class="class">Invoice</span> <span class="method">id:</span> <span class="number">2</span>, <span class="method">paid:</span> <span class="keyword">true</span>, <span class="method">amount:</span> <span class="number">100.0</span>, <span class="method">client_id:</span> <span class="number">2</span>&gt;,
    #&lt;<span class="class">Invoice</span> <span class="method">id:</span> <span class="number">3</span>, <span class="method">paid:</span> <span class="keyword">false</span>, <span class="method">amount:</span> <span class="number">100.0</span>, <span class="method">client_id:</span> <span class="number">2</span>&gt;]</code></pre>
<p>Huh.</p>
<h1>conclusion</h1>
<p>Obviously, there&#39;s nothing expressly <em>evil</em> about specifying conditions on an included assocation, but I now understand why the Rails Guides might recommend against it. As it turns out, relying on the filtering side effect of <code>includes</code> is quite fragile and error-prone.</p>
<p>As for the situation that led me to this realization, we decided to rework the existing code to eliminate its reliance on this filtering side effect. We went through each of the existing scopes and switched them from <code>includes</code> to <code>joins</code>, then we added (duplicatively) similar scopes to be used on the associated arrays of the results. The approach we landed on will result in more queries at runtime—if a performance problem emerges as a result, we&#39;ll tackle it then.</p>
<p>Huge thanks to <a href="https://twitter.com/angelolakra">Angelo Lakra</a>, <a href="https://twitter.com/diminish7">Jason Rush</a>, and <a href="https://twitter.com/toddkaufman">Mr. Todd Kaufman</a> for working with me (and in most cases, teaching me) what was going on in this case. I also pushed the <a href="https://github.com/searls/includes-vs-joins">repo that I used</a> to work out this post&#39;s example to github.</p>
]]></description><link>http://searls.testdouble.com/posts/2013-01-26-an-includes-trap.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2013-01-26-an-includes-trap.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Sat, 26 Jan 2013 00:00:00 GMT</pubDate></item><item><title><![CDATA[explicit vs implicit knowledge]]></title><description><![CDATA[<p>We lack much of a vocabulary to describe <em>knowledge</em> and how code can succeed to or fail at codifying it. The points made in this post are so popular as to be self-evident, but it seems I can always use more practice in articulating them. I&#39;ll start with an example that many of us are familiar with and then swivel into an issue I ran into today.</p>
<h1>code comments</h1>
<p>Inline comments in code are often maligned for two reasons: (1) well-factored code can be so expressive that additional comments shouldn&#39;t be too valuable, and (2) comments often fall out of sync with reality, as only the code <em>must</em> change to implement new behavior.</p>
<p>For example, we can probably all agree that there&#39;s a way to obviate the following comment:</p>
<pre><code><span class="comment">#go to the next candidate prime divisor</span>
<span class="title">n</span> += <span class="number">1</span></code></pre>
<p>The problem above is that the meaning of <code>n</code> is nearly <em>implicit</em>, and certainly would be if the comment had existed only outside the code listing (or worse, only inside someone&#39;s brain). In this case, there&#39;s an obviously <em>better place</em> to store that knowledge, in this case, with a better name for the identifier.</p>
<pre><code><span class="title">candidate_prime_divisor</span> += <span class="number">1</span></code></pre>
<p>Now the knowledge and the function are one and the same. I would call this example&#39;s knowledge of a number tracking of a candidate prime divisor <em>explicit</em>, because it literally states it.</p>
<h1>arguments lacking context</h1>
<p>The first example was quite contrived, but here&#39;s a method similar to one I ran into today. I struggled mightily to recall some of its intent:</p>
<pre><code><span class="function"><span class="keyword">def</span> <span class="title">report_on_payment</span><span class="params">(recipient, month, regions = [], types = [], save = <span class="keyword">true</span>)</span></span>
  save = <span class="keyword">false</span> <span class="keyword">if</span> month.current? || regions.any? || types.any?

  report = calculate_report(recipient, month, regions, types)
  save_report(report) <span class="keyword">if</span> save
  report
<span class="keyword">end</span></code></pre>
<p>Regardless of any other issues, it&#39;s clear what the thrust of this method is: it generates a report for payments to a recipient for a given month, and <em>sometimes</em> it persists that report.</p>
<p>But upon reading it, two questions fluttered in my mind:</p>
<ol>
<li>Why do <code>regions</code> and <code>types</code> default to blank? Shouldn&#39;t default behavior include <em>all</em> possible <code>regions</code> and <code>types</code>?</li>
<li>Why is the <code>save</code> flag tripped to <code>false</code> in the presence of any regions or types?</li>
</ol>
<p>And try as I might, there is nothing <em>explicitly</em> written in that method that can be used to answer those questions. In fact, the only way I managed to figure it out was on account of the fact that I had a part in writing it.</p>
<p>So, what&#39;s the missing meaning behind these questions? The answer: there was a bit of implied knowledge floating in the brain of the author: <strong><code>regions</code> and <code>types</code> are used to <em>filter</em> the contents of the report, with an empty array meaning &quot;don&#39;t filter&quot;.</strong></p>
<p>Prior to the introduction of those filter fields, the meaning of the method was more straightforward:</p>
<pre><code><span class="function"><span class="keyword">def</span> <span class="title">report_on_payment</span><span class="params">(recipient, month, save = <span class="keyword">true</span>)</span></span>
  save = <span class="keyword">false</span> <span class="keyword">if</span> month.current?

  report = calculate_report(recipient, month)
  save_report(report) <span class="keyword">if</span> save
  report
<span class="keyword">end</span></code></pre>
<p>The basic logic is clearly &quot;each report is calculated for a (recipient, month) tuple and is generally persisted, but never for reports on the current month&quot;. This isn&#39;t a perfectly simple method, but at least its motives are mostly clear.</p>
<p>Now, knowing that <code>regions</code> and <code>types</code> are meant as fields to filter the contents of the report, we might consider adding that knowledge to the method more explicitly, like so:</p>
<pre><code><span class="function"><span class="keyword">def</span> <span class="title">report_on_payment</span><span class="params">(recipient, month, filters = {<span class="symbol">:regions</span> =&gt; [], <span class="symbol">:types</span> =&gt; []}, save = <span class="keyword">true</span>)</span></span>
  save = <span class="keyword">false</span> <span class="keyword">if</span> month.current? || filters.values.flatten.any?

  report = calculate_report(recipient, month, filters)
  save_report(report) <span class="keyword">if</span> save
  report
<span class="keyword">end</span></code></pre>
<p>This new implementation is certainly a tad longer, but at least it&#39;s now abundantly clear (a) that regions &amp; types are fields by which a user may <em>filter</em> a report&#39;s contents, and (b) saving should be disallowed whenever there are any filter options provided.</p>
<p>In this example, it turns out that both of my points of confusion could be assuaged by making our intention more explicit with a single new identifier.</p>
<h1>more broadly</h1>
<p>This is not to say that implicit knowledge is bad, but that—lest it impede the understanding of others—implicit  knowledge carries the hidden cost that it must be spread somehow. Rails, for example, is full of implicit knowledge in the form of conventions and methods missing that we share through documentation and tribal knowledge. Similarly, the design of most business applications is aided by a small lexicon of deeply meaningful nouns—even if that meaning is only shared by a small internal group.</p>
<p>I suppose we must be mindful of balancing knowledge conveyed explicitly in code with knowledge our code relies on implicitly and which must be conveyed by some other means.</p>
]]></description><link>http://searls.testdouble.com/posts/2013-01-21-explicit-vs-implicit-knowledge.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2013-01-21-explicit-vs-implicit-knowledge.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Mon, 21 Jan 2013 00:00:00 GMT</pubDate></item><item><title><![CDATA[upgrading hacked dependencies]]></title><description><![CDATA[<p>Today we set out to upgrade one of the third-party JavaScript dependencies on which our project relies and we inadvertently discovered that it had a number of custom hacks made against it. This blog post replays a similar experience and how we can reduce some of the risk in attempting to confidently upgrade the dependency with <code>git diff</code> and <code>patch</code>.</p>
<h2>introducing a new dependency</h2>
<p>It starts when we add a <a href="https://github.com/searls/jasmine-given">new 3rd party library</a> to our project. Everything is new and exciting!</p>
<pre><code><span class="variable">$ </span>git add jasmine-stealth.js
<span class="variable">$ </span>git commit -m <span class="string">'Adding jasmine-stealth, a cool library I found!'</span></code></pre>
<h2>hacking that dependency</h2>
<p>Over time, we add some custom hacks to our dependency to suit the needs of our project. We know it&#39;s poor form to directly edit a dependency like this, but in the interest of expediency we did it anyway.</p>
<p>To see what our history after our hacks:</p>
<pre><code><span class="comment">$</span> <span class="comment">git</span> <span class="comment">log</span> <span class="literal">-</span><span class="literal">-</span><span class="comment">oneline</span> <span class="comment">jasmine</span>-<span class="comment">stealth</span>.<span class="comment">js</code></pre>
<p>Which will summarize our commits like this:</p>
<pre><code><span class="number">3</span>be7a1c hack! add a <span class="keyword">default</span> stubbing <span class="keyword">if</span> none is given
<span class="number">36</span>df5a6 hack! in our project, every <span class="class"><span class="keyword">object</span> <span class="title">responds</span> <span class="title">to</span></span>
e19149f Adding jasmine-stealth, a cool library I found!</code></pre>
<p>And we can see what the diff looks like, too:</p>
<pre><code>$ git diff e19149f.<span class="variable">.HEAD</span> jasmine-stealth<span class="variable">.js</span></code></pre>
<p>Our diff looks like:</p>
<pre><code><span class="comment">diff</span> <span class="literal">-</span><span class="literal">-</span><span class="comment">git</span> <span class="comment">a/jasmine</span>-<span class="comment">stealth</span>.<span class="comment">js</span> <span class="comment">b/jasmine</span>-<span class="comment">stealth</span>.<span class="comment">js</span>
<span class="comment">index</span> <span class="comment">31e7956</span>.<span class="string">.</span><span class="comment">4216889</span> <span class="comment">100644</span>
<span class="literal">-</span><span class="literal">-</span><span class="literal">-</span> <span class="comment">a/jasmine</span>-<span class="comment">stealth</span>.<span class="comment">js</span>
<span class="literal">+</span><span class="literal">+</span><span class="literal">+</span> <span class="comment">b/jasmine</span>-<span class="comment">stealth</span>.<span class="comment">js</span>
<span class="comment">@@</span> <span class="literal">-</span><span class="comment">37</span>,<span class="comment">7</span> <span class="literal">+</span><span class="comment">37</span>,<span class="comment">7</span> <span class="comment">@@</span> <span class="comment">site:</span> <span class="comment">https://github</span>.<span class="comment">com/searls/jasmine</span>-<span class="comment">stealth</span>
   <span class="comment">root</span>.<span class="comment">spyOnConstructor</span> <span class="comment">=</span> <span class="comment">function(owner</span>, <span class="comment">classToFake</span>, <span class="comment">methodsToSpy)</span> <span class="comment">{</span>
     <span class="comment">var</span> <span class="comment">fakeClass</span>, <span class="comment">spies;</span>
     <span class="comment">if</span> <span class="comment">(methodsToSpy</span> <span class="comment">==</span> <span class="comment">null)</span> <span class="comment">{</span>
<span class="literal">-</span>      <span class="comment">methodsToSpy</span> <span class="comment">=</span> <span class="title">[</span><span class="title">]</span><span class="comment">;</span>
<span class="literal">+</span>      <span class="comment">methodsToSpy</span> <span class="comment">=</span> <span class="title">[</span><span class="comment">'render'</span>]<span class="comment">;</span>
     <span class="comment">}</span>
     <span class="comment">if</span> <span class="comment">(_(methodsToSpy)</span>.<span class="comment">isString())</span> <span class="comment">{</span>
       <span class="comment">methodsToSpy</span> <span class="comment">=</span> <span class="title">[</span><span class="comment">methodsToSpy</span>]<span class="comment">;</span>
<span class="comment">@@</span> <span class="literal">-</span><span class="comment">86</span>,<span class="comment">14</span> <span class="literal">+</span><span class="comment">86</span>,<span class="comment">14</span> <span class="comment">@@</span> <span class="comment">site:</span> <span class="comment">https://github</span>.<span class="comment">com/searls/jasmine</span>-<span class="comment">stealth</span>

   <span class="comment">jasmine</span>.<span class="comment">createStub</span> <span class="comment">=</span> <span class="comment">jasmine</span>.<span class="comment">createSpy;</span>

<span class="literal">-</span>  <span class="comment">jasmine</span>.<span class="comment">createStubObj</span> <span class="comment">=</span> <span class="comment">function(baseName</span>, <span class="comment">stubbings)</span> <span class="comment">{</span>
<span class="literal">+</span>  <span class="comment">jasmine</span>.<span class="comment">createStubObj</span> <span class="comment">=</span> <span class="comment">function(baseName</span>, <span class="comment">stubbings</span>, <span class="comment">defaultStubbing)</span> <span class="comment">{</span>
     <span class="comment">var</span> <span class="comment">name</span>, <span class="comment">obj</span>, <span class="comment">stubbing;</span>
     <span class="comment">if</span> <span class="comment">(stubbings</span>.<span class="comment">constructor</span> <span class="comment">===</span> <span class="comment">Array)</span> <span class="comment">{</span>
       <span class="comment">return</span> <span class="comment">jasmine</span>.<span class="comment">createSpyObj(baseName</span>, <span class="comment">stubbings);</span>
     <span class="comment">}</span> <span class="comment">else</span> <span class="comment">{</span>
       <span class="comment">obj</span> <span class="comment">=</span> <span class="comment">{};</span>
       <span class="comment">for</span> <span class="comment">(name</span> <span class="comment">in</span> <span class="comment">stubbings)</span> <span class="comment">{</span>
<span class="literal">-</span>        <span class="comment">stubbing</span> <span class="comment">=</span> <span class="comment">stubbings</span>[<span class="comment">name</span>]<span class="comment">;</span>
<span class="literal">+</span>        <span class="comment">stubbing</span> <span class="comment">=</span> <span class="comment">stubbings</span>[<span class="comment">name</span>] <span class="comment">||</span> <span class="comment">defaultStubbing;</span>
         <span class="comment">obj</span>[<span class="comment">name</span>] <span class="comment">=</span> <span class="comment">jasmine</span>.<span class="comment">createSpy(baseName</span> <span class="literal">+</span> <span class="comment">"</span>.<span class="comment">"</span> <span class="literal">+</span> <span class="comment">name);</span>
         <span class="comment">if</span> <span class="comment">(_(stubbing)</span>.<span class="comment">isFunction())</span> <span class="comment">{</span>
           <span class="comment">obj</span>[<span class="comment">name</span>]<span class="string">.</span><span class="comment">andCallFake(stubbing);</code></pre>
<h2>An upgrade appears!</h2>
<p>Just when we were enjoying our hacked-up dependency, a new version is released with critical bug fixes! We want to upgrade it, but neither do we want to lose our hacks nor do we want to imagine hand-merging the two.</p>
<p>To start, let&#39;s save off our customizations to a patch file:</p>
<pre><code><span class="comment">$</span> <span class="comment">git</span> <span class="comment">diff</span> <span class="literal">-</span><span class="literal">-</span><span class="comment">no</span>-<span class="comment">prefix</span> <span class="comment">e19149f</span>.<span class="string">.</span><span class="comment">HEAD</span> <span class="comment">jasmine</span>-<span class="comment">stealth</span>.<span class="comment">js</span> &gt; <span class="comment">hacks</span>.<span class="comment">patch</code></pre>
<p>You may have noted that we also add the <code>--no-prefix</code> flag to make the diff easier to apply with the <code>patch</code> tool.</p>
<p>Next, commit the new (and yet-unmodified) upgrade.</p>
<pre><code><span class="variable">$ </span>mv new-jasmine-stealth.js jasmine-stealth.js
<span class="variable">$ </span>git add jasmine-stealth.js
<span class="variable">$ </span>gc -am <span class="string">'upgraded jasmine-stealth.js to 0.0.12'</span></code></pre>
<p>Now, we want to apply our fixes from our saved patch:</p>
<pre><code>$ <span class="keyword">patch</span> -p0 &lt; hacks.<span class="keyword">patch</span></code></pre>
<p>Which yields the happy output:</p>
<pre><code><span class="title">patching</span> file jasmine-stealth.js</code></pre>
<p>And we can commit those hacks anew:</p>
<pre><code><span class="variable">$ </span>git add jasmine-stealth.js
<span class="variable">$ </span>git commit -m <span class="string">'reapplied hacks'</span></code></pre>
<h2>yay!</h2>
<p>This isn&#39;t the only way to do this, and it&#39;s not the best (in many cases, rebase could be used to preserve the history of the hack commits), but it worked for me today and maybe this example will help you!</p>
]]></description><link>http://searls.testdouble.com/posts/2013-01-18-upgrading-hacked-dependencies.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2013-01-18-upgrading-hacked-dependencies.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Fri, 18 Jan 2013 00:00:00 GMT</pubDate></item><item><title><![CDATA[say hello to lineman]]></title><description><![CDATA[<p>We&#39;ve been hard at work on a tool called <a href="https://github.com/testdouble/lineman">Lineman</a> that helps you create web applications in JavaScript (and CoffeeScript!), and we&#39;re really excited to share it with you!</p>
<p>Tonight I recorded an <a href="http://www.youtube.com/watch?v=BmZ4XRErYAI">8-minute screencast</a> to show you the ropes:</p>
<div class="wide-hd-video-lol">
  <iframe width="1280" height="720" src="http://www.youtube.com/embed/BmZ4XRErYAI?rel=0" frameborder="0" allowfullscreen></iframe>
</div>



<p>As time goes on, I&#39;ll go into more detail on both our motivations in writing Lineman as well as more advanced usage like overriding configuration defaults.</p>
<p>In the meantime, please give Lineman a spin and tell us what you think!</p>
]]></description><link>http://searls.testdouble.com/posts/2012-10-13-say-hello-to-lineman.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2012-10-13-say-hello-to-lineman.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Sat, 13 Oct 2012 00:00:00 GMT</pubDate></item><item><title><![CDATA[api design is hard]]></title><description><![CDATA[<p><em><a href="https://github.com/searls/gimme/tree/inarguable">Note: this post covers unreleased features of gimme, which are unreleased because of the issues described in this post. They need more time in the oven. You can [peruse the feature branch</a> on github]</em></p>
<p>Working on <a href="https://github.com/searls/gimme">gimme</a> with <a href="http://twitter.com/jasonkarns">Mr. Karns</a> made me realize I&#39;d painted myself into a corner on gimme&#39;s API design. I thought I&#39;d share here, for hope that either (a) someone will respond with an approach I like better, or (b) the topic might prove independently useful, and some good will come of this after all.</p>
<h2>background</h2>
<p>Gimme is a <a href="http://xunitpatterns.com/Test%20Double.html">test double</a> library, which is a fancy way to say it makes fake objects for your tests.</p>
<p>Let&#39;s imagine an object we want to fake, like:</p>
<pre><code><span class="class"><span class="keyword">class</span> <span class="title">Police</span></span>
  <span class="function"><span class="keyword">def</span> <span class="title">radar</span><span class="params">(car)</span></span>
  <span class="keyword">end</span>

  <span class="function"><span class="keyword">def</span> <span class="title">taze!</span><span class="params">(bro)</span></span>
  <span class="keyword">end</span>
<span class="keyword">end</span></code></pre>
<p>First, we&#39;d need to ask gimme for a test double:</p>
<pre><code><span class="setting">cop = <span class="value">gimme(Police)</span></span></code></pre>
<p>If we wanted to rig the radar reading to be a certain number, we could:</p>
<pre><code><span class="function"><span class="title">give</span><span class="params">(cop)</span>.<span class="title">radar</span><span class="params">(my_car)</span> { 90 }</code></pre>
<p>And if we wanted to make sure our cop tazed my bro, we could:</p>
<pre><code><span class="function"><span class="title">verify</span><span class="params">(cop)</span>.<span class="title">taze</span>!<span class="params">(my_bro)</span></code></pre>
<h2>the initial solution</h2>
<p>But what if we don&#39;t care about <code>my_car</code>? What if we want the radar to only read 90? (This would be a very sensible desire if the radar was only loosely related to our test and a lot of cars needed to be scanned)</p>
<p>Well, Jason and I landed at an API like this one:</p>
<pre><code><span class="function"><span class="title">give</span><span class="params">(cop)</span>.<span class="title">radar</span> { 90 }.<span class="title">inarguably</span></code></pre>
<p>That <code>inarguably</code> flag would basically set up an additional stubbing for the method that would always be satisfied, whether in the presence or absence of arguments.</p>
<p>Verification could work (sort of) similarly.</p>
<pre><code><span class="function"><span class="title">verify</span><span class="params">(cop)</span>.<span class="title">inarguably</span>.<span class="title">taze</span>!</code></pre>
<h2>bad</h2>
<p>See the change in ordering? When stubbing, the <code>inarguably</code> configuration comes at the very end of the statement, but when verifying, <code>inarguably</code> is sandwiched in the beginning. <em>That&#39;s bound to confuse people.</em>, I thought.</p>
<p>Why was it done that way? Primarily, it was because a failed verification will immediate raise an error. Why not do this?</p>
<pre><code><span class="function"><span class="title">verify</span><span class="params">(cop)</span>.<span class="title">taze</span>!.<span class="title">inarguably</span></code></pre>
<p>But, alas, a <code>verify</code> can&#39;t return an optional configuration object to be invoked after the command, simply because it needs to know whether to raise an error, and there&#39;s no way of immediately knowing whether someone will ever call <code>inarguably</code> later.</p>
<p>So we settled for the previous solution. But I still really hate that mismatch; that&#39;s exactly the kind of test double design that confuses and frustrates people already confused and frustrated by test doubles!</p>
<h2>worse</h2>
<p>Then it gets worse! By adding an API like <code>inarguably</code> directly on the object returned by a <code>verify()</code> call, it means that <strong>users could not longer verify a method that&#39;s actually named &quot;inarguably&quot;</strong>. That&#39;s not cool.</p>
<p>I mean, sure, it&#39;s a goofy name. But rubyists love goofy names. And besides, Gimme is likely to accrue other configuration options in the future. I&#39;d hate to set a precedent now that leads to a dozen &quot;magical method names&quot; that, upon being verified, for some reason silently pass. That&#39;d surprise and confuse every user that might run into them.</p>
<h2>worst</h2>
<p>In my finite wisdom, I decided to tweak <code>give</code> to work just like <code>verify</code>, anyway. So at the moment, you can do either of these things:</p>
<pre><code><span class="function"><span class="title">give</span><span class="params">(cop)</span>.<span class="title">inarguably</span>.<span class="title">radar</span> { 90 }</code></pre>
<p>Or</p>
<pre><code><span class="function"><span class="title">verify</span><span class="params">(cop)</span>.<span class="title">inarguably</span>.<span class="title">taze</span>!</code></pre>
<p>And now I have two problems! Users can now neither stub nor verify a method called &quot;inarguably&quot;, and any remedy I can think to provide as the library&#39;s author (assuming this design stands) would require a user to first realize this limitation.</p>
<h2>halp?</h2>
<p>So what would you do? I&#39;ve thought of a couple silly ideas.</p>
<h3>a new arg</h3>
<pre><code><span class="function"><span class="title">give</span><span class="params">(cop, :inarguably)</span>.<span class="title">radar</span> { 90 }</code></pre>
<p>and</p>
<pre><code><span class="function"><span class="title">verify</span><span class="params">(cop, :inarguably)</span>.<span class="title">taze</span>!</code></pre>
<p>Which would require a somewhat-cute implementation, since verify already supports a syntax like <code>verify(cop, 4.times).taze!(bro)</code></p>
<h3>a catch-all config method</h3>
<p>I&#39;ve also thought about future-proofing the concern that we&#39;d one day have a bunch of one-off configuration methods that don&#39;t work, by creating just <em>one</em> configuration method to which you&#39;d supply an options hash:</p>
<pre><code><span class="function"><span class="title">give</span><span class="params">(cop)</span>.<span class="title">configure</span><span class="params">(:inarguable =&gt; true)</span>.<span class="title">radar</span> {90}</code></pre>
<p>or</p>
<pre><code><span class="function"><span class="title">verify</span><span class="params">(cop)</span>.<span class="title">configure</span><span class="params">(:inarguable =&gt; true)</span>.<span class="title">taze</span>!</code></pre>
<p>And perhaps both give &amp; verify could simply remove that configuration method as soon as it is used, that way if someone wanted to stub or verify a method with the same name, they could, with something like <code>verify(cop).configure.configure(:foo)</code>. Alas, the user would still have to realize what&#39;s going on, which makes it a deal breaker.</p>
<h2>in conclusion</h2>
<p>In conclusion, there is no conclusion. I&#39;m not sure what I want to do. The safest way would be the &quot;a new arg&quot; approach, adding an arg to <code>give</code> and <code>verify</code>, but it&#39;s also the one my eyes and fingers like least.</p>
<p>Any feedback on this issue? I&#39;d greatly appreciate it.</p>
]]></description><link>http://searls.testdouble.com/posts/2012-09-29-api-design-is-hard.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2012-09-29-api-design-is-hard.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Sat, 29 Sep 2012 00:00:00 GMT</pubDate></item><item><title><![CDATA[purpose oriented tests]]></title><description><![CDATA[<p>Lately I&#39;ve been thinking a lot about how we can improve our code by reflecting on our mindsets and motivations with respect to software testing. A while ago, I wrote about <a href="/2011/04/29/the-power-of-prompts/">the huge impact that prompts</a> have on how we grow code (even the parts of speech we use to name objects). Later, I sat down to <a href="/2012/04/01/types-of-tests/">illustrate a taxonomy</a> of the types of tests I tend to see in the wild. Recently, I wrote a bit about our natural tendency to <a href="/2012/07/19/blame-the-code-not-the-test/">misplace blame</a> when testing gets hard.</p>
<p>All of this reflection has helped me draw this conclusion: <strong>the best test suites serve exactly one purpose.</strong></p>
<h2>the word &quot;test&quot;</h2>
<p>In the beginning of my career, I didn&#39;t write any automated tests. Nevertheless, &quot;testing&quot; held several important meanings to me, even when performed manually:</p>
<ul>
<li>I&#39;d &quot;test&quot; that each bit of code was working as I wrote</li>
<li>I&#39;d &quot;test&quot; that I didn&#39;t obviously break major functionality before every deploy</li>
<li>I&#39;d &quot;test&quot; that my boss/customer/peers liked whatever I was building</li>
</ul>
<p>The fact I could get away with using the word &quot;test&quot; just now to describe the above activities says more about the English language than it does about writing software.</p>
<p>And yet, even though now I leverage automation in the above activities, I still call them all &quot;tests&quot;. Tests like the above often fall into buckets labeled something like &quot;unit&quot;, &quot;integration&quot;, and &quot;end-to-end&quot;, respectively.</p>
<p>But &quot;unit&quot;, &quot;integration&quot;, and &quot;end-to-end&quot; don&#39;t really capture the essence of the above activities. At best, they describe the types of interactions those tests are allowed to encounter. (That is, a unit test should be relatively isolated; an end-to-end test should be relatively realistic.) The ratio of isolation-to-realism is a very important thing to understand and think about, certainly, but it&#39;s tangential to the <em>purpose</em> of each test.</p>
<h2>problems!</h2>
<p>So slicing test suites by &quot;degree of realism&quot; has practical justifications. Each level-of-realism brings different automation tools into play. As realism increases, test execution slows down (as do our feedback loops), so cordoning fast tests into a separate suite can improve situations where the entire suite would be too slow to run locally.</p>
<p>But defining our tests by their integrated-ness has raised some problems, too. Problems I don&#39;t think we&#39;ve done a good job addressing.</p>
<h3>arbitrariness</h3>
<p>Learning automated testing is hard for most developers, but learning the initially-arbitrary-seeming distinctions between tests of one level of integration vs. another is even harder (perhaps because it seems so arbitrary at first).</p>
<p>This arbitrary feeling, I think, is the primary reason why people are so unsure about when using test doubles is appropriate; why teams allow fixtures &amp; factories to become tragedies of the commons; and why so many cycles get wasted on the question &quot;at what level-of-integration should I write this test?&quot;</p>
<h3>lack of prompting</h3>
<p>This method of test organization doesn&#39;t prompt developers at all with any information about <em>why</em> a test exists. Depending on the time of day, my mindset when I sit down to write a test can vary dramatically:</p>
<ul>
<li><p>I&#39;m excited, because I&#39;m writing brand new, unknown code</p>
</li>
<li><p>I&#39;m cautious, because I don&#39;t want future code changes to break this feature</p>
</li>
<li><p>I&#39;m a nervous wreck, because a bug I&#39;m responsible for just exploded in production</p>
</li>
</ul>
<p>Directory names like <code>faster_specs/</code>, <code>spec/</code>, and <code>features/</code> don&#39;t push me towards putting similarly-motivated tests nearby each other. As a result, some other factor will decide which directory the test goes in—sometimes it&#39;s convenience, sometimes it&#39;s habit, and sometimes it&#39;s even organizational culture.</p>
<p>It&#39;s worth noting that my <code>app/</code> directory <em>doesn&#39;t have this problem</em>. Every time I sit down to write code in <code>app</code>, my motivation is &quot;write working code that works well.&quot;</p>
<h3>test conflation</h3>
<p>The above issue, that of arbitrarily lumping differently-motivated tests together, leads to another problem: individual tests that represent numerous purposes.</p>
<p>Remember how terrible it was to see PHP/ASP/JSP/ERB templates like this?</p>
<pre><code><span class="tag">&lt;<span class="title">html</span>&gt;</span>
  <span class="vbscript">&lt;%= javascript_tag <span class="keyword">do</span> %&gt;</span>
    $(function(){
      $(".<span class="vbscript">&lt;%= my_class_name %&gt;</span>").show()
    });
  <span class="vbscript">&lt;% <span class="keyword">end</span> %&gt;</span>
  <span class="tag">&lt;<span class="title">stylesheet</span>&gt;</span>
    .<span class="vbscript">&lt;%= my_class_name %&gt;</span> { background-color: red; }
  <span class="tag">&lt;/<span class="title">stylesheet</span>&gt;</span>
<span class="tag">&lt;/<span class="title">html</span>&gt;</span></code></pre>
<p>The above example doesn&#39;t separate concerns. We&#39;ve got numerous execution contexts all lumped in a single file. But considering that, a great many tests approached at different times with varying motivations will invariably end up looking similarly!</p>
<p>For example, say I start a test for a new class called <code>TakesOrder</code>. To figure out a design, I might use isolation testing to discover <code>TakesOrder</code>&#39;s dependencies:</p>
<pre><code>describe <span class="variable">TakesOrder</span> do
  <span class="variable">Given</span>(:notifier) <span class="tuple">{ <span class="function_name">gimme</span>(<span class="variable">NotifiesUser</span>) }</span>
  subject <span class="tuple">{ <span class="variable">TakesOrder</span>.<span class="function_name">new</span>(notifier) }
  <span class="variable">When</span> <span class="tuple">{ subject.take }</span>
  <span class="variable">Then</span> <span class="tuple">{ <span class="function_name">verify</span>(notifier).<span class="keyword">not</span>ify }
<span class="keyword">end</span></code></pre>
<p>Later on, we find a bug in this class and we yell, &quot;Stupid mock! That test didn&#39;t give me any assurance at all!&quot;. So then we write a test for the bug with a dash of added realism:</p>
<pre><code>describe TakesOrder <span class="operator"><span class="keyword">do</span>
  Given(:notifier) { gimme(NotifiesUser) }
  Given(:<span class="keyword">user</span>) { FactoryGirl.<span class="keyword">create</span>(:<span class="keyword">user</span>) }
  Given { give(notifier).<span class="keyword">user</span> { <span class="keyword">user</span> } }
  subject { TakesOrder.new(notifier) }
  <span class="keyword">When</span> { subject.take }
  <span class="keyword">Then</span> { verify(notifier).notify }
  <span class="keyword">Then</span> { <span class="keyword">user</span>.notifications.<span class="keyword">size</span>.should == <span class="number">1</span> }
<span class="keyword">end</span></code></pre>
<p>And now we have a test that both uses test doubles (to aid in design) and also integrates with the database (to guard against regression).</p>
<p><strong>That sucks</strong>.</p>
<p>Now every time anyone cracks open the test, they&#39;re going to have to waste time deciding whether or not every additional collaborator should be fake or real.</p>
<h2>purpose-orientation</h2>
<p>Okay, so slicing tests by degree-of-realism isn&#39;t perfect. Is there any other way?</p>
<p>Let&#39;s return to the various mindsets we adopt when we&#39;re writing tests. I&#39;ll rattle off off a handful for the sake of discussion:</p>
<ul>
<li>We write tests to demonstrate to others (and ourselves) that our software does roughly what we agreed it should do. Maybe we write these on a feature-by-feature basis to gain the approval of a product owner</li>
<li>We write tests to gain confidence in the design of our code, and (particularly with TDD) we respond to pain caused by these tests by asking ourselves, &quot;can we obviate this pain by improving the design of our production code?&quot;</li>
<li>We write tests in response to being burned by bugs. In order to ensure a bug doesn&#39;t return, we write an automated test that replicates the buggy behavior in order to protect us from future regressions</li>
<li>We write tests that ensure the overall application is basically in a working state, either to increase our confidence that a build is stable or that our production environment is healthy.</li>
</ul>
<p>The above motivations are really valuable and interesting, but nearly every application does little-to-nothing to promote the distinction.</p>
<p>What if we sliced our tests into suites based on their purpose instead? Maybe we&#39;d end up with a directory structure like this?</p>
<pre><code>    <span class="string">.</span>
    <span class="comment">├──</span> <span class="comment">app</span>
    <span class="comment">│</span>   <span class="comment">└──</span> <span class="comment">app_stuff</span>.<span class="string">.</span><span class="string">.</span>
    <span class="comment">└──</span> <span class="comment">test</span>
        <span class="comment">├──</span> <span class="comment">acceptance</span>
        <span class="comment">├──</span> <span class="comment">design</span>
        <span class="comment">├──</span> <span class="comment">regression</span>
        <span class="comment">└──</span> <span class="comment">smoke</code></pre>
<h3>interesting consequences</h3>
<p>If we were to actually do this, it would raise all sorts of interesting questions:</p>
<ul>
<li>Would it suck for a single unit to be covered to some degree by three or four different tests? What does it mean when that happens?</li>
<li>Which of these are most important to run before check-in?</li>
<li>Which of these are most important to run in CI?</li>
<li>Would being forced to decide on the most appropriate level-of-integration for a given <em>purposeful</em> test be liberating or paralyzing, I wonder?</li>
</ul>
<h1>conclusion</h1>
<p>In any case, I wanted to raise the above issues, because I don&#39;t think we&#39;ve yet arrived at the best way to organize our code in such a way that respects the myriad of reasons we write (and don&#39;t write) tests. How about you?</p>
]]></description><link>http://searls.testdouble.com/posts/2012-07-27-purpose-oriented-tests.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2012-07-27-purpose-oriented-tests.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Fri, 27 Jul 2012 00:00:00 GMT</pubDate></item><item><title><![CDATA[blame the code not the test]]></title><description><![CDATA[<p>&quot;This test is too coupled to the implementation.&quot;</p>
<p>This complaint is commonly levied when—on account of test double setup—you have spec code that looks a lot like the subject&#39;s (&quot;SUT&#39;s&quot;) implementation code. I hear this complaint most often in cases where the subject has little responsibility beyond passing a value from dependency A to dependency B and returning it.</p>
<p>Because <a href="/2012/04/01/types-of-tests/#isolation-tests">isolation tests</a> specify not only the externally observable behavior of the subject, but also the subject&#39;s contracts with its collaborators, it should be obvious that isolation testing is going to bring complex interactions with collaborators to the forefront in a way that an integrated test would not.</p>
<p>Before immediately jumping to the conclusion that the use of test doubles is to blame for tests made painful by this fact, it&#39;s always helpful to remember that it&#39;s just as likely the production code is the root cause of the pain, and that the painful test is merely a symptom. That is to say, instead of responding to that pain in the test by changing how you test, one could use it as an opportunity to change the design so that the code is doing more than manually passing some value from dependency A to B (to C to D).</p>
<p>Say we have this code:</p>
<pre><code>Invoice =
  build: -&gt;
    count = CountCalculator<span class="variable">.calculate</span>()
    price = PriceCalculator<span class="variable">.calculate</span>(count)
    withTax = TaxCalculator<span class="variable">.calculate</span>(price)
    withShipping = ShippingCaclulator<span class="variable">.calculate</span>(withTax)</code></pre>
<p>The above code was demanded by this spec:</p>
<pre><code>describe <span class="string">"Invoice"</span>, -&gt;
  Given -&gt; window<span class="variable">.CountCalculator</span> = calculate: jasmine<span class="variable">.createSpy</span>()<span class="variable">.andReturn</span>(<span class="number">1</span>)
  Given -&gt; window<span class="variable">.PriceCalculator</span> = calculate: jasmine<span class="variable">.createSpy</span>()<span class="variable">.when</span>(<span class="number">1</span>)<span class="variable">.thenReturn</span>(<span class="number">2</span>)
  Given -&gt; window<span class="variable">.TaxCalculator</span> = calculate: jasmine<span class="variable">.createSpy</span>()<span class="variable">.when</span>(<span class="number">2</span>)<span class="variable">.thenReturn</span>(<span class="number">3</span>)
  Given -&gt; window<span class="variable">.ShippingCaclulator</span> = calculate: jasmine<span class="variable">.createSpy</span>()<span class="variable">.when</span>(<span class="number">3</span>)<span class="variable">.thenReturn</span>(<span class="number">4</span>)

  When -&gt; @result = Invoice<span class="variable">.build</span>()

  Then -&gt; expect(@result)<span class="variable">.toEqual</span>(<span class="number">4</span>)</code></pre>
<p>Ouch. Painful test. But it does assert the behavior that we want (even the order we want!). And it does so without any backdoor manipulation of the SUT; it may <em>feel</em> like backdoor manipulation because of the spec&#39;s intimate arrangement of everything the SUT will be doing, but this is more of an indictment of the SUT for not doing anything interesting or useful than an indication of wrongdoing on the test&#39;s part. [Note: in this contrived example, that nuance might be lost because we&#39;re effectively spying on global functions instead of using dependency injection, but I didn&#39;t want to risk confusion by making the code snippet any longer than necessary.]</p>
<p>A reaction I often hear from seeing a test like this focuses squarely on the use of test doubles, and the argument goes something like, &quot;because the test resembles the implementation so closely, test doubles shouldn&#39;t be used.&quot; Usually, the person forwarding the argument will advocate for a coarser, less-isolated test in response to this pain. And, of course, that would probably work fine, and it would probably result in a more readable spec than the one above, but unfortunately it would not take advantage of the greatest strength of isolation testing: <strong>alerting you to design problems by inflicting acute pain</strong>.</p>
<p>Instead, I&#39;d prefer to address the pain by searching for a way to make the <em>implementation</em> less rote, since it doesn&#39;t have any behavior of its own other than to call its collaborators in a series. Once that responsibility has been generalized, new isolation tests will emerge and hopefully be simpler (and, as a side effect, less resemble their production code).</p>
<p>For example, the code above can be refactored like this (the spec still passes):</p>
<pre><code><span class="comment">ChainsCalls</span> <span class="comment">=</span>
  <span class="comment">chain:</span> <span class="comment">(dependencies</span>, <span class="comment">method)</span> <span class="literal">-</span>&gt;
    <span class="comment">_(dependencies)</span>.<span class="comment">inject((memo</span>, <span class="comment">dependency)</span> <span class="literal">-</span>&gt;
      <span class="comment">dependency</span>[<span class="comment">method</span>]<span class="comment">(memo)</span>
    <span class="string">,</span> <span class="comment">undefined)</span>

<span class="comment">Invoice</span> <span class="comment">=</span>
  <span class="comment">build:</span> <span class="literal">-</span>&gt;
    <span class="comment">ChainsCalls</span>.<span class="comment">chain(</span>[<span class="comment">CountCalculator</span>, <span class="comment">PriceCalculator</span>, <span class="comment">TaxCalculator</span>, <span class="comment">ShippingCaclulator</span>]<span class="string">,</span> <span class="comment">"calculate")</code></pre>
<p>And after this refactor, we can tidy up our tests so that they mirror the production units:</p>
<pre><code>describe <span class="string">"ChainsCalls"</span>, -&gt;
  Given -&gt; <span class="variable">@a</span> = go: jasmine.createSpy().andReturn(<span class="string">"foo"</span>)
  Given -&gt; <span class="variable">@b</span> = go: jasmine.createSpy().<span class="keyword">when</span>(<span class="string">"foo"</span>).thenReturn(<span class="string">"bar"</span>)
  When -&gt; <span class="variable">@result</span> = ChainsCalls.chain([<span class="variable">@a</span>,<span class="variable">@b</span>], <span class="string">"go"</span>)
  Then -&gt; expect(<span class="variable">@result</span>).toBe(<span class="string">"bar"</span>)

describe <span class="string">"Invoice"</span>, -&gt;
  Given -&gt; window.ChainsCalls = chain: jasmine.createSpy()
  Given -&gt; <span class="variable">@dependencies</span> = [CountCalculator, PriceCalculator, TaxCalculator, ShippingCaclulator]
  Given -&gt; ChainsCalls.chain.<span class="keyword">when</span>(<span class="variable">@dependencies</span>, <span class="string">"calculate"</span>).thenReturn(<span class="string">"yay"</span>)
  When -&gt; <span class="variable">@result</span> = Invoice.build()
  Then -&gt; expect(<span class="variable">@result</span>).toEqual(<span class="string">"yay"</span>)</code></pre>
<p>Obviously the above example is more contrived than most similar situations you&#39;ll run into. The point is that when you experience pain while using test doubles, it doesn&#39;t necessarily mean that the test doubles or the practice of using them is to blame.</p>
<p>One thing I&#39;ve learned after several years of trying to become competent at isolation testing: when your tests inflict pain, if you&#39;re unwilling or unable to change the design of your production code, then the extra effort to perform rigorous isolation testing (as opposed to relying on fewer, less granular tests that exercise more of your code) is wasted.</p>
<p>This sentiment is often at mind when building an application hand-in-hand with a framework. When your code serves a framework (say, Rails) and the <em>framework</em> causes pain in your isolation tests (like ActiveRecord might), you&#39;re often stuck in a bind. You can&#39;t reasonably respond to your application&#39;s tests&#39; pain by dramatically refactoring the frameworks on which you depend. As a result, the prudent thing to do is often to try to isolate as much of your application code from the framework as you can and to forfeit isolation testing where it&#39;s too painful (say, where your objects must extend from framework classes).</p>
<p>If, like me, you&#39;re disinclined towards frameworks that rely on users extending framework classes, you can add this justification to your list of reasons why.</p>
]]></description><link>http://searls.testdouble.com/posts/2012-07-19-blame-the-code-not-the-test.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2012-07-19-blame-the-code-not-the-test.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Thu, 19 Jul 2012 00:00:00 GMT</pubDate></item><item><title><![CDATA[on organizational transformation]]></title><description><![CDATA[<p>I have a lot of empathy for people that work at big companies. No one should be required to use a crappy ThinkPad loaded with sluggish, productivity-monitoring software. No one should be forced to communicate through a regimented, politicized hierarchy to do their job. No one should have their actions decided for them by someone else, especially because no one else has a better chance of determining necessary actions than the person who is closest to the work.</p>
<p>And yet, big, rigid companies are everywhere! And they&#39;re brimming with employees! Why?</p>
<p>After a few years of trying to change my own big company employer, I realized that I was never going to succeed—so I quit. As my friend <a href="http://twitter.com/rubybuddha">Leon</a> says, &quot;you can change where you work, or you can change <em>where</em> you work.&quot;</p>
<p>But I was not content to free myself from the shackles of a big company and immediately embrace the liberation I could attain by joining a small company. That seemed like a cop-out; first, I needed to understand why <em>changing even small aspects of a large organization was disproportionately difficult</em>. Surely, thought I, changing large organizations isn&#39;t impossible?</p>
<p>To answer that question for myself, I spent about two years consulting with increasingly large, increasingly change-averse companies. Each organization was tremendously well-adapted to succeed, optimized for their own competitive environment. The only problem: over the course of their growth and evolution, they had each built software development organizations that were failing to deliver consistent results over longer periods of time and at larger scales.</p>
<p>In most cases, these companies had begun building an IT organization when <a href="http://searls.testdouble.com/2011/09/30/the-limits-of-metaphors/">the industrial (read: waterfall) metaphor</a> was prominent. Because command-and-control waterfall software management is so demonstrably ineffective, I was confident that helping a company &quot;transform&quot; into a self-organizing, autonomy-granting agile organization would yield everyone great benefits.</p>
<p>We introduced companies to agile principles, values, and practices. We educated and sold agile to executives. We helped train their developers, who were always highly engaged and excited to learn. At the outset, it always seemed that everyone in the company both recognized which things weren&#39;t working and agreed that the changes prescribed would—if implemented—drastically improve their organization&#39;s effectiveness.</p>
<p>During each engagement, a pilot project that reflected a clean break from the past would succeed <em>wildly</em>. Meanwhile, incremental changes would begin to successfully cascade through the rest of the organization. The first throes of an organizational transformation are highly rewarding (if grueling) work.</p>
<p>But each transformation failed to take hold. Sometimes, they failed spectacularly and all of the change agents within the organization were purged. Sometimes, practices would be retained, but the broader organizational systems would remain soundly intact. And never did I witness a genuine acknowledgement of individual autonomy take root in an organization that had previously been described as &quot;command-and-control&quot;.</p>
<p>And these failures were not for lack of trying hard enough! On every project, everyone always brought their &quot;A&quot;-game. But soon after after the initial successes, it was as if the direction of the wind changed. It was like the organization anthropomorphically woke from its slumber and—upon detecting the presence of a foreign body—quickly excised the changes before uneventfully returning to its dormant state.</p>
<p>I&#39;ve had plenty of time to ponder this and ask myself why this pattern kept repeating.</p>
<p>Over the years, I&#39;ve adopted (and subsequently discarded) numerous metaphors for organizational change. The only metaphor that I still consider apt is evolution. Consider Richard Dawkins&#39; seminal work, <a href="http://en.wikipedia.org/wiki/The_Selfish_Gene">The Selfish Gene</a>. In it, Dawkins demonstrates that not only organisms but even <em>individual genes</em> undergo competition to survive via natural selection. He masterfully extrapolated this discovery: so too do ideas (&quot;memes&quot;) and organizations fight for survival as if by natural selection.</p>
<p>Take dinosaurs, for example. As best I understand it, the world saw such large dinosaurs because of the parameters of their competitive environment. In order to survive and reproduce, many species got caught in a sort of arms race with others; this produced ever-larger, ever-more-powerful dinos. But when the environment changed in a fundamental way, dinosaurs&#39; adaptations were ill-equipped to compete and they died off. The top of the food chain was (and is always), comprised of species that are highly optimized for success in the context of their environment.</p>
<p>But whether we&#39;re speaking of organizations or organisms, there are two catches with all optimizations:</p>
<ul>
<li>Optimizations are <em>contextual</em>. In a fundamentally different environment, a given optimization will most likely be detrimental to success.</li>
<li>Optimizations are <em>specializations</em>. Switching from one optimization to another requires backtracking to some unoptimized point in order to find a new beginning and a fresh start.</li>
</ul>
<p>When the competitive landscape requires an organism to change those optimizations, the path to success is typically slow and counter-intuitive. For species, the outmoded adaptations might become (evolutionarily expensive) vestigial traits. For organizations, the recovery often requires starting a brand new subordinate organization that&#39;s free from the constraints and assumptions the existing organization acquired while attaining their previous success.</p>
<h2>There can be no agility for the highly-optimized</h2>
<p>Big companies aren&#39;t worse than small companies, they&#39;re just more likely to be well-adapted to succeed within their environment. For an organization to undertake operating in a fundamentally different environment, the transformation will always be more costly than it would have been to start a new venture. I believe large software companies are helping us understand this phenomenon, because of software&#39;s distinctly low—and ever-decreasing—barrier of entry (in terms of capital). In my mind, this is why RIM is doomed, why Google will take years to grok social product development, why Facebook will flounder in trying to make money from mobile devices, and why Netflix will be years behind schedule when they finally discard DVD rentals.</p>
<p>To prospective employees of big companies: if everything about the company is a great fit for you, then go for it! But, a warning: view any dissonance between you and the company through a very broad lens: that organization became successful by <em>expressly not</em> doing things the way that you wish they did.</p>
]]></description><link>http://searls.testdouble.com/posts/2012-06-21-on-organizational-transformation.html</link><guid isPermaLink="true">http://searls.testdouble.com/posts/2012-06-21-on-organizational-transformation.html</guid><dc:creator><![CDATA[Justin Searls]]></dc:creator><pubDate>Thu, 21 Jun 2012 00:00:00 GMT</pubDate></item></channel></rss>