<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><title>Design @ clintshank.javadevelopersjournal.com</title><link>http://clintshank.javadevelopersjournal.com/</link><description>(Design) My thoughts on software development.</description><copyright>Copyright 2008 clintshank.javadevelopersjournal.com</copyright><generator></generator><lastBuildDate>Fri, 05 Sep 2008 17:00:00 GMT</lastBuildDate><image><title>Design @ clintshank.javadevelopersjournal.com</title><url>http://res.sys-con.com/portlet/163/featured-blog-graphic-145.gif</url><link>http://clintshank.javadevelopersjournal.com/</link></image><ttl>360</ttl><docs>http://backend.userland.com/rss</docs><item><title>Law of Demeter and Unit Test Setup</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/long_unit_test_setup.htm</guid><link>http://clintshank.javadevelopersjournal.com/long_unit_test_setup.htm</link><pubDate>Sat, 01 Dec 2007 01:23:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=long%5Funit%5Ftest%5Fsetup</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Have you ever seen or even developed a long, complex setup method in JUnit?&nbsp; Maybe it was because the production code was violating the <a href="http://en.wikipedia.org/wiki/Law_of_Demeter">Law of Demeter</a>.&nbsp; Here&#39;s another <a href="http://www.objectmentor.com/resources/publishedArticles.html">Robert Martin Craftsman style</a> blog.</p><p><strong>Apprentice</strong>: &nbsp;Journeyman, I&#39;m having trouble writing the fixtures for my JUnit tests.&nbsp; They take too long.&nbsp; I spend about 10 times longer writing tests than the production code.</p><p><strong>Journeyman</strong>: &nbsp;Really?&nbsp; Unit test expert Gerard Meszaros <a href="http://www.se-radio.net/podcast/2007-10/episode-70-gerard-meszaros-xunit-test-patterns">says</a> that tests should take only 10% to 20% of development time.</p><p><strong>Apprentice</strong>: &nbsp;Well, I&#39;m experiencing the exact opposite.</p><p><strong>Journeyman</strong>: &nbsp;Let me take a look.</p><p><strong>Apprentice</strong>:&nbsp;&nbsp;Sure.</p><p><strong>Author Note</strong>: &nbsp;This is a trivial example for this blog entry.&nbsp; I&#39;ve seen some really obscure test setup methods.&nbsp;&nbsp;The example is based on the sequence diagram chapter in Martin Fowler&#39;s <a href="http://www.amazon.com/exec/obidos/ASIN/0321193687">UML Distilled</a> book.</p><pre>public class OrderTest {<br /> <br />     private Order order;<br /> <br />     @Before<br />     public void setUp() throws Exception {<br />         Product product1 = new Product(11.00);<br />         OrderLine line1 = new OrderLine(2, product1);<br />         <br />         Product product2 = new Product(22.00);<br />         OrderLine line2 = new OrderLine(3, product2);<br /> <br />         OrderLine[] lines = new OrderLine[] {line1, line2};<br />         order = new Order(Arrays.asList(lines));<br />     }<br />     <br />     <br />     @Test<br />     public void priceShouldBe88() {<br />         assertEquals(88.00, order.getPrice());<br />     }<br /> }<br /> &nbsp;</pre><p><strong>Journeyman</strong>:&nbsp; Okay, can I see the Order.getPrice() method?</p><pre>    public double getPrice() {<br />         double price = 0.00;<br />         <br />         for (OrderLine orderLine : orderLines) {<br />             Product product = orderLine.getProduct();<br />             double productPrice = product.getPrice();<br />             int quantity = orderLine.getQuantity();<br />             price += productPrice * quantity;<br />         }<br />         <br />         return price;<br />     }<br /> </pre><p><strong>Journeyman</strong>:&nbsp; Ah, I see the issue.&nbsp; Have you ever heard of the Law of Demeter (LoD)?</p><p><strong>Apprentice</strong>: &nbsp;Huh?</p><p><strong>Journeyman</strong>:&nbsp; The LoD has a few different names and related principles, but basically it means that an object should only deal with and only with its collaborators.</p><p><strong>Apprentice</strong>:&nbsp; Huh?</p><p><strong>Journeyman</strong>: You see how Order iterates through its OrderLine objects?</p><p><strong>Apprentice</strong>:&nbsp; Yeah.</p><p><strong>Journeyman</strong>:&nbsp; Well, that&#39;s fine.&nbsp; But then you grab the Product and then grab its price.&nbsp; You&#39;ve violated the LoD.&nbsp; Order should only know about OrderLines.&nbsp; You&#39;ve got more of a procedural design here, where you reach down into all the objects in the graph, grabbing all the data you need, and then do your thing.&nbsp; A more object oriented design would be to distribute the work.&nbsp; Do a little bit of work and delegate the rest to collaborating objects.</p><p><strong>Apprentice</strong>:&nbsp; Oh, I think I&#39;m beginning to see.</p><p><strong>Journeyman</strong>:&nbsp; You should go read up on Craig Larman&#39;s <a href="http://www.amazon.com/Applying-UML-Patterns-Introduction-Object-Oriented/dp/0131489062">GRASP</a> principles.&nbsp; He calls the LoD Don&#39;t Talk to Strangers.</p><p><strong>Apprentice</strong>:&nbsp; Okay, will do.</p><p><strong>Journeyman</strong>:&nbsp; Have you been following&nbsp;<a href="http://en.wikipedia.org/wiki/Test-driven_development">test driven development</a> (TDD)?</p><p><strong>Apprentice</strong>:&nbsp; Uh..., well..., not really.&nbsp; But I do&nbsp;write the tests afterwards.</p><p><strong>Journeyman</strong>:&nbsp; Complex test fixtures jump right out at you when you&#39;re doing TDD.&nbsp; You realize something is wrong right away.&nbsp; In fact, many times your testing style changes into more of an <a href="http://benpryor.com/blog/index.php?/archives/28-State-based-vs.-Interaction-based-Unit-Testing.html">interaction based style</a>.&nbsp; But I&#39;m getting ahead of myself.&nbsp; Let&#39;s refactor this together.</p><p><strong>Apprentice</strong>:&nbsp; Okay, cool,&nbsp;pair programming.</p><p><strong>Journeyman</strong>:&nbsp; Right.&nbsp; Remember, Order should only deal with OrderLines.</p><p>Now, the setUp() method looks like:</p><pre>     @Before<br />     public void setUp() throws Exception {<br />         OrderLine line1 = stubOrderLineGetPriceToReturn(22.00);<br />         OrderLine line2 = stubOrderLineGetPriceToReturn(66.00);<br /> <br />         OrderLine[] lines = new OrderLine[] {line1, line2};<br />         order = new Order(Arrays.asList(lines));<br />     }<br /> </pre><p>And the Order.getPrice() method looks like:</p><pre>    public double getPrice() {<br />         double price = 0.00;<br />         <br />         for (OrderLine orderLine : orderLines) {<br />             price += orderLine.getPrice();<br />         }<br />         <br />         return price;<br />     }<br /> </pre><p><strong>Apprentice</strong>:&nbsp; Okay, now I really see.&nbsp;&nbsp;Order and its test are simpler, but don&#39;t we have the same amount of work anyway?&nbsp; We had to write OrderLine.getPrice() and test that.</p><p><strong>Journeyman</strong>:&nbsp; Yes.&nbsp; The work is distributed. &nbsp;But I prefer lots of simpler objects with simpler test specifications than more complex objects and tests.</p><p><strong>Apprentice</strong>:&nbsp; What do you mean, more objects?&nbsp; We didn&#39;t create any new objects.</p><p><strong>Journeyman</strong>:&nbsp; I meant generally speaking, not necessarily in this case.&nbsp; Like I said, do a little work and pass the buck.&nbsp; That might mean creating <a href="http://martinfowler.com/bliki/DataClump.html">Data Clumps</a>, aggregate objects for collections, objects that represent abstract data types, and so on, but again, I&#39;m getting ahead of myself.</p><p><strong>Apprentice</strong>:&nbsp; Should I always follow the LoD?</p><p><strong>Journeyman</strong>:&nbsp; Well, there are of course consequences.&nbsp; Classes tend to have larger APIs because sometimes they need to wrap the functionality of collaborating objects.&nbsp; And you need to step through more objects to understand an algorithm as a whole because it&#39;s distributed.&nbsp; But most of the time, I follow LoD because dependencies are reduced.</p><p><strong>Apprentice</strong>:&nbsp; All right, I&#39;ll give it a shot.&nbsp; Thanks.</p><p>&nbsp;</p>]]></description><category>testing</category><category>design</category><category>lod</category></item><item><title>The Difference Between a Property, Field, Attribute</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/difference_property_field.htm</guid><link>http://clintshank.javadevelopersjournal.com/difference_property_field.htm</link><pubDate>Fri, 03 Aug 2007 14:05:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=difference%5Fproperty%5Ffield</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>I&rsquo;ve been asked a similar question at least three times this year.&nbsp; It goes something like, &ldquo;What&rsquo;s the difference between a field and a property?&rdquo;&nbsp; Or, &ldquo;Is there a difference between an attribute and a property?&rdquo;&nbsp; Given that many inexperienced developers automatically generate getters and setters for all their fields, I can understand the confusion.</p><p>I always give them the example of a circle.&nbsp; Here&rsquo;s some Groovy code:</p><pre>class Circle {<br />&nbsp;&nbsp;&nbsp; def radius<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; def getDiameter() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2 * radius<br />&nbsp;&nbsp;&nbsp; }</pre><pre>&nbsp;&nbsp;&nbsp; def getArea() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Math.PI * Math.pow(radius, 2)<br />&nbsp;&nbsp;&nbsp; }<br />&nbsp;&nbsp;&nbsp; <br />&nbsp;&nbsp;&nbsp; def getCircumference() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 2 * radius * Math.PI<br />&nbsp;&nbsp;&nbsp; }<br />}</pre><p><em>radius</em> is a field, also known as an instance variable, also known as a member variable in C++.&nbsp; It&rsquo;s an implementation detail of the <em>Circle</em>, i.e., it&rsquo;s a private variable that gets stored as part of the <em>Circle</em> object.</p><p>Properties are more public aspects of an object.&nbsp; In Java, following JavaBeans conventions for getters and setters allows you to expose properties.&nbsp; Those properties don&rsquo;t have to be backed up by fields, but in many cases are.</p><p>Coming back to the Groovy <em>Circle</em>, what are its properties?&nbsp; We&rsquo;ll you get <em>radius</em> for free as a read-write property.&nbsp; But because we&rsquo;ve got some getters that compute other values based on <em>radius</em>, we also have <em>diameter</em>, <em>area</em>, and <em>circumference</em> properties.&nbsp; These happen to be read-only properties since we didn&rsquo;t provide setters, but we could have (which would&nbsp;update the&nbsp;<em>radius</em> field accordingly).&nbsp; You can dump all of a <em>Circle</em> object&rsquo;s properties in Groovy like this: </p><pre>println myCircle.properties</pre><p>The point is <em>Circle</em> could be implemented in different ways: by using a <em>diameter</em> field instead of <em>radius</em>, for instance, but it would have the same properties.</p><p>Now, let&rsquo;s talk about attributes.&nbsp; I typically think of <a href="http://www.uml.org/">UML</a> when I hear attributes.&nbsp; Here&rsquo;s UML for <em>Circle</em>:</p><p><img src="http://files.blog-city.com/files/J06/154001/p/f/circle.png" alt="Circle UML" width="99" height="117" /></p><p>Notice that I&rsquo;ve distinguished the derived <em>diameter</em>, <em>area</em>, and <em>circumference</em> attributes with a &ldquo;/&rdquo;.&nbsp; This is standard UML.&nbsp; <em>radius</em> is a regular, non-derived attribute.&nbsp; We can distinguish fields&nbsp;from other computed properties like this.&nbsp; However, because we&rsquo;re modeling, and thinking in a higher level of abstraction, I like to think of attributes as more synonymous with properties.&nbsp; I&rsquo;d rather not make the assumption that every attribute&nbsp;is implemented with a field.</p><p>A similar discussion of these terms can be found <a href="http://forum.java.sun.com/thread.jspa?threadID=701357&amp;messageID=4068418">here</a>.</p>]]></description><category>programming</category><category>design</category></item><item><title>How to Refactor Many Arguments</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/refactor_many_arguments.htm</guid><link>http://clintshank.javadevelopersjournal.com/refactor_many_arguments.htm</link><pubDate>Fri, 25 May 2007 11:01:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=refactor%5Fmany%5Farguments</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>The following conversation is based on a true story.&nbsp; The roles are taken from <a href="http://www.objectmentor.com/resources/publishedArticles.html">Robert Martin&rsquo;s Craftsman series</a>.</p><p><span style="font-weight: bold">Apprentice:</span>&nbsp; Hey, can I ask you something?<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; Sure.<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; I was looking at a big constructor on one of our domain objects and I saw some groupings and was wondering whether it would be good to create objects for those groupings.&nbsp; Is there some kind of pattern for that?<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; Well first, how many parameters are there?<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; 72.<br /><span style="font-weight: bold">Journeyman:&nbsp;</span> 72!?&nbsp; Wow.&nbsp; Talk about a <a href="http://c2.com/cgi/wiki?TooManyParameters">code smell</a> .&nbsp; <a href="http://pmd.sourceforge.net/rules/index.html">PMD&#39;s ExcessiveParameterList</a>  rule will flip out on this one.&nbsp; I guess the author mapped those parameters straight from the out-of-our-control XML schema, whose document instances get unmarshalled in order to create the object.&nbsp; We don&rsquo;t have to follow suit and create such a flat domain model that matches the schema.<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; What do you mean?<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; Well, what I really mean is that I&#39;d much prefer distributing the logic among some richer objects.&nbsp; That is, create more little objects with little methods that do a little of the work.&nbsp; Not one big object that does it all.&nbsp; There would be an impedance mismatch between XML and the domain model, but that&rsquo;s typical because of the technology differences.&nbsp; I suppose the only benefit of the big constructor approach is the simpler mapping... maybe, but the negatives are much too great.<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; What are the negatives?<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; Well, for one, trying to list all 72 parameters in the correct order would be a pain.&nbsp; And trying to understand the object as a whole with all those fields would be difficult.&nbsp; Here [grabbing his <a href="http://martinfowler.com/books.html#refactoring">Refactoring</a>  book].&nbsp; You were initially asking about the &ldquo;Introduce Parameter Object&rdquo; refactoring.&nbsp; Read that refactoring.&nbsp; It can probably give you better details.<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; Martin Fowler.&nbsp; Does he know what he&rsquo;s talking about?<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; Oh yeah.&nbsp; He&rsquo;s one of the Masters.&nbsp; Let&rsquo;s take a look at the class.&nbsp; [Brings up the class in the IDE]</p> <pre>  public ImportantDomainObject(</pre><pre>    ...</pre><pre>    int x, int y,</pre><pre>    ...</pre><pre>    double min, double max,</pre><pre>    ...)</pre> <p>Well, I can see a few <a href="http://www.martinfowler.com/bliki/DataClump.html">data clumps</a>  already.&nbsp; You see the &lt;code&gt;x&lt;/code&gt; and &lt;code&gt;y&lt;/code&gt;?<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; Yeah.<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; That&rsquo;s probably a &lt;code&gt;Point&lt;/code&gt;.&nbsp; Also, that &lt;code&gt;min&lt;/code&gt; and &lt;code&gt;max&lt;/code&gt;, that looks like a &lt;code&gt;Range&lt;/code&gt;.&nbsp; What I would do is search for data clumps like these and create objects for them.&nbsp; Then, see where they&rsquo;re used in &lt;code&gt;ImportantDomainObject&lt;/code&gt; and start moving behavior into the new objects.&nbsp; Distribute the logic.&nbsp; We can create a richer domain model this way.&nbsp; You&rsquo;ll probably find clumps of these clumps and can follow the same process.<br /><span style="font-weight: bold">Apprentice:</span>&nbsp; Okay.&nbsp; This sounds great.&nbsp; Thanks.&nbsp; I&rsquo;m on it.<br /><span style="font-weight: bold">Journeyman:</span>&nbsp; Thank you for recognizing this and taking the initiative to improve the code base.</p><p>&nbsp;</p>]]></description><category>programming</category><category>design</category></item><item><title>DBC Precondition/Postcondition Subclass Rules</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/dbc_precondition_postcondition_subclass_rules.htm</guid><link>http://clintshank.javadevelopersjournal.com/dbc_precondition_postcondition_subclass_rules.htm</link><pubDate>Thu, 12 Apr 2007 23:32:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=dbc%5Fprecondition%5Fpostcondition%5Fsubclass%5Frules</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>I was recently in a discussion regarding the <a href="http://en.wikipedia.org/wiki/Precondition">precondition</a>  and <a href="http://en.wikipedia.org/wiki/Postcondition">postcondition</a>  <a href="http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29">covariance and contravariance</a>  rules of <a href="http://en.wikipedia.org/wiki/Design_by_contract">design by contract (DBC)</a>  in an inheritance/implementation hierarchy.  In order to obey the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle">Liskov substitution principle (LSP)</a> , a subclass or interface implementation can only meet or:</p><ul><li>Weaken the preconditions of the base class, not strengthen them (contravariance).</li><li>Strengthen the postconditions of the base class, not weaken them (covariance).</li></ul><p>There was some confusion as to why this was the case.  So I came up with an analogy to explain.  If you think in terms of the client requesting services of an object specifying the preconditions and postconditions, it all makes sense.</p><p>So the analogy?  Have you ever had to request a help desk ticket?  Maybe you need administrative rights or something.  And you hope that a specific someone is assigned to that ticket because she&#39;s really good and can get the job done quickly and accurately.  Let&#39;s use that as an example.</p><p>The general IT support group contract is:</p><ul><li>Precondition: Submit a help desk ticket filling in all the forms on the web site.</li><li>Postcondition: We&#39;ll get back to you within two hours.</li></ul><p>Now, suppose Suzy Support works in the IT support group.  She&#39;s really good and efficient.  You can think of her as a subclass of the IT support group base class.  In the past, whenever I&#39;ve had a problem and I just happened, purely by chance, to pass her in the hallway and mention it to her, she could solve it in minutes.  From my perspective, as a client of the IT support group, that&#39;s acceptable.</p><p>Suzy&#39;s contract is:</p><ul><li>Precondition: Just tell me the problem.  You don&#39;t have to fill out a help desk ticket for me.  This is weaker than the IT support group&#39;s precondition because I have less work to do.</li><li>Postcondition: I&#39;ll solve it in minutes.  This is a stronger postcondition.  I get better response time.</li></ul><p>Make sense?</p><p>By the way, for all the IT support group managers out there, this is just an analogy.  I know bypassing the help desk ticketing system messes up metrics.</p><p>&nbsp;</p>]]></description><category>design</category></item><item><title>Collection Utility Methods on the Object</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/collectionmethodsonobject.htm</guid><link>http://clintshank.javadevelopersjournal.com/collectionmethodsonobject.htm</link><pubDate>Sun, 16 Apr 2006 23:16:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=collectionmethodsonobject</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p class="MsoNormal">&nbsp;</p>
<p>I&rsquo;ve been experimenting lately with a technique that I&rsquo;m still unsure about. It has a little smell to it, but it has some benefits. The technique is to add static collection-related utility methods on an object. That is, I&rsquo;ll add a static method that takes a collection of that object on the object itself.</p>
<p>Take the classic Shape example:</p>
<pre>public class Shape {<br />&nbsp;  // here&rsquo;s a typical instance method   <br />&nbsp;&nbsp; public void draw();<br /><br />   // here's what I&rsquo;m talking about.   <br />&nbsp;&nbsp; public static void draw(Collection shapes) {      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (Iterator it = shapes.iterator(); it.hasNext; ) {         <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Shape shape = (Shape) it.next();         <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; shape.draw();      <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }   <br />&nbsp;&nbsp; }<br />}<br /></pre>
<p>Now, I haven&rsquo;t done this kind of thing much; maybe once or twice. The first time I did it was because I noticed some duplication. The exact looping code was shared by multiple clients. I wanted to remove the duplication, but I didn&rsquo;t know where to put it, so I stuck it on the object itself. The clients became (in the context of this example):</p>
<pre>someShapeClientMethod() {   <br />   ...   <br />   Shape.draw(myShapes);      <br />   ...<br />}</pre>
<p>I think this actually improves clarity (although I could have accomplished the same thing by creating a helper <font face="Courier New">draw()</font> method in the client). This also has the benefit of grouping the iteration logic close to its source, e.g.,<font face="Courier New">Shape</font> here.</p>
<p>The real world example where I first used this was a query.&nbsp; I had a collection of objects and I wanted to find a specific one. Say, I had a collection of Shapes and I wanted to know who was the biggest:</p>
<pre>public static Shape getBiggest(Collection shapes);</pre>
<p>I think this technique is most applicable under the following circumstances:</p>
<ol>
    <li>For good reason, multiple clients share the code and you want to remove the duplication. </li>
    <li>The number of such utility methods is very small. Otherwise, it would be better to group the methods in another, separate utility class (e.g., <font face="Courier New">Shapes</font> or <font face="Courier New">ShapeUtils</font>). </li>
</ol>
<p>What bothers me most is that I can&rsquo;t recall seeing this technique used anywhere. That could mean that there&rsquo;s something really bad about it. One problem is that it clutters the object with additional methods. That&rsquo;s why I think it should be used judiciously. Also, from a purist view, do these methods really belong on the object?</p>
<p>What do you think?</p>]]></description></item><item><title>A Common Set of Test Refactorings</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/commontestrefactorings.htm</guid><link>http://clintshank.javadevelopersjournal.com/commontestrefactorings.htm</link><pubDate>Sun, 19 Feb 2006 13:02:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=commontestrefactorings</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[Today, I want to blog about what I think might be my most common set of low level Eclipse refactorings used together when I&rsquo;m developing unit tests.&nbsp;I use this set to parameterize tests as discussed in <a href="http://clintshank.javadevelopersjournal.com/tabulartests.htm">Tabular Tests</a>.&nbsp;Lately, I&rsquo;ve been trying to use the Eclipse refactorings as much as possible, thinking that the automation would be less likely to break things than if I made the changes manually.&nbsp;It&rsquo;s also interesting to make code changes without doing any typing.&nbsp;The set consists of:
<ol type="1" style="margin-top: 0in;" start="1">
    <li><font face="Courier New">Extract      Local Variable</font> (possibly multiple times).</li>
    <li><font face="Courier New">Extract      Method</font></li>
    <li><font face="Courier New">Inline</font>      the local variables created in step 1.</li>
</ol>
So let&rsquo;s suppose I&rsquo;m about to start work on a new method.&nbsp;I like to start with a brain dump of most, if not all of the test cases.&nbsp;This is to get me thinking about the desired behavior and also because it clears my head, so that when I start writing the code, I can focus.&nbsp;Once I&rsquo;m ready, I start with a simple case.
<p>Let&rsquo;s take the <font face="Courier New">Range.equals()</font> example from the previous blog.&nbsp;My brain dump would have resulted in a table like this:</p>
<p>
<table width="200" cellspacing="1" cellpadding="1" border="1" align="">
    <tbody>
        <tr>
            <td><strong>Min</strong></td>
            <td><strong>Max</strong></td>
            <td><strong>Equals?</strong></td>
        </tr>
        <tr>
            <td>same</td>
            <td>same</td>
            <td>true</td>
        </tr>
        <tr>
            <td>different</td>
            <td>same</td>
            <td>false</td>
        </tr>
        <tr>
            <td>same</td>
            <td>different</td>
            <td>false</td>
        </tr>
    </tbody>
</table>
</p>
<p>Yes, I would have jotted down other, exceptional cases for things like <font face="Courier New">null</font> and a non-<font face="Courier New">Range</font> object, but that&rsquo;s out of scope here.&nbsp;For this blog, I&rsquo;m just concentrated on comparing <font face="Courier New">Range</font> objects.&nbsp;I start with the positive case and come up with something like:</p>
<p><code><span style="font-size: 10pt;">&nbsp;&nbsp; private static final int MIN = 1;<br /> &nbsp;&nbsp; private static final int MAX = 7;<br /> <br /> &nbsp;&nbsp; private Range range = new Range(MIN, MAX);</span></code> </p>
<div><code>&nbsp;</code></div>
<code><span style="font-size: 10pt;">&nbsp; &nbsp;public void testEqualsAnotherRange() {<br /> &nbsp; &nbsp; &nbsp; Range anotherRange = new Range(MIN, MAX);<br /> &nbsp; &nbsp; &nbsp; assertEquals(range, anotherRange);<br /> &nbsp; &nbsp;}</span></code>
<p>&nbsp;</p>
<p><code><span style="font-size: 10pt;"> </span></code>To be honest, I probably would have had the <font face="Courier New">MIN</font> and <font face="Courier New">MAX</font> constants hardcoded in there, but at some point, I would have performed <font face="Courier New">Extract Constant</font> to come up with the above.</p>
<p>After I get that test to pass (by returning <font face="Courier New">true</font>), I&rsquo;m ready to write the next test.&nbsp;I want to pick something simple again (of course in this example they&rsquo;re all simple).&nbsp;But before I write the next test, I do something that is probably considered cheating by the hardcore test-driven development crowd.&nbsp;I&rsquo;m not too concerned because I know from experience that I&rsquo;m going to end up with tabular tests.&nbsp;In fact, the table is specified above! &nbsp;So here goes the set of refactorings:</p>
<p>I first <font face="Courier New">Extract Local Variable</font> on <font face="Courier New">MIN</font> and <font face="Courier New">MAX</font>:</p>
<p><code><span style="font-size: 10pt;">&nbsp; &nbsp;public void testEqualsAnotherRange() {<br /> &nbsp; &nbsp; &nbsp; <strong>int testMin = MIN;<br /> &nbsp; &nbsp; &nbsp; int testMax = MAX;</strong><br /> &nbsp; &nbsp; &nbsp; Range anotherRange = new Range(<strong>testMin, testMax</strong>);<br /> &nbsp; &nbsp; &nbsp; assertEquals(range, anotherRange);<br /> &nbsp; &nbsp;}</span></code></p>
<p><code><span style="font-size: 10pt;"></span></code><span style=""><br /> </span>Now I know from my table that I need a <font face="Courier New">boolean</font> for my expected equals. There's no simple Eclipse refactoring so I manually make the change: </p>
<p><code><span style="font-size: 10pt;">&nbsp;&nbsp; public void testEqualsAnotherRange() {<br /> &nbsp; &nbsp; &nbsp; int testMin = MIN;<br /> &nbsp; &nbsp; &nbsp; int testMax = MAX;<br /> &nbsp; &nbsp; &nbsp; <strong>boolean expectedEquals = true;</strong><br /> &nbsp; &nbsp; &nbsp; Range anotherRange = new Range(testMin, testMax);<br /> &nbsp; &nbsp; &nbsp; <strong>assertEquals(expectedEquals, range.equals(anotherRange));</strong><br /> &nbsp; &nbsp;}</span></code></p>
<p><code><span style="font-size: 10pt;"></span></code><span style=""><br /> </span>I highlight the last two lines and perform <font face="Courier New">Extract Method</font>:<br /><br /> <code><span style="font-size: 10pt;">&nbsp; &nbsp;public void testEqualsAnotherRange() {<br /> &nbsp; &nbsp; &nbsp; &nbsp;int testMin = MIN;<br /> &nbsp; &nbsp; &nbsp; &nbsp;int testMax = MAX;<br /> &nbsp; &nbsp; &nbsp; &nbsp;boolean expectedEquals = true;<br /> &nbsp; &nbsp; &nbsp; &nbsp;<strong>testEqualsAnotherRange(testMin, testMax, expectedEquals);</strong><br /> &nbsp; &nbsp;}<br /> <br /><strong> &nbsp; &nbsp;private void testEqualsAnotherRange(int testMin, int testMax,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;boolean expectedEquals) {<br /> &nbsp; &nbsp; &nbsp; &nbsp;Range anotherRange = new Range(testMin, testMax);<br /> &nbsp; &nbsp; &nbsp; &nbsp;assertEquals(expectedEquals, range.equals(anotherRange));<br /> &nbsp; &nbsp;}</strong></span></code></p>
<p><code><span style="font-size: 10pt;"></span></code><span style=""><br /> </span>I want to get back to what it looks like in the table, so I <font face="Courier New">Inline</font> each local variable:</p>
<p><code><span style="font-size: 10pt;">&nbsp;&nbsp; public void testEqualsAnotherRange() {<br />&nbsp; &nbsp; &nbsp; testEqualsAnotherRange(<strong>MIN, MAX, true</strong>);<br /> &nbsp; &nbsp;}<br /> <br /> &nbsp; &nbsp;private void testEqualsAnotherRange(int testMin, int testMax,<br /> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;boolean expectedEquals) {<br /> &nbsp; &nbsp; &nbsp; Range anotherRange = new Range(testMin, testMax);<br /> &nbsp; &nbsp; &nbsp; assertEquals(expectedEquals, range.equals(anotherRange));<br /> &nbsp; &nbsp;}</span></code></p>
<p><code><span style="font-size: 10pt;"></span></code><span style=""><br /> </span>I just created the first row of the table by applying the set of refactorings that is the topic of this blog.&nbsp;At this point, I usually look at the parameterized method and make sure I&rsquo;m happy with the signature.&nbsp;I&rsquo;ve already done most of this when I extracted the method, but Eclipse doesn&rsquo;t let me make the method <font face="Courier New">static</font>, if that&rsquo;s appropriate (in this case it&rsquo;s not).&nbsp;Eclipse also lists all the checked exceptions, which for tests, I&rsquo;d rather generalize to <font face="Courier New">Exception</font>.&nbsp; This doesn't apply in this case either.<br /></p>
<p>During this set of refactorings, I would have ran the tests after a change or two just to make sure I didn&rsquo;t break anything.&nbsp;I also do that because it feels good to get that green bar.</p>
<p>This is a pretty trivial example.&nbsp;Most of the time much more is going on in the parameterized method, but this still shows the removal of duplication.</p>
<p>I could have made these changes manually, but like I mentioned above, I like the automation; I&rsquo;m less likely to break things.</p>
<div>Okay, I can write the next test now:</div>
<p><code><span style="font-size: 10pt;">&nbsp;&nbsp; public void testEqualsAnotherRange() {<br /> &nbsp; &nbsp; &nbsp; testEqualsAnotherRange(MIN, &nbsp; &nbsp; MAX, true);<br /> &nbsp; &nbsp; &nbsp; <strong>testEqualsAnotherRange(MIN - 1, MAX, false);</strong><br /> &nbsp; &nbsp;}</span></code></p>
<p><code><span style="font-size: 10pt;"> </span></code>I&rsquo;ve got the red bar.&nbsp;Time to make it green.</p>
<div>&nbsp;</div>]]></description></item><item><title>TDD Pattern: Tabular Tests</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/tabulartests.htm</guid><link>http://clintshank.javadevelopersjournal.com/tabulartests.htm</link><pubDate>Sun, 05 Feb 2006 19:23:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=tabulartests</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p><font face="Arial">Today, I thought I'd blog about one of my most common testing patterns.&nbsp; I call it table-like tests because I end up with a test method that calls a helper, parameterized test method.&nbsp; The high level test method shows all the test cases in what looks kind of like a table.&nbsp; </font>     To give proper credit to this technique, I believe I read about it on <a href="http://www.junit.org/">www.junit.org</a> or one of the XP sites years ago, but I couldn't find the article with a quick Google search.&nbsp; To demonstrate, <font face="Arial">suppose I were working on a <font face="Courier New">Range</font> class and was currently focused on the </font><font face="Arial"><font face="Courier New">equals() </font>method.&nbsp; I'd end up with the following:</font></p>
<font face="Courier New">&nbsp;&nbsp; private static final int MIN = 1;<br />&nbsp;&nbsp; private static final int MAX = 7;<br /><br /> &nbsp;&nbsp; private Range range = new Range(MIN, MAX);<br /><br />&nbsp;&nbsp; public void testEqualsAnotherRange() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; testEqualsAnotherRange(MIN,&nbsp;&nbsp;&nbsp;&nbsp; MAX, true);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; testEqualsAnotherRange(MIN - 1, MAX, false);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; testEqualsAnotherRange(MIN,&nbsp;&nbsp;&nbsp;&nbsp; MAX + 1, false);<br /></font><font face="Courier New"><font face="Courier New">&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp; private void testEqualsAnotherRange(int testMin,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; int testMax, boolean expectedEquals) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br />&nbsp;&nbsp; }<br /></font>  <br /></font>
<p><font face="Arial">Now, I know there are other tests for the <font face="Courier New">equals()</font> method, but I'm focusing on the meat of the tests here.&nbsp; I also want to emphasize that I don't start out specifying all the tests like this.&nbsp; I actually write one of the test cases, get that test to pass by minimally implementing the <font face="Courier New">Range</font> class, and then, as I start to write the next test case, I see the pattern and will extract the method and parameterize it for the next test case.</font></p>
<p><font face="Arial"> </font><font face="Arial">Time to make some points:</font></p>
<ol>
    <li>Test cases for the <font face="Courier New">equals()</font> method are grouped together.&nbsp; If I want to know how the <font face="Courier New">equals()</font> method works for non-exceptional cases, all the test cases are right there. When I write code, I focus on a method for a particular production class.&nbsp; That is, I'm trying to build out all the functionality for that method before moving on to the next method (or class).&nbsp; I find it helpful to have all the test cases grouped together.&nbsp; Parameterizing tests keeps the test cases as close together as possible.</li>
    <li>Whenever I detect duplication, I strive to remove it.&nbsp; This is a way to do so among the test cases.</li>
    <li>The mapping between test methods and production class methods is nearly one to one.&nbsp; There's one main <font face="Courier New">testEquals() </font>method for one <font face="Courier New">equals()</font> method.&nbsp; Of course, I'll have test methods for exceptional cases, but I don't have much more test methods than production methods.&nbsp; If I kept each test case in its own method, I'd have a harder time removing duplication and I would have much more test code than production code.<br /></li>
</ol>
<p><font face="Arial"> </font></p>
<p><font face="Courier New"><font face="Arial">I should also point out that many times, I don't use the same fixture.&nbsp; In the example above, I did, but many times I don't.&nbsp; The parameters passed in to the test helper method could be used to setup the production object.&nbsp; Sometimes, the parameters are used to help mock a nested object.&nbsp;&nbsp; Take, for example, the typical web site <font face="Courier New">Order</font> class.&nbsp; Let's suppose I were focused on the </font><font face="Arial"><font face="Courier New">getTotal()</font> method:</font></font></p>
<font face="Courier New"><font face="Courier New">&nbsp;&nbsp; private Order order = new Order();<br /><br />&nbsp;&nbsp; public void testGetTotal() {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; assertEquals(0.00, order.getTotal(), 0.0001);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; testGetTotal(1, 3.00, 3.00);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; testGetTotal(3, 5.00, 18.00);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // etc.<br />&nbsp;&nbsp; }<br /><br />&nbsp;&nbsp; private void testGetTotal(int lineItemQuantity,<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; double lineItemPrice, double expectedTotal) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // create a line item<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // add line item to order<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // verify total<br />&nbsp;&nbsp; }<br /></font><br /><font face="Arial"><br /></font></font>
<p><font face="Courier New"><font face="Arial">Now, I should point out some of the concerns of using this technique:</font></font> <br /></p>
<ol>
    <li><font face="Courier New"><font face="Arial">It doesn't follow the JUnit convention of working with the same fixture per <font face="Courier New">TestCase</font>.&nbsp; Many times, my &quot;fixture&quot; is just an empty production object that will be setup in individual test methods.&nbsp; B</font></font><font face="Arial">ehaviour Driven Development (BDD) is getting press these days and its focus is on fixtures called Contexts.&nbsp; Caveat: my knowledge of BDD is from reading this one <a href="http://blog.daveastels.com/files/sdbp2005/BDD%20Intro.pdf">article</a> by Dave Astels, and I haven't experimented with it.&nbsp; It seems to be good for showing behavior in a given context, whereas my technique is method focused.&nbsp; Maybe I'll give it a shot in the future.<br /></font></li>
    <li><font face="Courier New"><font face="Arial">Because there isn't a real fixture, the test methods are more static than object-oriented.&nbsp; That is, I might not be working with instance variables of the <font face="Courier New">TestCase</font>.&nbsp; I don't find this to be an issue though.&nbsp; I thought I'd point it out for OO purists.<br /></font></font></li>
    <li><font face="Courier New"><font face="Arial">Gerard Meszaros, who is writing a good book on <a href="http://tap.testautomationpatterns.com:8080/Book%20Outline.html">test automation patterns</a>, pointed out that if one of my earlier tests fails, then later tests won't be run.&nbsp; He also pointed out that it is harder to determine how many total test cases there are since some are embedded.&nbsp; These are valid points.&nbsp; To counter, I mentioned that I am following test-driven development, so I am building the tests as I go, and I usually don't run into the situation where an earlier test fails, although it does happen.&nbsp; I also never run into the situation where a bunch of tests are all of the sudden failing.&nbsp; As for the number of test cases, I've never had a need to know.&nbsp; But his points are definitely valid.</font></font></li>
    <li><font face="Courier New"><font face="Arial">Tests aren't isolated.&nbsp; You don't start fresh each time.&nbsp; Thus, earlier tests could have unwanted side effects.&nbsp; You have to be aware of this.&nbsp; I either want side effects (as in the <font face="Courier New">Order</font> example where I'm building up an <font face="Courier New">Order</font>) or I simply start with an empty production object and build it up in the helper test method.<br /></font></font></li>
</ol>
<font face="Courier New"><br /></font>]]></description></item><item><title>Coding By Intention</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/coding_by_intention.htm</guid><link>http://clintshank.javadevelopersjournal.com/coding_by_intention.htm</link><pubDate>Tue, 10 Jan 2006 17:56:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=coding%5Fby%5Fintention</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>I thought I'd start blogging about something I think I'm pretty decent at - programming.&nbsp; Yeah, yeah, I know, everybody thinks they are the best programmer, but I think I have some decent stuff to share.&nbsp; I wanted to start with programming tips.&nbsp; I'll try one tip per blog entry.</p>
<p>The first tip is coding by intention.&nbsp;The first time I learned of this was in college.&nbsp;I was reviewing some code with a professor of mine, Dave Binkley of Loyola College.&nbsp;We were reviewing a long method of mine and Professor Binkley said something equivalent to, &ldquo;I like to extract a method here to make it more clear what I&rsquo;m doing.&rdquo;&nbsp;The light came on.&nbsp;I learned that programming was more than just a science, but an art.&nbsp;This was back in the early 90s, before the Extreme Programming/Agile folks coined terms like &ldquo;extract method&rdquo;, &ldquo;refactor&rdquo;, and &ldquo;code by intention&rdquo;.</p>
<p>Now, I'm a big fan of Test-Driven Development (TDD).&nbsp; Since I've got to write a test first, I start there.&nbsp; The real code doesn't exist yet.&nbsp; The intent part starts here.&nbsp; I think, &quot;I've got this piece of functionality to implement.&nbsp; What would I call if I could write anything?&nbsp; What would the method name be and its arguments?&nbsp; How would I call this functionality as a client so that what I'm doing is crystal clear?&nbsp;The world is my oyster.&quot;</p>
<p>Coding by intention from the point of view of the test is pretty obvious.&nbsp; What I wanted to emphasize in this blog entry is to continue coding by intention all the way through until you've completely implemented everything.&nbsp; So after you've created a new call in the test, you start implementing it.&nbsp; It'll most likely be a public method.&nbsp; When you're implementing this, you continue coding by intention.&nbsp; You could just crank out a possibly long method to get the functionality implemented, but that's not what I'm talking about &ndash; that&rsquo;s what I did in the early days of college.&nbsp; The public method now becomes like another client.&nbsp; You code by intention here, asking yourself what you would call if what you needed already existed.&nbsp; You keep doing this with every method you need to implement, creating lots of small, but communicative and easy to understand methods.&nbsp; Eventually, you'll get to a level where the implementation is small and simple and you're done.&nbsp; What you've done is created some possibly reusable and very easy to maintain methods along the way.</p>
<p>It&rsquo;s time for an example.&nbsp;Suppose I&rsquo;m working with the usual Order/Line Items web site shopping example.&nbsp;One coding by intention technique I use when I need to process a collection like LineItems looks like this:</p>
<div><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp; public void processLineItems(List lineItems) {</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Iterator it = lineItems.iterator();</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; while (it.hasNext()) {</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; process((LineItem) it.next());</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp; }</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"></span></div>
<p>Instead of writing all the code in the while loop to process an item, I code by intention, pretending that the <font face="Courier New">process(LineItem)</font> method already exists.</p>
<p>Here&rsquo;s another, albeit obviously contrived example.&nbsp;Suppose I&rsquo;m working on Goldilocks&rsquo; Porridge class and need to implement the <font face="Courier New">isJustRight()</font> method.&nbsp;Right now I just have:</p>
<div><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp; public class Porridge {</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; private double currentTemperature = 0.0;</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;public Porridge(double currentTemperature) {</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; this.currentTemperature = currentTemperature;</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp; }</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"></span></div>
<p>To implement <font face="Courier New">isJustRight()</font>, in coding by intention style, I would do:</p>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; public boolean isJustRight() {</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return (notTooHot() &amp;&amp; notTooCold());</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"><font face="Courier New">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }</font></span></div>
<div style="MARGIN: 0in 0in 0pt"><span style="FONT-SIZE: 10pt"></span></div>
<p>So why code by intention?&nbsp;There are several reasons I can think of off the bat.&nbsp;The first is, as I&rsquo;ve stated above, you end up creating small, possibly reusable methods.&nbsp;My first tip was going to be &ldquo;create small methods&rdquo;, but I realized that coding by intention drives that.&nbsp;In my next entry, I&rsquo;ll go into more detail on why I think creating small methods is really important.&nbsp;There&rsquo;s a process to crafting elegant software and this is the first step.</p>
<p>Another reason is that the top level methods become really easy to understand.&nbsp;<br />They describe the algorithm in almost pseudo-code level.&nbsp;They communicate your intent of what you&rsquo;re trying to accomplish step by step.</p>
<p>Yet another reason is that it is sometimes hard to get started on a task and by coding by intention you are delaying all the details, but still getting things done.&nbsp;That is, not everything you need is available, but you&rsquo;re coding like it is.&nbsp;You&rsquo;re working top down, drilling down into the details level by level until your done, making progress along the way.</p>
<p>Now, if you&rsquo;re doing true TDD, you are writing just enough test to get a failing test, and just enough code to pass that test.&nbsp;Remember, compiler errors count as failures.&nbsp;I&rsquo;m a little lenient on this practice.&nbsp;I like writing an entire test method for one test case scenario before going to the code.&nbsp;So in the <font face="Courier New">isJustRight()</font> method above, I&rsquo;d first write a complete test method for a Porridge object that is too cold with all its calls and assertions.&nbsp;Then, I&rsquo;d write just enough code to get the test to pass, but still coding by intention in the Porridge class.&nbsp;So, in this case, the <font face="Courier New">isJustRight()</font> method would just call <font face="Courier New">notTooCold()</font> for now.</p>
<p>I suppose if you truly wanted to follow TDD, and in particular, get a passing test as fast as you could, you could just write the code in <font face="Courier New">isJustRight()</font>, then extract a <font face="Courier New">notTooCold()</font> method.&nbsp;Just remember to do this.&nbsp;Sometimes, we as programmers get a little lazy.&nbsp;Still, I favor coding by intention top down from the beginning.</p>
<p>Well, that&rsquo;s it for my first blog.&nbsp;Hope you enjoyed.</p>
<div>&nbsp;</div>]]></description></item></channel></rss>