<?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/"
	>

<channel>
	<title>The Grimoire</title>
	<atom:link href="http://codex.grimoire.ca/feed/" rel="self" type="application/rss+xml" />
	<link>http://codex.grimoire.ca</link>
	<description>Any insufficiently advanced magic is indistinguishable from technology.</description>
	<pubDate>Fri, 23 Jul 2010 19:32:46 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Abandoning switch In Three (And A Bit) Steps</title>
		<link>http://codex.grimoire.ca/2010/07/23/breaking-away-from-switch/</link>
		<comments>http://codex.grimoire.ca/2010/07/23/breaking-away-from-switch/#comments</comments>
		<pubDate>Fri, 23 Jul 2010 19:32:46 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Examples]]></category>

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=163</guid>
		<description><![CDATA[Everyone who&#8217;s worked in a C-derived language has seen a switch statement or two in their lives. There are a few well-known reasons not to use them, but somehow they crop up now and then anyways because they&#8217;re just so convenient — initially.
Switch is a holdover from lower-level languages (mostly, various assembly languages) where the [...]]]></description>
			<content:encoded><![CDATA[<p>Everyone who&#8217;s worked in a C-derived language has seen a <code>switch</code> statement or two in their lives. There are a few well-known reasons not to use them, but somehow they crop up now and then anyways because they&#8217;re just so convenient — initially.</p>
<p>Switch is a holdover from lower-level languages (mostly, various assembly languages) where the destination of a <code>jmp</code> instruction could be computed or looked up in a table. In modern languages, there are usually more appropriate structures for determining which piece of code to jump to: that&#8217;s what <a href="http://en.wikipedia.org/wiki/Virtual_method_table">virtual dispatch</a> does, for example.</p>
<p>Unfortunately, it&#8217;s not always obvious how to &#8220;fix&#8221; code that makes heavy use of <code>switch</code>. </p>
<p><span id="more-163"></span></p>
<p>I normally try to avoid this, but for the sake of clarity I&#8217;ve omitted a couple of good style points. Online presentation makes certain Java conventions difficult to present; just because the following examples use a single compilation unit with default-visibility symbols doesn&#8217;t mean you should, too.</p>
<h3>Starting Points</h3>
<p>Let&#8217;s take a simple example that uses a <code>switch</code> statement to control the state of some service. The surrounding context involves a simple control protocol for a light dimmer: it can either be turned fully off, turned fully on, or set to a &#8220;dim&#8221; state halfway between the two.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> States <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> OFF <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> DIM <span style="color: #339933;">=</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000066; font-weight: bold;">int</span> ON <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> DimmerController <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setIntensity<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        doStuffBeforeChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span>intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">case</span> OFF<span style="color: #339933;">:</span>
                disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">case</span> DIM<span style="color: #339933;">:</span>
                beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">case</span> ON<span style="color: #339933;">:</span>
                beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        doStuffAfterChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Eminent Domain</h3>
<p>There are a few obvious problems with the version above. For starters, there&#8217;s nothing preventing someone from passing the wrong value, either from the wrong set of constants or by hard-coding the literal values instead of using the constants. We could add a <code>default</code> clause that raises an <code>IllegalArgumentException</code>, but we&#8217;d still only find out about the problem at runtime. We&#8217;d really like to find out about errors in our programs as early as possible: compile time, or even as we type them. Most languages provide a tool for doing that; since we&#8217;re using Java, we&#8217;ll use an <code>enum</code>.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">enum</span> State <span style="color: #009900;">&#123;</span>
    OFF,
    DIM,
    ON
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> DimmerController <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setIntensity<span style="color: #009900;">&#40;</span>State intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        doStuffBeforeChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">switch</span> <span style="color: #009900;">&#40;</span>intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">case</span> OFF<span style="color: #339933;">:</span>
                disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">case</span> DIM<span style="color: #339933;">:</span>
                beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
            <span style="color: #000000; font-weight: bold;">case</span> ON<span style="color: #339933;">:</span>
                beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        doStuffAfterChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>On Your Best Behaviour</h3>
<p>That&#8217;s better, but it still has most of the fundamental problems <code>switch</code> statements bring with them. While I&#8217;m only showing one <code>switch</code>, apps that have them tend to have multiple <code>switch</code>es over the same set of constants, which leads to code duplication throughout the app and makes it hard to determine what a given constant will cause the system to do. In an object-oriented system, we normally try to keep behaviour with the data it works with, and as a side effect of refactoring to using an enumerated type, we now have real objects to use. Let&#8217;s add some methods to our enumerated type to handle the per-case behaviour.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">enum</span> State <span style="color: #009900;">&#123;</span>
    OFF<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>,
    DIM<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>,
    ON<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> DimmerController <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setIntensity<span style="color: #009900;">&#40;</span>State intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        doStuffBeforeChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        intensity.<span style="color: #006633;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        doStuffAfterChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Opening the Set</h3>
<p>You can stop here and have a reasonably well-structured program. The specifics of what each constant means are stored with the constant, and it&#8217;s now impossible to pass an illegal value into <code>setIntensity</code>. However, we&#8217;ve still embedded into <code>DimmerController</code> the assumption that we will only ever be setting the intensity of a three-state light - but we don&#8217;t actually use that assumption anywhere. We can refactor further to eliminate this dependency by realizing that <code>State</code>&#8217;s public interface really represents any arbitrary dimmer state callback:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">&nbsp;
<span style="color: #000000; font-weight: bold;">interface</span> State <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">enum</span> DimmerState <span style="color: #000000; font-weight: bold;">implements</span> State <span style="color: #009900;">&#123;</span>
    OFF<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>,
    DIM<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>,
    ON<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">/* ... */</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000066; font-weight: bold;">void</span> apply<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> DimmerController <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setIntensity<span style="color: #009900;">&#40;</span>State intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        doStuffBeforeChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        intensity.<span style="color: #006633;">apply</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        doStuffAfterChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Everything In Its Place</h3>
<p>On the other hand, sometimes the heavy lifting (in our case, the work of actually changing the intensity of a light) actually belongs outside the enumeration. This is true most of the time: enumerations can&#8217;t hold per-use state, and creating a new <code>State</code> instance (from the interface-based example above) for each light isn&#8217;t always appropriate. We can pull those methods back out of the enumeration by introducing a third class to act as a callback for the <code>apply</code> method:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">enum</span> State <span style="color: #009900;">&#123;</span>
    OFF<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> applyTo<span style="color: #009900;">&#40;</span>DimmerCallback dimmerCallback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            dimmerCallback.<span style="color: #006633;">disable</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>,
    DIM<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> applyTo<span style="color: #009900;">&#40;</span>DimmerCallback dimmerCallback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            dimmerCallback.<span style="color: #006633;">beginDimCycle</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>,
    ON<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> applyTo<span style="color: #009900;">&#40;</span>DimmerCallback dimmerCallback<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            dimmerCallback.<span style="color: #006633;">beginFullCycle</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000066; font-weight: bold;">void</span> applyTo<span style="color: #009900;">&#40;</span>DimmerCallback dimmerCallback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #666666; font-style: italic;">/* or interface */</span> DimmerCallback <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> disable<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginDimCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000066; font-weight: bold;">void</span> beginFullCycle<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">/* ... */</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> DimmerController <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Or from dependency injection, or...</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> DimmerCallback dimmerCallback <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> DimmerCallback<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setIntensity<span style="color: #009900;">&#40;</span>State intensity<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        doStuffBeforeChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        intensty.<span style="color: #006633;">applyTo</span><span style="color: #009900;">&#40;</span>dimmerCallback<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        doStuffAfterChangingIntensity<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Ok, But I Have This Integer</h3>
<p>In most of the cases where people feel compelled to use magic ints or an enumerated type, there&#8217;s an external force at work. The most common scenario involves file formats or network protocols where an integer or short known string needs to map directly to program behaviour. With the behaviour separated out into a real type with testable features, you lose the ability to near-blindly pass the protocol value directly into your logic.</p>
<p>Remember when I said that <code>switch</code> statements are really a giant lookup table? That should give you a hint. You can still use a lookup table to convert from an external representation to an internal one; depending on how far down the chain of refactorings you&#8217;ve gone, you may even get one for free. Consider the following, assuming we still have a <code>State</code> enumeration:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> State parseRequestedState<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> state<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">ProtocolException</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> State.<span style="color: #006633;">values</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span>state<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">IndexOutOfBoundsException</span> ioobe<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> UnexpectedValueException<span style="color: #009900;">&#40;</span>ioobe<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Java&#8217;s enumeration support gives us the lookup table we need for free. We can do the same thing with strings, if they happen to match the enum constants&#8217; names; alternately, we can use an explicit lookup table stored in an array or a <code>HashMap</code>. There are also plenty of strategies for automatically populating a lookup table using mechanisms like classpath scanning, <a href="http://download.oracle.com/docs/cd/E17409_01/javase/6/docs/api/java/util/ServiceLoader.html"><code>ServiceLoader</code></a>, annotation processing tools, and so on.</p>
<p>There are lots of places to go from here. For example, enum-based implementations of the <a href="http://c2.com/cgi/wiki?StatePattern">state object pattern</a> begin with a very similar refactoring. In languages without strong enums, the structure outlined here can be implemented using normal classes with a fixed pool of instances, instead (Java&#8217;s enum support does exactly that, under the hood), skipping directly to the interface-based version near the end.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2010/07/23/breaking-away-from-switch/feed/</wfw:commentRss>
		</item>
		<item>
		<title>God Money, I&#8217;ll do anything for you</title>
		<link>http://codex.grimoire.ca/2010/01/08/php-fread-sucks/</link>
		<comments>http://codex.grimoire.ca/2010/01/08/php-fread-sucks/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 18:54:24 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Finite Hate Machine]]></category>

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=143</guid>
		<description><![CDATA[The loop

1
2
3
4
5
&#60;?php
while &#40;$read &#60; $n &#38;&#38; &#40;false !== &#40;$buf = fread&#40;$this-&#62;sock, $n - $read&#41;&#41;&#41;&#41; &#123;
    /* ... */
&#125;
?&#62;

contains a subtle bug. Go ahead, read the relevant function documentation and see if you can spot it.

PHP&#8217;s fread function directly maps the C library&#8217;s fread function. As TBlue explains, the C fread function returns [...]]]></description>
			<content:encoded><![CDATA[<p>The loop</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$read</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$n</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">false</span> <span style="color: #339933;">!==</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$buf</span> <span style="color: #339933;">=</span> <span style="color: #990000;">fread</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sock</span><span style="color: #339933;">,</span> <span style="color: #000088;">$n</span> <span style="color: #339933;">-</span> <span style="color: #000088;">$read</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>contains a subtle bug. Go ahead, read the <a href="http://php.net/manual/en/function.fread.php">relevant function documentation</a> and see if you can spot it.</p>
<p><span id="more-143"></span></p>
<p>PHP&#8217;s <code>fread</code> function directly maps the C library&#8217;s <code>fread</code> function. As <a href="http://www.php.net/manual/en/function.fread.php#95413">TBlue</a> explains, the C <code>fread</code> function returns <code>0</code> when reading at the end of a stream. PHP does the simplest possible thing with this and returns an empty string; to determine that the stream is at end of file, programs must check with <code>feof</code> as well.</p>
<p>Most modern languages realize that explicitly checking for errors is a fairly error-prone convention. Java&#8217;s <a href="http://java.sun.com/javase/6/docs/api/java/io/InputStream.html#read(byte[])">InputStream.read(byte[])</a> methods return -1 on EOF (and only on EOF) and raise exceptions on errors. Python&#8217;s <a href="http://docs.python.org/library/stdtypes.html#file-objects">File-like objects</a> convention supports mechanisms other than raw byte reads (primarily, iteration) that make stopping at end of file implicit, on top of only returning an empty string at end of input (as with Java, Python raises exceptions when a stream read fails). Not PHP, though! In PHP, the loop above has to look like</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$read</span> <span style="color: #339933;">&lt;</span> <span style="color: #000088;">$n</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span><span style="color: #990000;">feof</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sock</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">false</span> <span style="color: #339933;">!==</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$buf</span> <span style="color: #339933;">=</span> <span style="color: #990000;">fread</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">sock</span><span style="color: #339933;">,</span> <span style="color: #000088;">$n</span> <span style="color: #339933;">-</span> 
<span style="color: #000088;">$read</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
<span style="color: #009900;">&#125;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Encountered in the wild: <a href="http://code.google.com/p/php-amqplib/issues/detail?id=12">php-amqplib bug #12</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2010/01/08/php-fread-sucks/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Singling Out to Spring</title>
		<link>http://codex.grimoire.ca/2009/03/11/singling-out-to-spring/</link>
		<comments>http://codex.grimoire.ca/2009/03/11/singling-out-to-spring/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 15:43:39 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Examples]]></category>

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

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=98</guid>
		<description><![CDATA[Last time, I wrote about why Singletons get a bad rap, and I wrote some high-level advice for moving away from them sanely. I want to cover a practical (if somewhat idealistic) example using Java and Spring to move a Singleton creation dependency out of a class.

First, a quick terminology aside. The term &#8220;Singleton&#8221; is [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://codex.grimoire.ca/2009/03/10/singled-out/">Last time</a>, I wrote about why Singletons get a bad rap, and I wrote some high-level advice for moving away from them sanely. I want to cover a practical (if somewhat idealistic) example using Java and Spring to move a Singleton creation dependency out of a class.<br />
<span id="more-98"></span><br />
First, a quick terminology aside. <a href="http://mathworld.wolfram.com/SingletonSet.html">The term &#8220;Singleton&#8221; is actually drawn from set theory</a>, where it means &#8220;a set with only one element&#8221;. The set of integers that equal 5 is a singleton. The analogy is that types (which are sets of values) that are Singletons also only have one value (the Singleton instance). This has caused a bit of confusion.</p>
<p>The Singleton pattern specifically refers to the object creational pattern where a class manages a single instance of itself and, usually, forbids other instances from existing. There&#8217;s also the &#8220;singleton&#8221; <a href="http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-factory-scopes">scope</a> in Spring, which means something more limited: Spring will only create one instance of the bean. Don&#8217;t confuse the arguments that Singleton classes are a bad idea for arguments that objects you only have one of are a bad idea.</p>
<p>I mention this because Spring scopes come up in the following examples, and the default Spring scope is also called <code>singleton</code>. Now, with that out of the way, on with the show.</p>
<h3>Moving a Singleton creation dependency to Spring</h3>
<p>Injecting a singleton into its clients involves replacing code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Mailer <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Mailer instance <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Mailer getInstance <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> instance<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sendMail <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> recipient, <span style="color: #003399;">String</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">printf</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;I am sending %s to %s!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>,
      message, recipient<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">/* Using a Struts2 Action as an example &quot;client&quot; */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SendMailAction <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setRecipient <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> recipient<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">recipient</span> <span style="color: #339933;">=</span> recipient<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setMessage <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">message</span> <span style="color: #339933;">=</span> message<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> execute <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    Mailer.<span style="color: #006633;">getInstance</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">sendMail</span> <span style="color: #009900;">&#40;</span>recipient, message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> message<span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> recipient<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>with code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SendMailAction <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> SendMailAction <span style="color: #009900;">&#40;</span>Mailer mailer<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">mailer</span> <span style="color: #339933;">=</span> mailer<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setRecipient <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> recipient<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">recipient</span> <span style="color: #339933;">=</span> recipient<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setMessage <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">message</span> <span style="color: #339933;">=</span> message<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> execute <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    mailer.<span style="color: #006633;">sendMail</span> <span style="color: #009900;">&#40;</span>recipient, message<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Mailer mailer<span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> message<span style="color: #339933;">;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">String</span> recipient<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The corresponding Spring configuration file looks like</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;mailer&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;ca.grimoire.examples.Mailer&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">factory-method</span>=<span style="color: #ff0000;">&quot;getInstance&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;action&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">scope</span>=<span style="color: #ff0000;">&quot;request&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;ca.grimoire.examples.SendMailAction&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;constructor-arg</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;mailer&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
  <span style="color: #808080; font-style: italic;">&lt;!-- more definitions --&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>If getInstance, for some reason, needs parameters, they can be passed as <code><constructor-arg></code> elements nested inside its bean definition.</p>
<p>You can now write isolated tests for <code>SendMailAction</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Using JMock rather than a hand-crafted alternate implementation.</span>
@RunWith<span style="color: #009900;">&#40;</span>JMock.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SendMailTest <span style="color: #009900;">&#123;</span>
  <span style="color: #666666; font-style: italic;">// This requires some extension to work with class mocks</span>
  <span style="color: #666666; font-style: italic;">// See http://www.jmock.org/mocking-classes.html</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">final</span> Mockery mockery <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JUnit4Mockery<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#123;</span>
    setImposteriser<span style="color: #009900;">&#40;</span>ClassImposteriser.<span style="color: #006633;">INSTANCE</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
  @Test
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sendsExpectedMessage <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">final</span> Mailer mailer <span style="color: #339933;">=</span> mockery.<span style="color: #006633;">mock</span> <span style="color: #009900;">&#40;</span>Mailer.<span style="color: #000000; font-weight: bold;">class</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    mockery.<span style="color: #006633;">checking</span> <span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Expectations <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><span style="color: #009900;">&#123;</span>
      oneOf <span style="color: #009900;">&#40;</span>mailer<span style="color: #009900;">&#41;</span>.<span style="color: #006633;">sendMail</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Recipient&quot;</span>, <span style="color: #0000ff;">&quot;Hello World&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    SendMailAction action <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SendMailAction <span style="color: #009900;">&#40;</span>mailer<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    action.<span style="color: #006633;">setRecipient</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Recipient&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    action.<span style="color: #006633;">setMessage</span> <span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Hello World&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    action.<span style="color: #006633;">execute</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Prior to this change, writing a test for SendMailAction that did not also involve Mailer would&#8217;ve been difficult and error-prone.</p>
<h3>Injecting dependencies into Singletons</h3>
<p>You can also inject dependencies, including other Singleton instances, into a Singleton instance, which is helpful for breaking Singleton graphs. Let&#8217;s give <code>Mailer</code> another Singleton it depends on:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SmtpConnection <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> SmtpConnection instance <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SmtpConnection <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> SmtpConnection getInstance <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> instance<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">PrintStream</span> getSmtpStream <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Mailer <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Mailer instance <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Mailer getInstance <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> instance<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sendMail <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> recipient, <span style="color: #003399;">String</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    SmtpConnection connection <span style="color: #339933;">=</span> SmtpConnection.<span style="color: #006633;">getInstance</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    connection.<span style="color: #006633;">getSmtpStream</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">printf</span> <span style="color: #009900;">&#40;</span>
      <span style="color: #0000ff;">&quot;I am sending %s to %s!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, message, recipient<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>You can move this dependency into Spring if you change Mailer:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Mailer <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Mailer instance <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Mailer getInstance <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> instance<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> setConnection <span style="color: #009900;">&#40;</span>SmtpConnection connection<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">connection</span> <span style="color: #339933;">=</span> connection<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sendMail <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> recipient, <span style="color: #003399;">String</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    connection.<span style="color: #006633;">getSmtpStream</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">printf</span> <span style="color: #009900;">&#40;</span>
      <span style="color: #0000ff;">&quot;I am sending %s to %s!<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span>, message, recipient<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">private</span> SmtpConnection connection<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The corresponding Spring configuration looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;beans</span> <span style="color: #000066;">xmlns</span>=<span style="color: #ff0000;">&quot;http://www.springframework.org/schema/beans&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;connection&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;ca.grimoire.examples.SmtpConnection&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">factory-method</span>=<span style="color: #ff0000;">&quot;getInstance&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
&nbsp;
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;bean</span> <span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;mailer&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">class</span>=<span style="color: #ff0000;">&quot;ca.grimoire.examples.Mailer&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">factory-method</span>=<span style="color: #ff0000;">&quot;getInstance&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
    <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;property</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;connection&quot;</span> <span style="color: #000066;">ref</span>=<span style="color: #ff0000;">&quot;connection&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/bean<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
&nbsp;
  <span style="color: #808080; font-style: italic;">&lt;!-- more definitions --&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/beans<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<p>Even clients who aren&#8217;t using Spring to inject the <code>Mailer</code> Singleton can be used with this, so long as the Spring injection happens before anything tries to use the <code>Mailer</code>.</p>
<p>Without an interface limiting the operations, though, clients of <code>Mailer</code> may decide to call <code>setConnection</code> - <em>don&#8217;t do this</em> because it becomes a form of mutable global state. If you&#8217;re going to follow this route, either force clients to use a narrower interface without the setters or be very careful about code review.</p>
<address>Edited at Mar 11, 2009 @ 10:43: <a href="http://dashi.ca/blog/">Taavi</a> pointed out that my SmtpConnection Spring example was still calling <code>getInstance</code>. Whoops!</address>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2009/03/11/singling-out-to-spring/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Singled Out</title>
		<link>http://codex.grimoire.ca/2009/03/10/singled-out/</link>
		<comments>http://codex.grimoire.ca/2009/03/10/singled-out/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 02:24:05 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Manifestos and Rants]]></category>

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

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

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=78</guid>
		<description><![CDATA[One of my colleagues blindsided me the other day with a question about software architecture that I should&#8217;ve been able to answer on the spot: &#8220;Are singletons really all that bad?&#8221;


Singletons aren&#8217;t popular by accident, though. In most modern object-oriented systems, there is a constellation of core classes which, in the final system, only need [...]]]></description>
			<content:encoded><![CDATA[<p>One of my colleagues blindsided me the other day with a question about software architecture that I should&#8217;ve been able to answer on the spot: &#8220;Are singletons really all that bad?&#8221;<br />
<span id="more-78"></span><br />
<!--<br />
* What's a singleton?<br />
* What are the consequences?<br />
 * Only one instance of the class exists.<br />
 * That instance can be referenced from anywhere.<br />
--></p>
<p>The Singleton pattern is one of the common solutions identified in <a href="http://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional/dp/0201633612">Design Patterns</a>. At its core, a <a href="http://c2.com/cgi/wiki?SingletonPattern">Singleton</a> is a class that only allows one instance. All clients of the class will operate against the same instance. The implementation outlined in Design Patterns provides a class-level function replacing the class&#8217; constructor in its public API which manages the existence of the singleton instance.</p>
<p>A fairly stock Java Singleton implementation for, for example, sending mail runs like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Mailer <span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> Mailer instance <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Mailer getInstance <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> instance<span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">/* Note the access specifier: no other class can access this
     constructor. */</span>
  <span style="color: #000000; font-weight: bold;">private</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> sendMail <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> recipient, <span style="color: #003399;">String</span> message<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">/* ... */</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p><!--<br />
* What are the costs of only having a single instance? (Manageable.)<br />
 * Any clients of the singleton must not modify its state (singletons that call other services that are being stubbed in).<br />
 * Impact on garbage collection?<br />
 * Impact on synchronization?<br />
 * "Workaround" methods for creating multiple instances may invalidate singleton assumptions.<br />
  * Examples (Logger managers like log4j, global transaction management)<br />
  * Multiple singletons come up naturally in containerized applications, where multiple classloaders or appdomains are part of deployment.<br />
 * Ultimately not a big deal.<br />
 * Can be the Right Thing<br />
  * Accurately models the problem (Runtime in Java)<br />
  * Appropriate client interface (Logger in Log4j)<br />
--></p>
<p>From an implementor&#8217;s point of view, Singleton classes cost almost nothing, either in terms of extra code to maintain or in terms of assumptions to test. In the average application, each class providing some service to the application only has one instance, so constraining the class to <em>only</em> one instance isn&#8217;t a huge leap. These kinds of classes tend to be stateless, or almost stateless, so clients don&#8217;t necessarily need to be aware that they&#8217;re sharing instances with other clients as there are no extra synchronization or garbage collection hazards to handle. There are even times when Singletons are the right thing: either they accurately model some aspect of the problem where only a single representative can exist (for example, Java&#8217;s <code>Runtime</code> class, which exposes services provided by the JVM running the program), or the resulting API is compellingly simple and easy to use (for example, Log4J&#8217;s <code>Logger</code>, which is effectively backed by a Singleton registry of Logger instances).</p>
<p>Implementing a Singleton correctly can easily depend on the dark corners of the language&#8217;s object model. The most common source of Singleton implementation bugs are caused by language or deployment models that scope &#8220;global&#8221; state to only part of the system. Networked systems can easily have an instance on every node, and applications that have multiple <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.aspx">AppDomains</a> or <a href="http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html">ClassLoaders</a> can easily create multiple Singleton instances in a single address space. In multithreaded apps (that is, almost anything written this decade), Singletons can also be threading hazards: if they manage access to an external resource, then it&#8217;s very easy to build a synchronization bottleneck into your entire application in the name of keeping access to that resource thread-safe.</p>
<p><!--<br />
* What are the costs of calling getInstance everywhere? (Huge.)<br />
 * Difficult or impossible to replace the singleton with a stub (eg., for testing).<br />
 * No "traction" for applying behaviour-modifying patterns (decorator, proxy, AOP).<br />
 * Embeds an assumption that every other client of the (implicit?) interface is using the same implementation.<br />
 * Easy to accidentally create huge meshes of singletons in a single call if singletons depend on each other.<br />
 * Comes up with any inline creation technique.<br />
  * 'new'ing dependencies is bad!<br />
  * Use dependency injection techniques to factor out creation.<br />
--></p>
<p>Singletons cause most of the problems associated with them on the consumer side. The most common implementation pattern for Singleton clients is very simple: every occurrence of</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Mailer m <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Mailer <span style="color: #009900;">&#40;</span><span style="color: #666666; font-style: italic;">/* ... */</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>gets replaced with</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Mailer m <span style="color: #339933;">=</span> Mailer.<span style="color: #006633;">getInstance</span> <span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This wins <em>nothing</em>: the client is tightly bound to a number of assumptions about the identity and lifecycle of the provider. In fact, it loses a little: instead of giving each client its own isolated state, now there&#8217;s a guarantee that some state is shared between client instances, via the Singleton instance. There are also knock-on effects: because the client controls exactly which provider it uses, it&#8217;s difficult to isolate only the client class for testing. It also becomes difficult, if not impossible, to insert behaviour between the client and the singleton provider - no <a href="http://www.onjava.com/pub/a/onjava/2004/01/14/aop.html">AOP</a>, no <a href="http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSProxy_Class/index.html">proxies</a>, and no <a ref="http://pyro.sourceforge.net/">remoting</a>, without making invasive changes to the client or the singleton.</p>
<p>Over the long term, as software evolves, patterns tend to propagate. Inline <code>getInstance()</code> calls for Singleton clients tend to get repeated in new code. In a sufficiently evolved codebase that uses Singletons extensively, a badly-placed <code>getInstance()</code> call can easily cause half the objects in the system to spring into being and initialize themselves. Even when this doesn&#8217;t cause performance issues on some code paths, it can easily cause startup and initialization order to become unpredictable during apparently-safe changes. Remembering which code paths are &#8220;supposed&#8221; to initialize singletons becomes an extra form of friction for developers working on the codebase.</p>
<p><!--<br />
* Why do developers create singletons?<br />
 * Developers create singletons because they're convenient.<br />
  * Compare implementing an injected dependency (Java + Spring) to a singleton, with code samples.<br />
 * Incorrect extrapolation from only needing a single instance to only allowing a single instance.<br />
--></p>
<p>Singletons aren&#8217;t popular by accident, though. In most modern object-oriented systems, there is a constellation of core classes which, in the final system, only need to exist once. The <code>Mailer</code> example I&#8217;ve been using is actually a good example: if it manages connections to the underlying mail system itself in a sane way, then there probably only needs to be a single instance of <code>Mailer</code> in the deployed app. If <code>Mailer</code> handles any connection pooling, then ensuring the creation of new instances is carefully controlled becomes almost mandatory. Singletons provide a really simple way to provide a single instance to an application.</p>
<p>Most development time, thought, and effort goes into the code paths that get used in the final product, so there&#8217;s an easy conceptual leap to make from &#8220;the system I&#8217;m building only needs one instance&#8221; to &#8220;this object should only allow one instance.&#8221; Developers without fairly extensive experience with <a href="http://www.mockobjects.com/">mocking</a> and other unit-testing techniques, or who don&#8217;t value the ability to insert new behaviour without changing existing code, can easily see no problem with using Singletons to manage lifetime <em>and to provide access to the instance</em>, since it&#8217;s <a href="http://www.jwz.org/doc/worse-is-better.html">convenient</a>.</p>
<p>There are alternatives to Singletons for managing service objects: the standard Java examples are <a href="http://java.sun.com/products/ejb/">EJBs</a>, which delegates control over object lifecycles to the app container, and <a href="http://www.springsource.org/about">Spring</a>, which <a href="http://martinfowler.com/articles/injection.html">takes responsibility for lifecycle management and wiring between providers and consumers</a> within the app. Other languages have similar tools available, either in the language or as a library. However, these tools have a higher barrier to entry than &#8220;just another Singleton&#8221;: even the simplest inversion of control implementation is more lines of code than a Singleton.</p>
<p>The kinds of problems Singletons cause only really become problems in medium-sized and larger codebases. Not coincidentally, medium-sized and larger codebases tend to be the product of long evolution from a small, relatively clean initial product, which means there&#8217;s been lots of time for people to forget the program&#8217;s overall structure. Refactoring to clean up the problems isn&#8217;t difficult, but surprisingly little has been written about it.</p>
<p><!--<br />
* What do we fix first?<br />
 * Context of a large (500,000 LOC) system with lots of singletons.<br />
 * Moving creation of single objects out of singletons is low-reward, high-risk.<br />
  * Touches the singleton class and every client at once.<br />
  * Doesn't affect the flexibility or testability of the singleton much.<br />
 * Moving obtaining an instance out of clients is high-reward, low-risk.<br />
  * Can be done one client at a time.<br />
  * Dramatically improves testability and compsability/flexibility.<br />
--></p>
<p>For most Singletons, where obtaining an instance is a parameter-less call to a <code>getInstance()</code>-like method, refactoring that call out to an injected dependency via a constructor or method parameter is a low-risk change that can be made and tested for one class at a time. Most, if not all, <code>getInstance()</code> calls follow a very simple, predictable code path, which means there are no side effects to take care of, and no changes at all have to happen in the provider. The only potential &#8220;gotcha&#8221; is the first call, which may do initialization work. This kind of change also has high rewards: injected dependencies can be replaced with alternate implementations, which makes testing much easier and lets you augment or replace the implementation without altering the clients.</p>
<p>There&#8217;s more risk in changing the Singleton itself first. Refactoring the lifecycle management code out of the Singleton and into a higher layer does help, but while clients are calling <code>getInstance()</code> directly, any change to the lifecycle management means changing <em>every</em> client at the same time, which in turn means you need to re-test all of those clients. Once the clients have been refactored, though, it&#8217;s much safer and easier to change the lifecycle managment.</p>
<p>Singletons are not the <a href="http://blogs.msdn.com/scottdensmore/archive/2004/05/25/140827.aspx">Great Evil</a> they&#8217;re sometimes depicted as. However, they&#8217;re used in a lot of situations as a crutch to avoid writing real inter-object dependency management, <a href="http://steve.yegge.googlepages.com/singleton-considered-stupid">to the detriment of software using them</a>. Their convenience can outweigh the problems, especially in small systems or prototypes, but you need to have a way out when they start to cause problems.</p>
<p>Next time: implementation examples, for Spring.</p>
<address>Edited at March 11, 2009 at 12:45 am: I weeded the links a bit - it sounded too much like Jeff Atwood. If you want to know what I removed, drop a comment.<br />
Edited again at March 12, 2009 at 2:23 pm: HTML fail. Thanks, Justin!</address>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2009/03/10/singled-out/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Automatic Code Formatting and Merges</title>
		<link>http://codex.grimoire.ca/2009/01/10/automatic-code-formatting-and-merges/</link>
		<comments>http://codex.grimoire.ca/2009/01/10/automatic-code-formatting-and-merges/#comments</comments>
		<pubDate>Sat, 10 Jan 2009 20:21:14 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=75</guid>
		<description><![CDATA[&#8230;or, how to give other developers screaming nightmares in 10 seconds flat.
The next time you think to reach for the &#8220;reformat source code&#8221; button in your IDE, think twice before you press it. Automatic reformatting is a great way to turn a small merge hazard contained to a single method into a huge merge hazard [...]]]></description>
			<content:encoded><![CDATA[<p>&#8230;or, how to give other developers screaming nightmares in 10 seconds flat.</p>
<p>The next time you think to reach for the &#8220;reformat source code&#8221; button in your IDE, think twice before you press it. Automatic reformatting is a great way to turn a small merge hazard contained to a single method into a huge merge hazard affecting an entire file. Merge tools are relatively stupid: in general, they&#8217;re not aware of the syntactic structure of a source file, just the text by lines; as a result, it&#8217;s very easy to fool them into thinking a one-line change and a reformat are a conflict covering the entire file.</p>
<p>If you&#8217;re using automatic formatting tools, please check with the other developers on your project and make sure that your code formatter settings agree with theirs.  If you can&#8217;t make that happen, then don&#8217;t reformat code unless everyone&#8217;s nobody but you is touching those files.</p>
<p>Please, think of the merges.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2009/01/10/automatic-code-formatting-and-merges/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Shameless Self-Promotion: LDAP Outside the Enterprise</title>
		<link>http://codex.grimoire.ca/2008/11/19/shameless-self-promotion-ldap-outside-the-enterprise/</link>
		<comments>http://codex.grimoire.ca/2008/11/19/shameless-self-promotion-ldap-outside-the-enterprise/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 05:18:14 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

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

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

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=62</guid>
		<description><![CDATA[Last week I set up LDAP as a central authentication/identity store for the Toronto Hacklab. I thought I&#8217;d share my notes. It went well enough that I&#8217;m going to repeat the process with the Grimoire: right now each part of the site (Wordpress, WebDAV for various repositories, JIRA, and Hudson) handles its own authentication, and [...]]]></description>
			<content:encoded><![CDATA[<p>Last week I set up LDAP as a central authentication/identity store for the <a href="http://hacklab.to">Toronto Hacklab</a>. I thought I&#8217;d <a href="http://hacklab.to/archives/ldap-outside-the-enterprise/">share my notes</a>. It went well enough that I&#8217;m going to repeat the process with the Grimoire: right now each part of the site (Wordpress, WebDAV for various repositories, JIRA, and Hudson) handles its own authentication, and it&#8217;s gotten unmanageable.</p>
<p>Yes, there is only one user. Yes, I still think it&#8217;s worthwhile.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2008/11/19/shameless-self-promotion-ldap-outside-the-enterprise/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Annotation Processing and the Pernicious // TODO</title>
		<link>http://codex.grimoire.ca/2008/11/18/annotation-processing-and-the-pernicious-todo/</link>
		<comments>http://codex.grimoire.ca/2008/11/18/annotation-processing-and-the-pernicious-todo/#comments</comments>
		<pubDate>Wed, 19 Nov 2008 04:40:14 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

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

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=55</guid>
		<description><![CDATA[Raise your hand if you&#8217;ve ever put a // TODO comment in your source code. Or // FIXME, // XXX, or any of the thousands of other variants programmers have been using since before there was dirt to mark places that need further work.
Now raise your hand if your compiler or build tool can tell [...]]]></description>
			<content:encoded><![CDATA[<p>Raise your hand if you&#8217;ve ever put a <code>// TODO</code> comment in your source code. Or <code>// FIXME</code>, <code>// XXX</code>, or any of the thousands of other variants programmers have been using since before there was dirt to mark places that need further work.</p>
<p>Now raise your hand if your compiler or build tool can tell you about them.<br />
<span id="more-55"></span><br />
That&#8217;s been a personal itch of mine for a while, so I took the chance to scratch it and learn the Java annotation processing API at the same time. The result: <a href="http://alchemy.grimoire.ca/m2/sites/ca.grimoire/todo-annotations/1.0/">TODO Annotations</a>, a set of annotations intended to replace <code>// TODO</code> comments with something easier to check. Now I can have <a href="http://alchemy.grimoire.ca/hudson/">my build server</a> complain and die when FIXMEs go un-fixed without imposing the same stricture on my development environment.</p>
<p>You can grab <a href="http://alchemy.grimoire.ca/hg/todo-annotations">the source</a> and bang on it - it provides a decent &#8220;hello world&#8221; example of working with the compiler. For more information on what the API can do, check <a href="http://java.sun.com/javase/6/docs/api/javax/annotation/processing/package-summary.html">the annotation processing API</a>, as well as <a href="http://java.sun.com/javase/6/docs/api/javax/lang/model/package-summary.html">the</a> <a href="http://java.sun.com/javase/6/docs/api/javax/lang/model/element/package-summary.html">language</a> <a href="http://java.sun.com/javase/6/docs/api/javax/lang/model/type/package-summary.html">model</a> <a href="http://java.sun.com/javase/6/docs/api/javax/lang/model/util/package-summary.html">API</a>, and the <a href="http://java.sun.com/javase/6/docs/technotes/guides/apt/index.html">Annotation Processing Tool</a> docs. Patches, bug reports, and feedback are <a href="mailto:owen.jacobson@grimoire.ca">always welcome</a>. <a href="http://alchemy.grimoire.ca/m2/releases/ca/grimoire/todo-annotations/">Binaries</a> are also available in <a href="http://alchemy.grimoire.ca/m2/">the Maven repository</a>.</p>
<p>Or, you can use the <a href="http://mojo.codehaus.org/taglist-maven-plugin/">Maven taglist plugin</a> - but then you&#8217;re stuck with Maven.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2008/11/18/annotation-processing-and-the-pernicious-todo/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Nobody Cares About Your Makefile</title>
		<link>http://codex.grimoire.ca/2008/10/01/nobody-cares-about-your-makefile/</link>
		<comments>http://codex.grimoire.ca/2008/10/01/nobody-cares-about-your-makefile/#comments</comments>
		<pubDate>Thu, 02 Oct 2008 02:20:52 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

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

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=28</guid>
		<description><![CDATA[GNU Make is a relatively modern version of one of the oldest build tools still in regular use. Make has existed since 1977 and is still the standard tool for building native software in Unix-derived environment. The pattern Make established, based on using a directed graph to automate builds, is still in use in more [...]]]></description>
			<content:encoded><![CDATA[<p>GNU Make is a relatively modern version of one of the oldest build tools still in regular use. Make has existed since 1977 and is still the standard tool for building native software in Unix-derived environment. The pattern Make established, based on using a directed graph to automate builds, is still in use in more recent tools.<br />
<span id="more-28"></span></p>
<h3>make understanding</h3>
<p>Make&#8217;s basic approach to building software is based on walking <a href="http://mathworld.wolfram.com/DirectedGraph.html">directed graphs</a>. Each node of a Makefile&#8217;s graph represents a file, and the arrows point to other nodes representing dependencies. Make begins at the nodes named on the command line and follows the arrows to determine which other nodes to build first.</p>
<p>Make reads the graph, and the actions required to build any files it decides it needs to, are read from a text file called a Makefile with a very simple structure.  Lines like</p>
<p><code>alice: bob gerald</code></p>
<p>specify that a file named alice depends on files named bob and gerald. Dependency rules can also include shell commands to perform when building alice:</p>
<pre>
alice: bob gerald
        cat bob gerald > alice
</pre>
<p>Makefiles are an elegant way to describe the proces of building native programs, but on their own they&#8217;re insufficient and inefficient for larger projects.</p>
<h3>make hit-and-miss</h3>
<p>Make grew out of the Unix culture. Make itself is designed to run from a shell, which makes it very easy to automate; Make editing modes and execution plugins exist for every worthwhile Unix text editor and Make itself forms the backbone for a number of Unix IDEs. In turn, Make uses a list of shell commands to execute at each step, which makes it very easy to extend—in fact, Make has no way to compile or package code on its own, relying on a toolchain like GCC for the finer details.</p>
<p>The same culture also popularized the C language, which requires both compilation into intermediate object files and linking into the final program. Because compiling source code can take a while for large projects, Make has features to support incremental recompilation. When Make encounters a node whose file is newer than the files of all dependency nodes, it skips the build stage for that file on the assumption that it&#8217;s already up to date. This means that running the same Make command twice will usually do different, but equivalent, things: the first one will build the entire dependency graph from source, and the second one will notice that everything&#8217;s up to date and do nothing.</p>
<p>On the surface, this is a safe optimization: if your source files haven&#8217;t changed, and your compile process is deterministic, then you don&#8217;t need to rebuild the intermediate or final products. However, specificying the project&#8217;s dependency graph correctly is not as easy as it appears.</p>
<p>Consider the following C program, composed of two source files and a header:</p>
<h4>logging.h</h4>
<pre>
#ifndef LOGGING
#define LOGGING

void log_message (const char *message);

#endif
</pre>
<h4>logging.c</h4>
<pre>
#include <stdio.h>
#include "logging.h"

void log_message (const char *message) {
    printf ("Log message: %s\n", message);
}
</pre>
<h4>main.c</h4>
<pre>
#include "logging.h"

int main () {
    log_message ("Hello, world.");
    return 0;
}
</pre>
<p>The final product, an executable named <code>example-1</code>, has a dependency graph shaped like this:</p>
<div id="attachment_36" class="wp-caption aligncenter" style="width: 289px"><a href="http://codex.grimoire.ca/wp-content/uploads/2008/10/make-example-1-correct-graph.png"><img src="http://codex.grimoire.ca/wp-content/uploads/2008/10/make-example-1-correct-graph.png" alt="Both objects depend on the header file and one source file." title="The correct dependency graph" width="279" height="346" class="size-full wp-image-36" /></a><p class="wp-caption-text">Both objects depend on the header file and one source file.</p></div>
<p>Unfortuntely, Make&#8217;s code-agnostic nature makes is unable to spot the dependencies on <code>logging.h</code> without help, giving this graph:</p>
<div id="attachment_38" class="wp-caption aligncenter" style="width: 193px"><a href="http://codex.grimoire.ca/wp-content/uploads/2008/10/make-example-1-stock-rules-only.png"><img src="http://codex.grimoire.ca/wp-content/uploads/2008/10/make-example-1-stock-rules-only.png" alt="Make&#039;s stock rules are unaware of included files." title="The graph, missing the header file" width="183" height="346" class="size-full wp-image-38" /></a><p class="wp-caption-text">Make's stock rules are unaware of included files.</p></div>
<p>Adding a new feature to the &#8220;logging&#8221; library by modifying the source and header will recompile both logging.o and the final program, but not main.o. Depending on the kind of changes involved, this could be harmless, or it could lead to some fairly strange bugs—bugs that magically disappear if you build from a clean environment.</p>
<p>For a trivial project, like this one, it was easy enough to specify them manually in the Makefile I used to test this example:</p>
<pre>
example-1: main.o logging.o
	$(CC) $(LDFLAGS) $^ -o $@

main.o: main.c logging.h

logging.o: logging.c logging.h
</pre>
<p>In a real project, however, there can be tens or hundreds of header files, and manually maintaining the list of header files in two places (in the source itself, and in the Makefile) is tedious and error-prone. There is no good, general-case solution for this, but there are language-specific tools that can parse a source tree and spit out a list of include files in a format Make can understand. Using these tools is one more piece of complexity in the build and one more obstacle to maintenance, compounded by the Unix philosophy of gluing tools together.</p>
<p>GNU Make&#8217;s manual <a href="http://www.gnu.org/software/automake/manual/make/Automatic-Prerequisites.html">suggests</a> this snippet for dependency analysis of C and C++ projects:</p>
<pre>
%.d: %.c
        @set -e; rm -f $@; \
         $(CC) -M $(CPPFLAGS) $&lt; &gt; $@.$$$$; \
         sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' &lt; $@.$$$$ &gt; $@; \
         rm -f $@.$$$$

include *.d
</pre>
<p>&#8230;clear as mud.</p>
<p>Various tools have grown up around Make that automate this and other kinds of configuration, from various dependency scanning tools to the GNU Autotools suite, used by almost every recent Unix-and-C project. These tools generate Makefiles that are about as comprehensible as that last snippet and degrade both the portability and the simplicity of the build system.</p>
<p>Make&#8217;s own tools for streamlining builds aren&#8217;t much better: &#8220;pattern&#8221; rules, which are made out of a combination of a wildcard matching language and special variables in the Makefile, can bridge gaps in dependency trees and allow Make to infer intermediate steps from the sources available and the target to be built. Patterns can also standardize builds by packaging up common steps; the pattern rule Make provides for compiling C source files takes advantage of this:</p>
<pre>
%.o: %.c
        $(CC) -c $(CPPFLAGS) $(CFLAGS) $^ -o $@
</pre>
<p>In a large project that makes heavy use of patterns, though, it rapidly becomes impossible to determine which source files will be rebuilt until you actually go to run the build.</p>
<h3>make finished</h3>
<p>Designing your project to play to Make&#8217;s strengths can create simple, readable, fast builds. However, even with the voluminous documentation on how to use Make available on the web, it can be hard to keep your build within Make&#8217;s outdated build model in the face of complex projects. If you plan to use Make, find someone who&#8217;s already experienced with it before setting out; it&#8217;s not simple enough for an inexperienced team to use effectively, and by the time they can use it to its fullest, they&#8217;ll be experts and your project will be late.</p>
<p>I&#8217;ve started with Make because it was one of the first tools to formalize the idea of a build process. While it hasn&#8217;t aged particularly well, and its support for comfort features and chrome is weak compared to modern offerings, Make is still a competent tool and does well at three of the fundamentals of a build system: automatability, standardization, and extensibility.</p>
<p><small><em>Edited Nov. 18, 2008: corrected the name of the header in #include directives in the example. Thanks, <a href="http://plouj.com/">Plouj</a>!</em></small></p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2008/10/01/nobody-cares-about-your-makefile/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Merging Structural Changes</title>
		<link>http://codex.grimoire.ca/2008/09/28/merging-structural-changes/</link>
		<comments>http://codex.grimoire.ca/2008/09/28/merging-structural-changes/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 06:10:39 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

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

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

		<category><![CDATA[version control]]></category>

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=15</guid>
		<description><![CDATA[Recently, a project I&#8217;m working on set out to reinvent their build process, migrating from a mass of poorly-written Ant scripts to Maven and reorganizing their source tree in the process. The development process is based on having a branch per client, so there is a lot of ongoing development on the original layout for [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, a project I&#8217;m working on set out to reinvent their build process, migrating from a mass of poorly-written Ant scripts to Maven and reorganizing their source tree in the process. The development process is based on having a branch per client, so there is a lot of ongoing development on the original layout for clients that haven&#8217;t been migrated yet. We discovered that our version control tool, <a href="http://subversion.tigris.org/">Subversion</a>, is unable to merge the changes between client branches on the old structure and the trunk on the new structure automatically.</p>
<p>Curiousity piqued, I cooked up a script that reproduces the problem and performs the merge from various directions to examine the results. Subversion, sadly, performed dismally: none of the merge scenarios tested retained content changes when merging structural changes to the same files.<br />
<span id="more-15"></span></p>
<h3>The Preferred Outcome</h3>
<div id="attachment_16" class="wp-caption aligncenter" style="width: 310px"><a href="http://codex.grimoire.ca/wp-content/uploads/2008/09/ideal-merge-results.png"><img src="http://codex.grimoire.ca/wp-content/uploads/2008/09/ideal-merge-results-300x226.png" alt="Both changes survive the merge." title="Ideal Merge Results" width="300" height="226" class="size-medium wp-image-16" /></a><p class="wp-caption-text">Both changes survive the merge.</p></div>
<p>The diagram above shows a very simple source tree with one directory, <code>dir-a</code>, containing one file with two lines in it. On one branch, the file is modified to have a third line; on another branch, the directory is renamed to <code>dir-b</code>. Then, both branches are merged, and the resulting tree contains both sets of changes: the file has three lines, and the directory has a new name.</p>
<p>This is the preferred outcome, as no changes are lost or require manual merging.</p>
<h3>Subversion</h3>
<div id="attachment_17" class="wp-caption aligncenter" style="width: 310px"><a href="http://codex.grimoire.ca/wp-content/uploads/2008/09/subversion-merge-results.png"><img src="http://codex.grimoire.ca/wp-content/uploads/2008/09/subversion-merge-results-300x286.png" alt="Subversion loses the content change." title="Subversion Merge Results" width="300" height="286" class="size-medium wp-image-17" /></a><p class="wp-caption-text">Subversion loses the content change.</p></div>
<p>There are two merge scenarios in this diagram, with almost the same outcome. On the left, a working copy of the branch where the file&#8217;s content changed is checked out, then the changes from the branch where the structure changed are merged in. On the right, a working copy of the branch where the structure changed is checked out, then the changes from the branch where the content changed are merged in. In both cases, the result of the merge has the new directory name, and the original file contents. In one case, the merge triggers a rather opaque warning about a &#8220;missing file&#8221;; in the other, the merge silently ignores the content changes.</p>
<p>This is a consequence of the way Subversion implements renames and copies. When Subversion assembles a changeset for committing to the repository, it comes up with a list of primitive operations that reproduce the change. There is no primitive that says &#8220;this object was moved,&#8221; only primitives which say &#8220;this object was deleted&#8221; or &#8220;this object was added, as a copy of that object.&#8221; When you move a file in Subversion, those two operations are scheduled. Later, when Subversion goes to merge content changes to the original file, all it sees is that the file has been deleted; it&#8217;s completely unaware that there is a new name for the same file.</p>
<p>This would be fairly easy to remedy by adding a &#8220;this object was moved to that object&#8221; primitive to the changeset language, and <a href="http://subversion.tigris.org/issues/show_bug.cgi?id=898">a bug report for just such a feature</a> was filed in 2002. However, by that time Subversion&#8217;s repository and changeset formats had essentially frozen, as Subversion was approaching a 1.0 release and more important bugs <em>without</em> workarounds were a priority.</p>
<p>There is some work going on in Subversion 1.6 to handle tree conflicts (the kind of conflicts that come from this kind of structural change) more sensibly, which will cause the two merges above to generate a Conflict result, which is not as good as automatically merging it but far better than silently ignoring changes.</p>
<h3>Mercurial</h3>
<div id="attachment_18" class="wp-caption aligncenter" style="width: 310px"><a href="http://codex.grimoire.ca/wp-content/uploads/2008/09/mercurial-merge-results.png"><img src="http://codex.grimoire.ca/wp-content/uploads/2008/09/mercurial-merge-results-300x247.png" alt="Mercurial preserves the content change." title="Mercurial Merge Results" width="300" height="247" class="size-medium wp-image-18" /></a><p class="wp-caption-text">Mercurial preserves the content change.</p></div>
<p>Interestingly, there are tools which get this merge scenario right: the diagram above shows how <a href="http://www.selenic.com/mercurial/">Mercurial</a> handles the same two tests. Since its changeset language does include an &#8220;object moved&#8221; primitive, it&#8217;s able to take a content change for <code>dir-a/file</code> and apply it to <code>dir-b/file</code> if appropriate.</p>
<h3>Further Resources</h3>
<p>If you feel like reproducing this yourself, or want to adapt my test scripts to work with your favourite version control system, the scripts are <a href="http://alchemy.grimoire.ca/hg/tree-conflicts/">available</a> from Mercurial or as a <a href="http://alchemy.grimoire.ca/hg/tree-conflicts/archive/tip.zip">zip</a>. Patches and suggestions welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2008/09/28/merging-structural-changes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Nobody Cares About Your Build</title>
		<link>http://codex.grimoire.ca/2008/09/24/nobody-cares-about-your-build/</link>
		<comments>http://codex.grimoire.ca/2008/09/24/nobody-cares-about-your-build/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 00:50:35 +0000</pubDate>
		<dc:creator>Owen</dc:creator>
		
		<category><![CDATA[Manifestos and Rants]]></category>

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

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

		<guid isPermaLink="false">http://codex.grimoire.ca/?p=3</guid>
		<description><![CDATA[Every software system, from simple Python packages to huge enterprise-grade systems spanning massive clusters, has a build—a set of steps that must be followed to go from a source tree or a checked-out project to a ready-to-use build product. A build system&#8217;s job is to automate these steps.
Build systems are critical to software development.
They&#8217;re also [...]]]></description>
			<content:encoded><![CDATA[<p>Every software system, from simple Python packages to huge enterprise-grade systems spanning massive clusters, has a build—a set of steps that must be followed to go from a source tree or a checked-out project to a ready-to-use build product. A build system&#8217;s job is to automate these steps.</p>
<p>Build systems are critical to software development.</p>
<p>They&#8217;re also one of the most common avoidable engineering failures.<br />
<span id="more-3"></span><br />
A reliable, comfortable build system has measurable benefits for software development. Being able to build a testable, deployable system at any point during development lets the team test more frequently. Frequent testing isolates bugs and integration problems earlier, reducing their impact. Simple, working builds allow new team members to ramp up more quickly on a project: once they understand how one piece of the system is constructed, they can apply that knowledge to the entire system and move on to doing useful work. If releases, the points where code is made available outside the development team, are done using the same build system that developers use in daily life, there will be fewer surprises during releases as the “release” build process will be well-understood from development.</p>
<h3>Builds Have Needs, Too</h3>
<p>In 1947, Abraham Maslow described a <a href="http://en.wikipedia.org/wiki/Maslow's_hierarchy_of_needs">hierarchy of needs</a> for a person&#8217;s physical and mental well-being on the premise that all the items at the lowest level of the hierarchy must be met before a person will be able to focus usefully on higher-level needs. Maslow&#8217;s hierarchy begins with a set of needs that, without which, you do not have a person (for long)—physiological needs like &#8220;breathing,&#8221; &#8220;food,&#8221; and &#8220;water.&#8221; At the peak, there are extremely high-level needs that are about being a happy and enlightened person—&#8221;creativity,&#8221; &#8220;morality,&#8221; &#8220;curiosity,&#8221; and so on.</p>
<p><a href="http://codex.grimoire.ca/wp-content/uploads/2008/09/buildifesto-pyramid.png"><img src="http://codex.grimoire.ca/wp-content/uploads/2008/09/buildifesto-pyramid.png" alt="" title="The Pyramid" width="500" height="365" class="aligncenter size-full wp-image-4" /></a>Builds, and software engineering as a whole, can be described the same way: at the top of the hierarchy is a working system that solves a problem, and at the bottom are the things you need to have software at all. If you don&#8217;t meet needs at a given level, you will eventually be forced to stop what you&#8217;re doing at a higher level and face them.</p>
<p>Before a build is a build, there are five key needs to meet:</p>
<ul>
<li><strong>It must be repeatable</strong>. Every time you start your build on a given source tree, it must build exactly the same products without any further intervention. Without this, you can&#8217;t reliably decide whether a given build is &#8220;good,&#8221; and can easily wind up with a build that needs to be run several times, or a build that relies on running several commands in the right order, to produce a build.
</li>
<li><strong>It must be automatable</strong>. Build systems are used by developers sitting at their desks, but they’re also used by automatic build systems for nightly builds and continuous integration, and they can be made into parts of other builds. A build system that can only be run by having someone sit down at a keyboard and mouse and kicking it off can’t be integrated into anything else.
</li>
<li><strong>It must be standardized</strong>. If you have multiple projects that build similar things—for example, several Java libraries—all of them must be built the same way. Without this, it&#8217;s difficult for a developer to apply knowledge from one project to another, and it&#8217;s difficult to debug problems with individual builds.
</li>
<li><strong>It must be extensible</strong>. Not all builds are created equal. Where one build compiles a set of source files, another needs five libraries and a WSDL descriptor before it can compile anything. There must be affordances within the standard build that allow developers to describe the ways their build is different. Without this, you have to write what amounts to a second build tool to ensure that all the &#8220;extra&#8221; steps for certain projects happen.
</li>
<li><strong>Someone must understand it</strong>. A build nobody understands is a time bomb: when it finally breaks (and it will), your project will be crippled until someone fixes it or, more likely, hacks around it.
</li>
</ul>
<p>If you have these five things, you have a working build. The next step is to make it comfortable. Comfortable builds can be used daily for development work, demonstrations, and tests as well as during releases; builds that are used constantly don&#8217;t get a chance to &#8220;rust&#8221; as developers ignore them until a release or a demo and don’t hide surprises for launch day.</p>
<ul>
<li><strong>It must be simple</strong>. When a complicated build breaks, you need someone who understands it to fix it for you. Simple builds mean more people can understand it and fewer things can break.</li>
<li><strong>It must be fast</strong>. A slow build will be hacked around or ignored entirely. Ideally, someone creating a local build for a small change should have a build ready in seconds.</li>
<li><strong>It must be part of the product</strong>. The team responsible for developing a project must be in control of and responsible for its build. Changes to it and bugs against it must be treated as changes to the product or bugs in the product.</li>
<li><strong>It must run unit tests</strong>. Unit tests, which are completely isolated tests written by and for developers, can catch a large number of bugs, but they&#8217;re only useful if they get run. The build must run the unit test suite for the product it&#8217;s building every build.</li>
<li><strong>It must build the same thing in any environment</strong>. A build is no good if developers can only get a working build from a specific machine, or where a build from one developer&#8217;s machine is useless anywhere else. If the build is uniform on any environment, any developer can cook up a build for a test or demo at any time.
</li>
</ul>
<p>Finally, there are &#8220;chrome&#8221; features that take a build from effective to excellent. These vary widely from project to project and from organization to organization.  Here are some common chrome needs:</p>
<ul>
<li><strong>It should integrate with your IDEs</strong>. This goes both directions: it should be possible to run the build without leaving your IDE or editor suite, and it should be possible to translate the build system into IDE-specific configurations to reduce duplication between IDE settings and the build configuration.</li>
<li><strong>It should generate metrics</strong>. If you gather metrics for test coverage, common bugs, complexity analysis, or generate reports or documentation, the build system should be responsible for it. This keeps all the common administrative actions for the project in the same place as the rest of the configuration, and provides the same consistency that the system gives the rest of the build.</li>
<li><strong>It should support multiple processors</strong>. For medium-sized builds that aren’t yet large enough to merit breaking down into libraries, being able to perform independent build steps in parallel can be a major time-saver. This can extend to distributed build systems, where idle CPU time can be donated to other peoples’ builds.</li>
<li><strong>It should run integration and acceptance tests</strong>. Taking manual work from the quality control phase of a project and running it automatically during builds amplifies the benefits of early testing and, if your acceptance tests are good, when your project is done.</li>
<li><strong>It should not need repeating</strong>. Once you declare a particular set of build products &#8220;done&#8221;, you should be able to use those products as-is any time you need them. Without this, you will eventually find yourself rebuilding the same code from the same release over and over again.</li>
</ul>
<h3>What Doesn’t Work</h3>
<p>Builds, like any other part of software development, have antipatterns—recurring techniques for solving a problem that introduce more problems.</p>
<ul>
<li><strong>One Source Tree, Many Products</strong>. Many small software projects that survive to grow into large, monolithic projects are eventually broken up into components. It&#8217;s easy to do this by taking the existing source tree and building parts of it, and it&#8217;s also wrong. Builds that slice up a single source tree require too much discipline to maintain and too much mental effort to understand. Break your build into separate projects that are built separately, and have each build produce one product.
</li>
<li><strong>The Build And Deploy System</strong>. Applications that have a server component often choose to automate deployment and setup using the same build system that builds the project. Too often, the extra build steps that set up a working system from the built project are tacked onto the end of an existing build. This breaks standardization, making that build harder to understand, and means that that one build is producing more than one thing—it&#8217;s producing the actual project, and a working system around the project.
</li>
<li><strong>The Build Button</strong>. IDEs are really good at editing code. Most of them will produce a build for you, too. Don&#8217;t rely on IDE builds for your build system, and don&#8217;t let the IDE reconfigure the build process. Most IDEs don&#8217;t differentiate between settings that apply to the project and settings that apply to the local environment, leading to builds that rely on libraries or other projects being in specific places and on specific IDE settings that are often buried in complex settings dialogs.
</li>
<li><strong>Manual Steps</strong>. Anything that gets done by hand will eventually be done wrong. Automate every step.
</li>
</ul>
<h3>What Does Work</h3>
<p>Similarly, there are patterns—solutions that recur naturally and can be applied to many problems.</p>
<ul>
<li><strong>Do One Thing Well</strong>. The UNIX philosophy of small, cohesive tools works for build systems, too: if you need to build a package, and then install it on a server, write three builds: one that builds the package, one that takes a package and installs it, and a third that runs the first two builds in order. The individual builds will be small enough to easily understand and easy to standardize, and the package ends up installed on the server when the main build finishes.
</li>
<li><strong>Dependency Repositories</strong>. After a build is done, make the built product available to other builds and to the user for reuse rather than rebuilding it every time you need it. Similarly, libraries and other inward dependencies for a build can be shared between builds, reducing duplication between projects.
</li>
<li><strong>Convention Over Extension</strong>. While it&#8217;s great that your build system is extensible, think hard about whether you really need to extend your build.  Each extension makes that project’s build that much harder to understand and adds one more point of failure.
</li>
</ul>
<h3>Pick A Tool, Any Tool</h3>
<p>Nothing here is new. The value of build systems has been <a href="http://www.joelonsoftware.com/articles/fog0000000043.html">discussed</a> <a href="http://www.gamesfromwithin.com/articles/0506/000092.html">in</a> <a href="http://c2.com/cgi/wiki?BuildSystem">great</a> <a href="http://www.codinghorror.com/blog/archives/000988.html">detail</a> <a href="http://www.cc2e.com/">elsewhere</a>. Much of the accumulated build wisdom of the software industry has already been incorporated to one degree or another into build tools. What matters is that you pick one, then use it with the discipline needed to get repeatable results without thinking.</p>
]]></content:encoded>
			<wfw:commentRss>http://codex.grimoire.ca/2008/09/24/nobody-cares-about-your-build/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
