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

<channel>
	<title>cumulus</title>
	<atom:link href="http://cumulus.ixcode.org/feed/" rel="self" type="application/rss+xml" />
	<link>http://cumulus.ixcode.org</link>
	<description>an experiment in OO design</description>
	<lastBuildDate>Sat, 04 Apr 2009 00:07:09 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.5</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Rule #6 (OK, most of 7, 8 and 9 too): Keep All Entities Small.</title>
		<link>http://cumulus.ixcode.org/2009/04/03/rule-6-ok-most-of-7-8-and-9-too-keep-all-entities-small/</link>
		<comments>http://cumulus.ixcode.org/2009/04/03/rule-6-ok-most-of-7-8-and-9-too-keep-all-entities-small/#comments</comments>
		<pubDate>Sat, 04 Apr 2009 00:07:09 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=86</guid>
		<description><![CDATA[This was brutal.  At the beginning, I had two classes that were more than 100 lines long (the target: 50).  Not only that, I hadn&#8217;t been using packaging properly, so I had one very large package and a few tiny ones.
I find it useful to think about this rule and the following three [...]]]></description>
			<content:encoded><![CDATA[<p>This was brutal.  At the beginning, I had two classes that were more than 100 lines long (the target: 50).  Not only that, I hadn&#8217;t been using packaging properly, so I had one very large package and a few tiny ones.</p>
<p>I find it useful to think about this rule and the following three rules as somewhat of a unit, since the refactorings needed to implement them cut across them, and are also part of a feedback loop.  Here are the rules:</p>
<ul>
<li>Keep All Entitites Small.
</li>
<li>Maximum 2 instance variables per class.
</li>
<li>Use first-class collections.
</li>
<li>Don&#8217;t use any getters/setters/properties.
</li>
</ul>
<p>Here are the refactorings:</p>
<ul>
<li>Remove Fields.
</li>
<li>Encapsulate Collections.
</li>
</ul>
<ul>
<li>Split Classes.
</li>
<li>Minimize Visibility.
</li>
</ul>
<p>Removing fields and making first class collections are all about encapsulation.  One way to go about this is to try to make all fields private (i.e. no getters/setters), then move functionality and fields around, and relax visibility of the fields, until you have a working system again.  This will automagically make separate classes.  But, they might be too big.</p>
<p>Breaking up classes makes packages bigger.  So, you need to cluster the new quiver O classes into packages.  This is an optimization problem:  You need to minimize visibility (of the classes themselves, as well as the methods) and also minimize the number of packages, so that only those classes which need to be in the same package with their friends, are.  During this process, you might want to increase visibility and reintroduce getters/setters so that you can make your packages &#8220;work&#8221;.  Then it&#8217;s back to the previous paragraph.</p>
<h3>What I did</h3>
<p>First, I tried to repackage.</p>
<p>Then, I did an exercise to minimize instance variables.</p>
<p>Then, I worked on refactoring the domain model so that collections had more functionality (First Class Collections), and the object model was more granular (Splitting Classes). </p>
<p>Then, I worked on repackaging again, and finally got rid of the getter/setters (Rule #9).  This was trivial, especially since I cheated &#8211; I couldn&#8217;t get rid of the intValue() method on WrappedInteger!  In fact, the method is central to the entire application!  This doesn&#8217;t surprise me &#8211; it&#8217;s the type of cross-cutting getter that wrapping primitives makes necessary &#8230;</p>
<p>To split classes, I started by looking for &#8220;responsibility&#8221; and making each class do just one thing.  For example, my Solver used a chart to memoize the sub-solutions as it recursively solved the large problem.  I removed the chart and put it in its own class, then gave the class more functionality so that the solver had to have the bare minimum number of lines to do its memoization.</p>
<p>My end state has no getters, EXCEPT the &#8220;intValue()&#8221; on the WrappedInteger class.  It does, however, have members of a package which use the package-local visibility of another class&#8217;s field to peek at it.  In fact, the collections package is the largest one in my solution (!), with nine (yes, 9) classes.  Not all are collections, but the domain model really revolves around collections. and so its name is a historical artifact.  In fact, hell, I should just rename the package &#8220;model&#8221; or something.  In this way it&#8217;d exclude the &#8220;primitives&#8221; package &#8211; but hmm, maybe I&#8217;ll make that a sub-package of domain.  Hold on &#8230;. OK, done.  That took all of 3 minutes.</p>
<h3>About those Classy Containers</h3>
<p>In the process of making first-class containers, I found it useful to use two levels of implementation, and sometimes three:</p>
<ol>
<li>Make a minimal collection which just uses the Java collection framework to do what it needs (e.g. is it a list, or a map? It is sorted?)  This is just instantiating a generic collection and putting non-domain-specific functionality on it.
</li>
<li>Wrap the base collection with additional concerns.  Usually, you want to do this by containing the base class rather than extending it.  By doing this you hide all of the stuff you don&#8217;t really care about for your domain collection.
</li>
<li>Sometimes the class becomes large enough and with enough extra, domain-specific functionality, that you can extend the secondary class, and make the top-level class the only public one.
</li>
</ol>
<h4>A First Class Collection example</h4>
<p> The domain model revolving around sets of coins goes like this (TODO: Produce a class diagram):</p>
<p>A CoinSet has a bunch of CoinRolls. A CoinRoll is a roll of a single denomination (like that roll of quarters you have on your beside table at home), whereas a CoinSet has more than one denomination.  The implementation of CoinRoll has 3 levels:</p>
<ul>
<li><strong>CoinRollSet</strong> &#8211; This is just an extension of a Java collection template instantiation.
</li>
<li><strong>CoinRollCollectionBase</strong>  &#8211; This contains a CoinRollSet, implements Iterable<CoinSet>, and adds the stuff I&#8217;ll need for a proper object: toString, equals, hashCode, all of that.  It&#8217;s still very much a low-level class.
</li>
<li><strong>CoinRollCollection</strong> &#8211; This is the only public class in this 3-level &#8220;hierarchy&#8221;, and has a couple domain-specific methods (containsDenomination and totalCoinCount).  It also contains deepCopy, which while not domain-specific, is a good place for it since it&#8217;s like a constructor.
</li>
</ul>
<h4>Another First Class Collection (but, not quite as classy)</h4>
<p>In the case of the memoization chart mentioned above (called SolutionChart, strangely enough), the basic class can store a set of solutions for each Money amount being solved for.  I used a HashMap as the basic storage, and contained it in a class with the functionality to create a solution from a CoinSet; and to decide whether the CoinSet was empty.  Since I needed so little of the HashMap functionality, I didn&#8217;t even bother to extend it into its own class.</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/04/03/rule-6-ok-most-of-7-8-and-9-too-keep-all-entities-small/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>friendly-coins Rule #5: No Abbrvs</title>
		<link>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-5-no-abbrvs/</link>
		<comments>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-5-no-abbrvs/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 22:07:03 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=83</guid>
		<description><![CDATA[For this refactor I renamed a few classes and a relative lot of variables and fields.
It felt good.  I kind of felt like I had just taken a nice hot shower after swimming in the Charles.
Not only did I get rid of abbreviations, I also renamed after thinking a bit about what a meaningful [...]]]></description>
			<content:encoded><![CDATA[<p>For this refactor I renamed a few classes and a relative lot of variables and fields.</p>
<p>It felt good.  I kind of felt like I had just taken a nice hot shower after swimming in the Charles.</p>
<p>Not only did I get rid of abbreviations, I also renamed after thinking a bit about what a meaningful name would be, and I also tried to standardize naming.</p>
<p>So, whereas MinNumCoinsSolver became MinimumCoinCountSolver (abbrvs),<br />
many instances of &#8220;greedySolution&#8221; became &#8220;highestFirstSolution&#8221; (because the class that produced them had always been named HighestFirstSolver).</p>
<p>I also split the &#8220;Helpers&#8221; class into several different types of helpers: Again, this was not merely watching out for abbreviations, but also paying attention to reasonable naming and even packaging (a prelude to Rule #6)</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-5-no-abbrvs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>friendly-coins Rule #4: One Dot Per Line</title>
		<link>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-4-one-dot-per-line/</link>
		<comments>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-4-one-dot-per-line/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 21:57:08 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=80</guid>
		<description><![CDATA[When I embarked on this refactor, I hadn&#8217;t yet got to the point of minimizing the calls to the horrible WrappedInteger.intValue() method.  What ended up happening is having a load of extra lines to assign the .intValue() to a temporary variable, subsequently used on the next line.  Yuck.  Not to worry, that [...]]]></description>
			<content:encoded><![CDATA[<p>When I embarked on this refactor, I hadn&#8217;t yet got to the point of minimizing the calls to the horrible WrappedInteger.intValue() method.  What ended up happening is having a load of extra lines to assign the .intValue() to a temporary variable, subsequently used on the next line.  Yuck.  Not to worry, that got taken care of when I improved the WrappedInteger() later.</p>
<p>There were also some egregious offenders which went beyond the simple intValue() gaff.  A nice examples below:</p>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
    while( index >= 0 &#038;&#038; ordered.get(index).intValue() >
        total.intValue() - ret.sum().intValue() ) {
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
    while( index >= 0 &#038;&#038;
        greaterThan( ordered.get( index ), maxAddable) ) {
</code></pre>
</div>
<p>Aside from that there were some required uses of temporary variables (below).  Precious few &#8220;real&#8221; encapsulation examples, so I seem to not have been a huge offender on Demeter&#8217;s law.  Not this time around at least &#8230;</p>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
return this.getClass().getSimpleName() + "<" +
     Helpers.stringJoin( getCoinSets(), Joiner.COMMA ) + ">";
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
final String className = klass.getSimpleName();
return className + "<" +
     Helpers.stringJoin( getCoinSets(), COMMA ) + ">";
</code></pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-4-one-dot-per-line/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>friendly-coins Rule #3: Wrap all primitives and Strings.</title>
		<link>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-3-wrap-all-primitives-and-strings/</link>
		<comments>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-3-wrap-all-primitives-and-strings/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 17:49:20 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=72</guid>
		<description><![CDATA[This was rather invasive.  The motive behind it (this is from Jeff&#8217;s article) is to add semantics to the use of atomic values; and also (a side benefit), give you a chance to stick behavior on those &#8220;small objects&#8221;.
In the Friendly Coins problem, it&#8217;s fairly clear there are at least three distinct flavors of [...]]]></description>
			<content:encoded><![CDATA[<p>This was rather invasive.  The motive behind it (this is from Jeff&#8217;s article) is to add semantics to the use of atomic values; and also (a side benefit), give you a chance to stick behavior on those &#8220;small objects&#8221;.</p>
<p>In the Friendly Coins problem, it&#8217;s fairly clear there are at least three distinct flavors of numbers (all integers, by the way):</p>
<ul>
<li>A coin has a <strong>Denomination</strong> (e.g., a nickel has a denomination of 5 cents).
</li>
<li>When you are making change, you will then have a certain number of each Denomination.  I decided to call this flavor of number a <strong>Cardinality</strong>.
</li>
<li>Finally, there is the number which arises by combining a bunch of Denominations into a handful of change (which we hope is Friendly, of course).  I decided to call this <strong>Money</strong>, because that&#8217;s what it is, after all.
</li>
</ul>
<p>Since we are dealing with small objects, I used the Instance Singleton pattern to make sure each Denomination and Cardinality only ever had one instance in memory (I decided NOT to do this for Money, since Money is only ever persisted in memory about once per value in the solution, and Money, unlike the others, is mutable &#8211; and I didn&#8217;t even want to think about implementing copy-on-write). </p>
<p>Just a small taste:</p>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public static CoinSet createCoinSet(Integer... denominations) {
    return new CoinSet( denominations );
}
...
int sum = 0;
...
private void incrementDenomination( int denomination ) {
    int card = getCardinality( denomination );
    denominations.put( denomination, 1 + card );
    sum += denomination;
}
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public static CoinSet createCoinSet(Denomination... denominations) {
    return new CoinSet( denominations ) ;
}
...
private Money sum = new Money();
...
private void incrementDenomination( Denomination denomination ) {
    Cardinality card = getCardinality( denomination );
    setCardinality( denomination, Cardinality.getInstance( card.intValue() + 1 ));
    sum.addCoin( denomination );
}
</code></pre>
</div>
<p>One of the choices I made when encapsulating the ints: since Integer cannot be extended, I could either add methods to my own spanky new WrappedInteger base class, or provide static helper methods.  If one writes helper methods, one immediately gets into the game of exposing the internal value (oops, there&#8217;s a line of code or a dot or whatever); manipulating it (a call to a helper); then possibly re-encapsulating it.  So, I gave WrappedInteger the needed comparison and plus/minus methods. </p>
<p>So, I recompile, and LOOK: I get warnings to the effect that I am comparing nonconvertible classes when I do this: </p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
if( total.equals( denomination ) )
</code></pre>
</div>
<p>&#8230; Happily, this is exactly what I want to do &#8211; if the total change to give is equal to the denomination &#8211; then it&#8217;s a single coin.  But in general, comparing denominations and Money would seem to be  a no-no (since Denominations aren&#8217;t really money; they&#8217;re just the abstract concept of the possibility of representing a Money.  You need a Denomination and a Cardinality to make Money).  So to avoid the warning, I do this:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
 if( new WrappedInteger( total ).equals( denomination ) )
</code></pre>
</div>
<p>In fact, this is exactly what I want &#8211; normally, comparing apples to oranges is not good.  In this case, all I needed to know was whether the apple weighed exactly the same.  Or, was the same color.  Or, something.  You know what I mean.  </p>
<p>In my case I&#8217;m not sure I&#8217;ve done things in a complete optimal way &#8211; I got rid of the messiness of helper methods, but have some warnings in the implementations, <em>and</em> try as I might, I simply cannot get my WrappedInteger implementation to not exceed the 50-line limit (!)  </p>
<p>I&#8217;m sitting here wondering: If Java had automatic casting (as does, for example, Scala), or allowed me to extend Integer, then instead of implementing my own arithmetic and comparison methods, I&#8217;d just use the out-of-the-box stuff, and everyone would be happy.  Boo Java.  Or, boo on me, if there&#8217;s some simple thing I should have done but have missed.  On the other hand, the exercise of designing my own general numeric classes and specializations was valuable in its own right &#8230;</p>
<h3>Less Mundane stuff &#8230;</h3>
<p>In addition to the numeric types, I played with the StringJoin helper method, introducing Joiners and Joinees.<br />
</code></pre>
</div>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public static final String EMPTY_STRING = "";
...
public static String stringJoin( Collection<?> objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    String useJoiner = EMPTY_STRING;
    for( Object o : objects ) {
        stringJoinAppend( o, useJoiner, builder );
        useJoiner = joiner;
    }
    return builder.toString();
}
private static void stringJoinAppend( Object o, String joiner,
        StringBuilder builder ) {
    builder.append( joiner );
    builder.append( (null == o) ? "null" : o.toString() );
}
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public static final Joiner EMPTY_STRING = new Joiner("");
...
public static String stringJoin( Collection<?> objects, Joiner joiner ) {
    StringBuilder builder = new StringBuilder();
    Joiner useJoiner = EMPTY_STRING;
    for( Object o : objects ) {
        stringJoinAppend( new Joinee(o), useJoiner, builder );
        useJoiner = joiner;
    }
    return builder.toString();
}
private static void stringJoinAppend( Joinee o, Joiner joiner,
        StringBuilder builder ) {
    builder.append( joiner );
    builder.append( o.toString() );
}
</code></pre>
</div>
<p>Aside from giving me a place to put the constant Joiner.COMMA (commonly used, of course), and the nicety of having the translation of the null value to the string "null" be in the Joinee class, I question the use/smell of this particular change, because in the end, the implementation is twice the length of its original (I didn't show you the Joiner and Joinee classes - they're rather mundane).  Maybe there would be future methods that also use Joiner and Joinee, making it all worthwhile.  On the other hand, its usage (as opposed to its implementation) is virtually identical to before the change; the only thing you have to do is send the stringJoin method a Joiner rather than a plain String (the Collection sent to it is automatically converted itemwise into Joinees).</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-3-wrap-all-primitives-and-strings/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>friendly-coins Rule #2: Don&#8217;t use the else keyword.</title>
		<link>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-2-dont-use-the-else-keyword/</link>
		<comments>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-2-dont-use-the-else-keyword/#comments</comments>
		<pubDate>Fri, 03 Apr 2009 16:59:55 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=64</guid>
		<description><![CDATA[For some reason I expected that I would have a bunch of else&#8217;s.  I didn&#8217;t.  There were a grand total of four.  Not much to say on this then.  For the most part, it&#8217;s what you&#8217;d expect (but I&#8217;m saving the best for last, hang in there!):
BEFORE:


public int getCardinality( int denomination [...]]]></description>
			<content:encoded><![CDATA[<p>For some reason I expected that I would have a bunch of else&#8217;s.  I didn&#8217;t.  There were a grand total of four.  Not much to say on this then.  For the most part, it&#8217;s what you&#8217;d expect (but I&#8217;m saving the best for last, hang in there!):</p>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public int getCardinality( int denomination ) {
    if( containsDenomination( denomination ) ) {
        return denominations.get( denomination );
    } else {
        return 0;
    }
}
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public int getCardinality( int denomination ) {
    if( containsDenomination( denomination ) ) {
        return denominations.get( denomination );
    }
    return 0;
}
</code></pre>
</div>
<p>This of course violates the prescription &#8220;Only have one exit point for a method&#8221; &#8211; and also increases the cyclomatic complexity.  But, these are both Allowed for this exercise.  Besides, I must say I&#8217;d choose the AFTER aver the BEFORE any day.</p>
<p>It&#8217;s not always that simple:</p>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
private void accumulateTotal(CoinSet coinSet) {
    if( 0 == total ) {
        total = coinSet.sum();
    } else if( coinSet.sum() != total ) {
        throw new IllegalStateException( "All coinSets must have the same sum" );
    }
}
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
private void accumulateTotal(CoinSet coinSet) {
    if( 0 == total ) {
        total = coinSet.sum();
        return;
    }
    if( coinSet.sum() != total ) {
        throw new IllegalStateException( "All coinSets must have the same sum" );
    }
}
</code></pre>
</div>
<p>I like the BEFORE in this case.  Assuming that is that I like the throwing of the exception &#8211; which, no, I don&#8217;t.  Never mind, this all gets refactored later on anyhow.</p>
<p><strong>Much more gratifying</strong> than either of the above is the chance to get rid of plain bad smelling code, by reducing the number of variables, curlies, and dropping the else:</p>
<p>BEFORE:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public static String stringJoin( Collection<?> objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for( Object o : objects ) {
        first = stringJoinAppend( o, joiner, builder, first );
    }
    return builder.toString();
}	

private static boolean stringJoinAppend( Object o, String joiner,
        StringBuilder builder, boolean first ) {
    if( ! first ) {
        builder.append( joiner );
    } else {
        first = false;
    }
    builder.append( (null == o) ? "null" : o.toString() );
    return first;
}
</code></pre>
</div>
<p>AFTER:</p>
<div style="background: #ddd; border: 1px; padding: 20px; clear: both">
<pre><code>
public static String stringJoin( Collection<?> objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    String useJoiner = "";
    for( Object o : objects ) {
        stringJoinAppend( o, useJoiner, builder );
        useJoiner = joiner;
    }
    return builder.toString();
}

private static void stringJoinAppend( Object o, String joiner,
        StringBuilder builder ) {
    builder.append( joiner );
    builder.append( (null == o) ? "null" : o.toString() );
}
</code></pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/04/03/friendly-coins-rule-2-dont-use-the-else-keyword/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>friendly-coins, Stage 1: Only one level of indentation per method</title>
		<link>http://cumulus.ixcode.org/2009/03/23/friendly-coins-stage-1-only-one-level-of-indentation-per-method/</link>
		<comments>http://cumulus.ixcode.org/2009/03/23/friendly-coins-stage-1-only-one-level-of-indentation-per-method/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 16:51:04 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[friendly-coins]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=49</guid>
		<description><![CDATA[For the friendly-coins project, my strategy is to start from a completed project, and apply refactorings to arrive at a codebase obeying the Nine Rules.
I think this will be interesting for at least a couple reasons:

It&#8217;ll give me a chance to see which of the Nine I tend to diverge from the most.
I&#8217;ll be able [...]]]></description>
			<content:encoded><![CDATA[<p>For the friendly-coins project, my strategy is to start from a completed project, and apply refactorings to arrive at a codebase obeying the Nine Rules.</p>
<p>I think this will be interesting for at least a couple reasons:</p>
<ul>
<li>It&#8217;ll give me a chance to see which of the Nine I tend to diverge from the most.</li>
<li>I&#8217;ll be able to do a before/after measurement on a few code metrics (for example, complexity and cohesion).</li>
</ul>
<p>The first refactor I applied was &#8220;Use only one level of indentation per method&#8221;.</p>
<h3>Micro-state sharing</h3>
<p>The bulk of the changes involved moving loops into their own methods.</p>
<p>I noticed a two variants of a micro-pattern.  First, let&#8217;s look at a stringJoin (yes, this is available elsewhere &#8212; but I decided not to use any non-core libraries, and even to not use core implementations if writing the code might exercise some of the Nine Rules).</p>
<p>BEFORE:</p>
<pre><code>
public static String stringJoin( Collection objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for( Object o : objects ) {
        if( ! first ) {
            builder.append( joiner );
        } else {
            first = false;
        }
        builder.append( (null == o) ? "null" : o.toString() );
    }
    return builder.toString();
}
</code></pre>
<p>AFTER:</p>
<pre><code>
public static String stringJoin( Collection objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    String useJoiner = "";
    for( Object o : objects ) {
        first = stringJoinAppend( o, useJoiner, builder );
        useJoiner = joiner;
    }
    return builder.toString();
}

private static boolean stringJoinAppend( Object o, String joiner, StringBuilder builder ) {
    builder.append( joiner );
    builder.append( (null == o) ? "null" : o.toString() );
}
</code></pre>
<p>Now, let&#8217;s look at a method which find a minimal value (yes, yes, here I am reimplementing the wheel &#8211; in the interest of calisthenics).</p>
<p>BEFORE:</p>
<pre><code>
private CoinSet findMin(Collection coinSets) {
     CoinSet theLeast = null;
     for( CoinSet coinSet : coinSets ) {
         if( null == theLeast || coinSet.getNumCoins() &lt; theLeast.getNumCoins() ) {
             theLeast = coinSet;
         }
     }
     return theLeast;
 }
</code></pre>
<p>AFTER:</p>
<pre><code>
private CoinSet findMin(Collection coinSets) {
     CoinSet theLeast = null;
     for( CoinSet coinSet : coinSets ) {
         theLeast = isItLess( theLeast, coinSet );
     }
     return theLeast;
 }

 private CoinSet isItLess(CoinSet theLeast, CoinSet coinSet) {
     if( null == theLeast || coinSet.getNumCoins() &lt; theLeast.getNumCoins() ) {
         theLeast = coinSet;
     }
     return theLeast;
 }
</code></pre>
<p>I am claiming this is a &#8220;micropattern&#8221; characterized by the fact that there is state associated with the loop, and the state needs to be managed by coordination between the caller and callee methods.  In the case of stringJoin, the state is whether or not to append the spearator to the string.  In the case of findMin (which actually has a more descriptive name in the real source), it&#8217;s what the minimal value found so far is.</p>
<p>How the state is managed between caller and -ee differs in the two examples.  In the stringJoin case, the state is independent of the called method (i.e., the caller maintains state).  In the findMin case, the called method is responsible for maintaining the correct state.  It would be possible to re-implement either method so that the responsibility is flipped.  It&#8217;s just that the way I implemented both of them smelled right to me on the day I did it.  It is worth noting that in the stringJoin, I have a redundant assignment (the assignment need only be done on the first pass through the loop).  However, I liked getting rid of the &#8220;if&#8221; test that would be necessary.  On the other hand, finding the minimal value does need a conditional, so putting the &#8220;if&#8221; in the callee works nicely.</p>
<h3>Try / Catch &#8211; Problematic</h3>
<p>Tricky to eliminate extra indentation were the try/catches &#8211; in this case, I took the requirement to be that there be 0 levels if indent inside the try/catch.  These are almost like a loop-removal, but seem to me to be more &#8220;woven&#8221; into the rest of the method (because of dependencies on variable).  This particular refactor smelled a little bad to me.  I&#8217;d even say that try/catches might by their very nature introduce extra complexity that requires extra effort in implementation.</p>
<h3>Strategy Pattern / Anonymous Methods / Yield / Micro-IOP</h3>
<p>Also interesting, was one instance of a &#8220;collect&#8221; pattern (as in, the Ruby language &#8220;collect&#8221; method, which in other languages might be called &#8220;map&#8221;):</p>
<p>BEFORE:</p>
<pre><code>
@Override public String toString() {
      String ret = this.getClass().getSimpleName() + "&lt;";
      boolean first = true;
      for( int k : denominations.keySet() ) {
          if( ! first ) {
              ret += ",";
          } else {
              first = false;
          }
          ret += k;
          ret += "'s:";
          ret += denominations.get( k );
      }
      return ret + "&gt;";
      items.add( item );
  }
</code></pre>
<p>I tried to get tricky and introduce a first-class &#8220;foreach&#8221; in order to use the already-refactored stringJoin.  The idea is that the difference is what gets executed INSIDE the foreach &#8211; so, since Java in its Old Skool way doesn&#8217;t yet have real anonymous functions, I tried to make one.</p>
<p>AFTER:</p>
<pre><code>
public String toString() {
      final Collection<Object> items = new ArrayList<Object>();
      new Foreach( denominations.keySet() ) {
          public @Override void each( Object o ) {
              denominationToString(o, items);
          }
      }.apply();
      return this.getClass().getSimpleName() + "<" + Helpers.stringJoin( items, "," ) + ">";
  }</code></pre>
<p>This looks bad.  The boilerplate is ugly.  Actually what I ended up liking better was this:</p>
<pre><code>
public String toString() {
      final Collection<Object> items = new ArrayList<Object>();
      for( int item : denominations.keySet() ) {
          items.add( denominationToString( o, items ) );
      }
      return this.getClass().getSimpleName() + "<" + Helpers.stringJoin( items, "," ) + ">";
  }
</code></pre>
<p>But on further reflection on the pursuit of first-class functions, maybe what I *really* wanted might have been this:</p>
<pre><code>
public String toString() {
     final Collection<Object> items =
         new Collect( denominations.keySet() ) {
             public @Override void each( Object o ) {
                 denominationToString(o, items);
             }
         }.apply();
     return this.getClass().getSimpleName() + "<" + Helpers.stringJoin( items, "," ) + ">";
 }
</code></pre>
<p>No matter what, the boilerplate kills the elegance.  If there were more going on besides the boilerplate, I&#8217;d like this pattern.  What I&#8217;m really trying to do is force Java to allow us to do this:</p>
<pre><code>
new Collect( denominations.keySet() ) {
    public @Override void each( Object o ) {
    ...
}.apply() ...
</code></pre>
<p>by just typing this:</p>
<pre><code>
collect { }
</code></pre>
<p>You see where I&#8217;m coming from.  I just want something that Java isn&#8217;t prepared to let me have.  Not today, anyhow.</p>
<h3>Final Java Bash</h3>
<p>A final note on this exercise:  In two of the cases where a loop was moved out of a more complex method, some sort of state was identified that needed to be shared.  This suggests treating the method as a class in its own right.  But, Java isn&#8217;t geared up to allow this to be done elegantly, especially in the case that the state, or strategy, is trivial.  In the &#8220;collect&#8221; case, what we wanted to do is supply (&#8221;inject&#8221;) a behavior into an existing algorithm.  Again, foiled by the language itself.  Finally, in the try/catch case, we&#8217;re faced with something that would better be solved using different language feature (assuming that our goal is to make the language support our best coding practices in the easiest way possible).  Maybe a type of method which can be then decorated using AOP to insert the try/catch.</p>
<p>Nevertheless, in spite of the dearth of language features, We Can Do it.  It just takes the courage to write minimal boilerplate and claim that it&#8217;s the Right Thing to Do.  Besides, exercise is good for you.</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/03/23/friendly-coins-stage-1-only-one-level-of-indentation-per-method/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>New sub-project in the SVN repo: friendly-coins</title>
		<link>http://cumulus.ixcode.org/2009/03/23/new-sub-project-in-the-svn-repo-friendly-coins/</link>
		<comments>http://cumulus.ixcode.org/2009/03/23/new-sub-project-in-the-svn-repo-friendly-coins/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 15:14:03 +0000</pubDate>
		<dc:creator>carl</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=44</guid>
		<description><![CDATA[Hi!  First blog post from me.  In at attempt to kill two birds with one stone, I&#8217;m:

Starting a new small project, called friendly-coins.
This project happens to be a suggestion for a new Coding Problem.  Therefore we get a solution to the problem, as well as some Object Calisthenics.

The repo is at: http://code.google.com/p/cumulus-code/source/browse/#svn/friendly-coins
Look at [...]]]></description>
			<content:encoded><![CDATA[<p>Hi!  First blog post from me.  In at attempt to kill two birds with one stone, I&#8217;m:</p>
<ul>
<li>Starting a new small project, called friendly-coins.</li>
<li>This project happens to be a suggestion for a new Coding Problem.  Therefore we get a solution to the problem, as well as some Object Calisthenics.</li>
</ul>
<p>The repo is at: <a href="http://code.google.com/p/cumulus-code/source/browse/#svn/friendly-coins" target="_blank">http://code.google.com/p/cumulus-code/source/browse/#svn/friendly-coins</a></p>
<p>Look at the &#8220;PROBLEM-STATEMENT.txt&#8221; file to see what the problem is all about.  Stay tuned (next blog post) for the beginnings of a narrative of Object Calisthenics experiences to date.</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/03/23/new-sub-project-in-the-svn-repo-friendly-coins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Code is moved to googlecode</title>
		<link>http://cumulus.ixcode.org/2009/03/18/code-is-moved-to-googlecode/</link>
		<comments>http://cumulus.ixcode.org/2009/03/18/code-is-moved-to-googlecode/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 19:43:31 +0000</pubDate>
		<dc:creator>Jim</dc:creator>
				<category><![CDATA[meta]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=41</guid>
		<description><![CDATA[After much palaver involving moving the directory structure around, I finally had it working and then remembered about googlecode. As it give quite a nice browsing experience, allows you to review code and also to make comments, I thought I would move it over there.
You can now find it at http://code.google.com/p/cumulus-code/
It also provides issue tracking [...]]]></description>
			<content:encoded><![CDATA[<p>After much palaver involving moving the directory structure around, I finally had it working and then remembered about googlecode. As it give quite a nice browsing experience, allows you to review code and also to make comments, I thought I would move it over there.</p>
<p>You can now find it at <a href="http://code.google.com/p/cumulus-code/">http://code.google.com/p/cumulus-code/</a></p>
<p>It also provides issue tracking and a wiki which might be useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/03/18/code-is-moved-to-googlecode/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Created a sub-project</title>
		<link>http://cumulus.ixcode.org/2009/03/18/created-a-sub-project/</link>
		<comments>http://cumulus.ixcode.org/2009/03/18/created-a-sub-project/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 11:32:09 +0000</pubDate>
		<dc:creator>Jim</dc:creator>
				<category><![CDATA[meta]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=29</guid>
		<description><![CDATA[We have moved the source code into a sub directory in the svn repository. We have decided to call our first project &#8220;feedcloud&#8221; because its intent is to turn a feed into a tag cloud. This will allow us to add more projects along the way so that others can contribute to the cloud.
]]></description>
			<content:encoded><![CDATA[<p>We have moved the source code into a sub directory in the svn repository. We have decided to call our first project &#8220;feedcloud&#8221; because its intent is to turn a feed into a tag cloud. This will allow us to add more projects along the way so that others can contribute to the cloud.</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/03/18/created-a-sub-project/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Day 3</title>
		<link>http://cumulus.ixcode.org/2009/03/07/day-3/</link>
		<comments>http://cumulus.ixcode.org/2009/03/07/day-3/#comments</comments>
		<pubDate>Sat, 07 Mar 2009 10:01:41 +0000</pubDate>
		<dc:creator>Jim</dc:creator>
				<category><![CDATA[diary]]></category>

		<guid isPermaLink="false">http://cumulus.ixcode.org/?p=22</guid>
		<description><![CDATA[So we only got about half a day today but completed a small spike getting the database set up correctly. I also had some interesting feedback from Jeff around static methods which I have written up here.
Our DB spike simply does a set of CRUD against mysql, so now everything is set up. To run [...]]]></description>
			<content:encoded><![CDATA[<p>So we only got about half a day today but completed a small spike getting the database set up correctly. I also had some interesting feedback from Jeff around static methods which I have written up <a href="http://jimbarritt.com/non-random/2009/03/07/object-calisthenics-jeff-bay-part-2/">here</a>.</p>
<p>Our DB spike simply does a set of CRUD against mysql, so now everything is set up. To run it you will need a mysql db called cumulusdb with appropriate user, which you can see in the code, you might of course want to change the password.</p>
<p>The code is in the spike package <a href="http://cumulus.ixcode.org/svn/trunk/src/spike/java/org/ixcode/cumulus/spike/mysql/">org.ixcode.cumulus.spike.mysql</a> is in svn.</p>
<p>So now we are ready to roll! Oh except we have to go off to some projects&#8230;. Hopefully will find some time to work on this in between.</p>
]]></content:encoded>
			<wfw:commentRss>http://cumulus.ixcode.org/2009/03/07/day-3/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

