<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><title>Clint Shank&apos;s Blog</title><link>http://clintshank.javadevelopersjournal.com/</link><description>My thoughts on software development.</description><copyright>Copyright 2008 clintshank.javadevelopersjournal.com</copyright><generator></generator><lastBuildDate>Sun, 11 May 2008 04:12:00 GMT</lastBuildDate><image><title>Clint Shank&apos;s Blog</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>Quotes from No Fluff Just Stuff</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/no_fluff_just_stuff_quotes.htm</guid><link>http://clintshank.javadevelopersjournal.com/no_fluff_just_stuff_quotes.htm</link><pubDate>Mon, 28 Apr 2008 17:57:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=no%5Ffluff%5Fjust%5Fstuff%5Fquotes</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>I just returned from this past weekend&#39;s <a href="http://www.nofluffjuststuff.com/">No Fluff Just Stuff</a> conference in Reston, Virginia.&nbsp; As always (this was my fifth show), I had a great time conversing with my peers and the excellent speakers.<br /><br />The following are some memorable quotes/paraphrases in chronological order.&nbsp; Some disclaimers: 1) you should always take quotes in context and 2) I could have misinterpreted the intent of the speaker.&nbsp; I&#39;ll try to provide some comments for additional context.<br /><br /><a href="http://www.devjam.biz">David Hussman</a>: &quot;You need to respect the <span class="definition">pomodoro</span>,&quot; quoting an Italian manager of a team who used a tomato timer.&nbsp; They would work hard for 25 minutes, then take a 5 minute break.&nbsp; When one developer wanted to keep working...<br /><br /><a href="http://www.devjam.biz">David Hussman</a>: &quot;Sometimes stand-up meetings turn into stand-there meetings.&quot;&nbsp; This is when nobody is saying anything and we&#39;re just going through the motions.&nbsp; I&#39;ve definitely experienced this.<br /><br /><a href="http://www.agiledeveloper.com">Venkat Subramaniam</a>: In the context of <a href="http://code.google.com/p/google-guice/">Guice</a>, when comparing annotation and xml configuration, &quot;Both XML and annotations are evil.&nbsp; Annotations are the lesser evil.&quot;&nbsp; My opinion is that annotations are a good addition to the Java language, but can certainly be overused.&nbsp; This may be what Venkat was talking about.<br /><br /><a href="http://www.thediscoblog.com">Andrew Glover</a>: &quot;Some people say, &#39;<a href="http://en.wikipedia.org/wiki/Behavior_driven_development">Behavior-Driven Development</a>  (BDD) is <a href="http://en.wikipedia.org/wiki/Test-driven_development">Test-Driven Development</a>  (TDD) done right&#39;, but I say BDD is Customer focused TDD.&quot;&nbsp; BDD is closer to the customer&#39;s language.<br /><br /><a href="http://www.nealford.com/">Neal Ford</a>: &quot;If there were a book written today about real world software development, it would be called Accidental Complexity, Ceremony Over Essence, Ensuring Your Job Security written by the Enterprise Architecture Team.&quot;&nbsp; Neal had tons of good quotes from his excellent keynote.<br /><br /><a href="http://www.agiledeveloper.com">Venkat Subramaniam</a>: &quot;We constantly create whack-a-mole systems.&nbsp; Fix the code in one place and this other, seemingly unrelated part of the code breaks.&quot;&nbsp; Venkat was comparing software development with the children&#39;s game.<br /><br /><a href="http://www.integrallis.com"> Brian Sam-Bodden</a> : &quot;Remember when you had to go outside your IDE to access your version control system?&nbsp; And then, that functionality was integrated with Eclipse?&nbsp; That&#39;s what <a href="http://www.eclipse.org/mylyn/">Mylyn</a>  does for task management.&quot;&nbsp; Less context switching keeps you focused.<br /> <br /><a href="http://agileartisans.com/"> Jared Richardson</a>  or <a href="http://www.nealford.com/">Neal Ford</a>: &quot;Ted Neward is the Las Vegas of speakers.&nbsp; You have to go see him at least once.&quot;&nbsp; I always enjoy Ted&#39;s sessions.<br /> <br /><a href="http://www.tedneward.com"> Ted Neward</a>: Sarcastically, &quot;The code is perfect when it leaves my desk.&nbsp; Something mystical happens afterwards that introduces bugs.&quot;<br /> <br /><a href="http://www.tedneward.com"> Ted Neward</a>: &quot;The Teddy Bear Technique has the added advantage of keeping people away, particularly when you&#39;re caught talking to it by a manager.&quot;&nbsp; The Teddy Bear Technique is the act of explaining your problem to a stuffed animal, and then suddenly solving it as you start to question your assumptions.<br /> <br /><a href="/console/admin/v5/edit/www.tedneward.com"> </a><a href="http://www.tedneward.com"> Ted Neward</a>: &quot;Oh Great Debugger, tell me where the bug is.&quot;<br /> <br /><a href="http://agileartisans.com/"> Jared Richardson</a>: &quot;Take a shortcut here, another shortcut there - you get to a point where you&#39;re so busy paying interest, you don&#39;t have time to pay the principal.&quot;&nbsp; This was in his talk about credit card software development (<a href="http://www.martinfowler.com/bliki/TechnicalDebt.html">Technical Debt</a> ).<br /> <br /><a href="http://agileartisans.com/"> Jared Richardson</a>: Quoting <a href="http://en.wikipedia.org/wiki/Watts_Humphrey">Watts Humphrey</a>, &quot;Developers are caught in a victim&#39;s mentality.&quot;&nbsp; We never think it&#39;s our fault, it&#39;s always somebody else&#39;s.<br /> <br /> Expert Panel: When asked for two words about <a href="http://en.wikipedia.org/wiki/Service-oriented_architecture">SOA</a>, some of the phrases were, &quot;<a href="http://www.w3.org/TR/wsdl">WSDL</a>  sucks&quot;, &quot;Consider <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer">REST</a> &quot;, &quot;Overly complex&quot;<br /> <br /> Expert Panel: When asked for two words about closures, one of the experts said, &quot;Use Groovy&quot;<br /> <br /><a href="http://wmrichards.com/"> Mark Richards</a>: &quot;Java has become over-bloated and way past its usefulness as a general purpose language.&quot;&nbsp; I think he was the one who said, &quot;Use Groovy.&quot;<br /> <br /><a href="http://www.g2one.com"> Jeff Brown</a>: &quot;If we could start [Java] from scratch today, Java would look like Groovy.&nbsp; Groovy is the preferred general purpose language.&quot;<br /> <br /> Jay Zimmerman, Symposium Director: &quot;If you want management approval to use Groovy, don&#39;t call it Groovy, call it Next Generation Java.&quot;&nbsp; Managers freak out when they hear you want to use something called &#39;Groovy.&#39;<br /> </p><p><a href="http://www.tedneward.com"> Ted Neward</a>: &quot;Your peer group is more important than any tool or book we can recommend.&quot;&nbsp; Great advice.<br /> <br /><a href="http://www.davebock.com"> David Bock</a>: &quot;The existence of the system changes the requirements of the system.&quot;&nbsp; Dave was talking about how seeing the system run changes the customer&#39;s mind of what he really wants.<br /> <br /><a href="http://www.davebock.com"> David Bock</a>: &quot;Never believe someone who tells you he&#39;s 90% done.&quot;&nbsp; Ever notice how that last 10% takes a long time?</p><p>I look forward to next time.</p><p>&nbsp;</p>]]></description><category>conference</category><category>show</category></item><item><title>Hudson CI Game Plugin</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/hudson_ci_game_plugin.htm</guid><link>http://clintshank.javadevelopersjournal.com/hudson_ci_game_plugin.htm</link><pubDate>Thu, 17 Apr 2008 22:50:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=hudson%5Fci%5Fgame%5Fplugin</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p><a href="http://redsolo.blogspot.com/">redsolo</a>  has implemented a version of <a href="/ci_build_game.htm">The Continuous Integration Build Game</a>.&nbsp; It&#39;s a <a href="https://hudson.dev.java.net/">Hudson</a>  plugin and is described <a href="http://redsolo.blogspot.com/2008/04/start-playing-continuous-integration.html">here</a> .&nbsp; Way to go redsolo!<br /> </p>]]></description><category>build</category><category>ci</category><category>tools</category></item><item><title>Spring Configuration Per Environment</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/spring_configuration_per_environment.htm</guid><link>http://clintshank.javadevelopersjournal.com/spring_configuration_per_environment.htm</link><pubDate>Wed, 30 Jan 2008 16:10:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=spring%5Fconfiguration%5Fper%5Fenvironment</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>It&#39;s common that configuration changes between environments (e.g., development, test, production).&nbsp; For example, you&#39;d definitely want a different DataSource URL depending on what environment you&#39;re running in.&nbsp; Do you really want to hit the production database while developing?&nbsp; Spring doesn&#39;t seem to support this per environment configuration out of the box (at least I&#39;ve never been able to find it).&nbsp; There&#39;s been a request for this&nbsp;feature&nbsp;for some time now (<a href="http://jira.springframework.org/browse/SPR-1876">SPR-1876</a>), but it&#39;s still open.</p><p>The reality is that properties files are the simplest and easiest way to configure an application, particularly for non-developers.&nbsp; What I&#39;d like to see is a <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html">PropertyPlaceholderConfigurer</a> that can configure an application per environment.&nbsp; This is what SPR-1876 is all about.&nbsp; However, it suggests there be a file per environment.&nbsp; As an alternative, I suggest a single properties file.&nbsp; A single file containing all the properties would be the simplest to maintain.&nbsp; Think of it.&nbsp; I&#39;ve got a new property.&nbsp; Do I want to add it to three files or one?&nbsp; If I want to see all the possible values of a property, do I want to open and hunt through three files or one?</p><p><a href="http://grails.org/doc/1.0.x/guide/3.%20Configuration.html#3.2%20Environments">Grails</a>&nbsp;supports the idea of grouping all the properties together, but it uses&nbsp;multiple configuration files (Config.groovy and DataSource.groovy) depending on the property.</p><p>Okay, so here&#39;s what I propose the properties file look like:</p><pre># this is the default value for all environments<br />my.prop=defaultValue<br /># but in the production environment, it is different<br />[production].my.prop=productionValue<br /> <br /># here&#39;s another property with no default<br /># (adapted example from the Grails user guide)<br />[development].dataSource.url=jdbc:hsqldb:mem:devDB<br />[test].dataSource.url=jdbc:hsqldb:mem:testDb<br />[production].dataSource.url=jdbc:hsqldb:file:prodDb;shutdown=true<br /> </pre><p>The context definition simply uses the property name without the environment and the custom per environment PropertyPlaceholderConfigurer provides the appropriate value:</p><pre>&lt;bean id=&quot;dataSource&quot;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; class=&quot;org.springframework.jdbc.datasource...&quot;&gt;<br />&nbsp; &lt;property name=&quot;url&quot; value=&quot;${dataSource.url}&quot; /&gt;<br />&lt;/bean&gt;</pre><p>So what are the downsides to this approach?&nbsp; I suppose you can argue that a single properties file could be cluttered with details you don&#39;t care about.&nbsp; For example, a production administrator may not care to see all the development and test values.</p><p>The other downside I can think of is forgetting to override a property.&nbsp; That is, nothing reminds you that you have to override the DataSource URL for production.&nbsp; It&#39;s content with using a default value.&nbsp; The separate file approach would handle this because the property would be undefined.</p><p>So if I were reading this I&#39;d say, &quot;Spring is open source dude.&nbsp; And those Spring guys are busy.&nbsp; Go implement it and attach it to SPR-1876.&quot;&nbsp; And if I get some time... </p><p>&nbsp;</p>]]></description><category>spring</category></item><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>Parallel JUnit Ant Task</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/parallel_junit_ant_task.htm</guid><link>http://clintshank.javadevelopersjournal.com/parallel_junit_ant_task.htm</link><pubDate>Tue, 16 Oct 2007 15:41:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=parallel%5Fjunit%5Fant%5Ftask</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Over time, how do you maintain a maximum <a href="http://www.think-box.co.uk/blog/2006/02/ten-minute-build-continuous.html">10 minute build</a>? This is an important agile practice for <a href="http://en.wikipedia.org/wiki/Continuous_integration">continuous integration</a>.</p><p>It&#39;s inevitable. As more and more features are added to an application, the code base grows. The build has more to do: more compiling, more tests and metrics to run, more reports to generate. We&#39;ve done numerous things to keep the build time down. In this entry, I&#39;d like to describe one of them: running standard JUnit tests concurrently.</p><p>A colleague of mine came up with this idea.&nbsp;He first did a preliminary search to see if anything already existed.&nbsp; Pretty much everything he found was intrusive, e.g., requiring extending a specialized TestCase.&nbsp; He then&nbsp;attempted&nbsp;to combine <a href="http://ant.apache.org/manual/index.html">Ant&#39;s Parallel and JUnit tasks</a>. That is, he could simply nest N number of JUnit tasks inside a Parallel task. The problem here was coming up with a good way to divide the tests up into equal parts beforehand. My colleague quickly scrapped this idea in favor of a custom Ant task that wrapped the JUnit task.</p><p>The thought was to leverage the JUnit task as much as possible, but fronting it with the ability to run tests in parallel. The conceptual design looks like this:</p><p><img src="http://files.blog-city.com/files/J06/154001/p/f/paralleljunit.png" alt="Conceptual design" width="314" height="74" /></p><p>There are N number of TestExecutors. A TestExecutor runs in a single JVM. Thus, there are N JVMs. Say we have a dedicated, 4 processor integration machine running builds. We may choose to configure our custom task with 5 TestExecutors (we&#39;ll add one&nbsp;assuming&nbsp;we&#39;re not 100% compute bound). Note: if you&#39;re familiar with the JUnit task, you may be wondering how its fork/forkmode attributes fit in. The answer is that they are&nbsp;eliminated in favor of this jvm-count attribute.</p><p>There&#39;s a single TestProvider. His job is to gather all the tests and hand them out one at a time to whichever TestExecutor is ready. A simple protocol exists to let a TestExecutor tell the TestProvider that he&#39;s done and ready for another test.&nbsp; This should maximize parallelism.</p><p>The biggest negative with this approach is that since all tests run in a fixed number of JVMs,&nbsp;there&#39;s some loss of isolation here. Class level/global state set from a previous test could affect later tests. We&#39;re willing to trade this for increased performance.</p><p>The other possible downside is the use of a non-standard Ant task.</p><p>Using this approach&nbsp;we&#39;ve successfully reduced our build time to usable levels.</p><p>&nbsp;</p>]]></description><category>testing</category><category>tools</category><category>build</category><category>ci</category></item><item><title>The Continuous Integration Build Game</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/ci_build_game.htm</guid><link>http://clintshank.javadevelopersjournal.com/ci_build_game.htm</link><pubDate>Fri, 14 Sep 2007 21:46:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=ci%5Fbuild%5Fgame</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>I was reading <a href="http://alistair.cockburn.us/">Alistair Cockburn</a>&#39;s <a href="http://tinyurl.com/famze">Agile Software Development</a> book the other night.  In it, he described a game developed by Darin Cummins to reinforce good development practices.  The game is described <a href="http://www.ddj.com/184401568">here</a>.  This inspired me to create a fun game for continuous integration builds.</p><p>As I described in a previous <a href="/afterbuildbreaks.htm">blog entry</a>, I&#39;ve had problems in the past with people breaking the build.  To help, I&#39;ve used techniques like the rotating Build Nazi and the put a dollar in the broken build jar, but these are all negative focused.  How about something that rewards developers that don&#39;t break the build?  How about rewarding developers for following the best practice of breaking their work into smaller chunks and <a href="http://www.extremeprogramming.org/rules/integrateoften.html">checking in early and often</a>?</p><p>So I&#39;m thinking of a game where a developer gets, say 1 point for getting his name on a successful build.  The number of files checked in is ignored.  We want to discourage big check-ins, so you get more points for smaller grained check-ins since your name will show up on more successful builds.  And on the other side, you get points taken away when you break the build.  Now, we want to keep things simple, so we could probably stop right here, but I&#39;m thinking that some failures are worse than others.  So maybe we have something like:</p><table border="0" align="left" style="width: 455px; height: 149px"><tbody><tr><th>&nbsp;Description</th><th>Reward Points&nbsp;</th></tr><tr><td>&nbsp;Check-in and build passes<br /></td><td>1&nbsp;</td></tr><tr><td>&nbsp;One or more unit tests failed<br /></td><td>-10&nbsp;</td></tr><tr><td>&nbsp;Compiler error (come on now)<br /></td><td>-20&nbsp;</td></tr><tr><td>&nbsp;Big check-in caused build to remain in a broken state for hours<br /></td><td>-40&nbsp;</td></tr></tbody></table><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p>It&#39;s a game, so we need something for the winner.  Bragging rights is too lame, so maybe lunch on the team, or some kind of trophy kept on the winner&#39;s desk to remind everybody of his champion status.</p><p>Now, there are some negatives.  Perhaps not everybody would want to play.  Particularly, notorious build breakers wouldn&#39;t want everybody (specifically management) to see their poor results.  In that case, I suppose we could only publicly display the leaders, or top half, but that wouldn&#39;t be as fun.</p><p>People could easily cheat too.  Maybe, write a cron job that every hour checks out a file, changes a comment and checks back in.  We&#39;d have to look out for that kind of thing.</p><p>What about the analysis time required to keep score?  I could easily see how a post processing ant task could be developed to update the points for developers on a successful build.  But for a failure, I think you&#39;d need human analysis.  That&#39;s a negative because it requires time, so the job could be rotated.  On the plus side, what I&#39;ve noticed is that analyzing why the build failed brings awareness to issues.  Issues like some people needing training, or a test requiring change because it&#39;s non-deterministic, or a hole in the <a href="/buildscmpart3.htm">pre-check-in process</a>  used to ensure a successful build.</p><p>To keep the game fresh and the developers motivated, we&#39;d have to reset the points periodically.  Iteration boundaries seem appropriate here.</p><p>Well, maybe I&#39;ll give it a shot and see what happens...</p>]]></description><category>scm</category><category>ci</category><category>build</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>Groovy or JRuby?</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/groovy_or_jruby.htm</guid><link>http://clintshank.javadevelopersjournal.com/groovy_or_jruby.htm</link><pubDate>Sat, 24 Mar 2007 19:32:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=groovy%5For%5Fjruby</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[Which dynamic programming language should I introduce to a group of relatively young, inexperienced Java developers?  The choice is between <a href="http://groovy.codehaus.org/">Groovy</a>  and <a href="http://jruby.codehaus.org/">JRuby</a>.<p>Ruby and particularly Ruby on Rails has been hot for awhile now.  Ruby in the enterprise is becoming more accepted.  As Martin Fowler pointed out nearly a year ago in this <a href="http://www.martinfowler.com/bliki/EvaluatingRuby.html">blog entry</a> , some top minds in our field including Bruce Tate, Justin Gehtland, and Stuart Halloway have moved <a href="http://www.oreilly.com/catalog/beyondjava/">Beyond Java</a> .  Even one of my old mentors, <a href="http://gaffney.wsj2.com/">Mike Gaffney</a> , has repeatedly told me to bail on Java.  But I agree with Scott Davis as he points out in this <a href="http://www.nofluffjuststuff.com/s/podcast/18/nfjs-scott-davis-groovy.mp3">podcast</a> , Java is not dead.</p><p>The growing acceptance of Ruby is a strong reason to consider JRuby.  Being able to run Ruby on Rails apps on the JVM is very appealing.  But remember the context of the decision here.  We&#39;re talking about a group of developers whose only development language has been Java, and whose projects for the foreseeable future will run on the Java platform.  Groovy wins in this context.</p><p>There are lots of reasons to get excited about Groovy.  It too runs on the ever-improving JVM.  In fact, it was the first scripting language officially approved by Sun to run on the JVM.  It can be compiled to byte code or run in script form.  The interoperability is fantastic.  Developers can still use Java, its tools and familiar libraries such as <a href="http://www.springframework.org/">Spring</a>  and <a href="http://www.hibernate.org/">Hibernate</a> , where appropriate, and mix in Groovy, where that is more appropriate.</p><p>But what really makes this decision easy is the similarity in language syntax.  You can take a snippet of Java code, drop it into a Groovy file, and it will nearly work.  Then, you can take that snippet and start making use of Groovy language improvements such as closures to make the code more readable and <a href="/coding_by_intention.htm">intention revealing</a> .</p><p>So the decision is easy here.  Take the seamless step forward and introduce Groovy.</p>]]></description><category>groovy</category><category>ruby</category></item><item><title>Bad PMD Rules</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/bad_pmd_rules.htm</guid><link>http://clintshank.javadevelopersjournal.com/bad_pmd_rules.htm</link><pubDate>Fri, 09 Mar 2007 05:00:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=bad%5Fpmd%5Frules</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p><a href="http://pmd.sourceforge.net/">PMD</a>  is an excellent tool for finding potential bugs and improving code quality, but it can generate a lot of false positives.  Here&#39;s my list of the top 10 rules I turn off immediately, in alphabetical order, with a short comment explaining why.  Descriptions for the rules can be found <a href="http://pmd.sourceforge.net/rules/index.html">here</a>.</p><ol><li><strong>AtLeastOneConstructor</strong>: Why?  Code is smaller without an empty, no-args contructor.</li><li><strong>AvoidInstantiatingObjectsInLoops</strong>:  This one just seems to generate too many false positives.  In addition, for short-lived objects, garbage collection is essentially free.</li><li><strong>CallSuperInConstructor</strong>: super() is called implicitly and requiring it just adds more lines of code.</li><li><strong>JUnitAssertionsShouldIncludeMessage</strong>: Most of the methods in Assert already generate good messages.  I do include a message for those that don&#39;t (assertTrue(), assertFalse(), fail()).</li><li><strong>LocalVariableCouldBeFinal</strong>:  final for variables is usually overkill and it adds line length.</li><li><strong>LongVariable</strong>: Clarity rules! </li><li><strong>MethodArgumentCouldBeFinal</strong>: Same as LocalVariableCouldBeFinal.</li><li><strong>OnlyOneReturn</strong>: I think it&#39;s clearer to exit early.  It reduces the amount of things to think about below the exit.</li><li><strong>PositionLiteralsFirstInComparisons</strong>: This really isn&#39;t that bad, but myString.equals(&quot;x&quot;) just reads better than &quot;x&quot;.equals(myString).</li><li><strong>ShortVariable</strong>:  There are just too many cases where it&#39;s acceptable to have short variables in <a href="/smallmethods.htm">small methods</a> .</li></ol><p>&nbsp;These two just missed the cut:</p><ul><li><strong>ShortMethodName</strong>: I try to make my names expressive.  I&#39;ve never seen this rule fire. </li><li><strong>SignatureDeclareThrowsException</strong>:  This is an okay rule, but for JUnit tests, who cares?</li></ul><p>&nbsp;</p><p>&nbsp;</p>]]></description><category>tools</category></item><item><title>The todo Test Category</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/todo_test_category.htm</guid><link>http://clintshank.javadevelopersjournal.com/todo_test_category.htm</link><pubDate>Fri, 26 Jan 2007 14:33:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=todo%5Ftest%5Fcategory</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[Recently, <a href="http://www.elharo.com/">Elliotte Rusty Harold</a>  <a href="http://cafe.elharo.com/testing/go-ahead-break-the-build/">blogged</a>  about committing test cases for bugs to the build cycle before fixing them right away.  He enumerated several good reasons for doing this such as the fix being difficult and time consuming.  His point was that breaking the build (where breaking the build includes passing all the unit tests) is okay in some cases.<p>I disagree with this stance, but I think Harold has a really good idea there, which I&#39;ll get to in a moment.  I think breaking the build does include passing all the unit tests and should be part of the continuous integration process.  I&#39;ve always liked the idea of the tests serving as a safety net when I add new functionality or refactor existing code.  The tests not only specify the desired behavior, but act as a regression suite.</p><p>So what&#39;s the idea?  I first learned of the concept of <a href="http://www.ibm.com/developerworks/java/library/j-cq10316/">test categorization</a>   from Cedric Beust&#39;s <a href="http://testng.org/">TestNG</a>  framework and the writings of disco king <a href="http://thediscoblog.com/">Andrew Glover</a> .  Essentially, the concept is to break tests into groups such as unit, component, and system and run them at different intervals.  Unit tests are run many times a day as code is developed, component tests less frequently, and system tests the least frequently of all.  You can categorize tests in several different ways such as by file naming conventions, placing them in different directories, or using Java annotations.</p><p>Harold brings up a new category - the todo category.  (I was originally thinking the fixme category, but I thought todo could serve more purposes.)  The todo category contains all tests that serve as a reminder of work to do.  They obviously fail or there would be nothing to do.  When it&#39;s finally time, the test moves out of the todo category and into the unit, component, or system category as appropriate.  Although you could have a todo category for each of the original, regression categories (todoUnit, todoComponent, and todoSystem), I think that would be overkill.  Notice that I slipped the word regression into &quot;original categories&quot; above.  I&#39;m advocating that the original categories should pass at all times - they should break the build if they fail (well, at a minimum the unit category).  Once tests get into the regression categories, they never go back to todo.</p><p>The obvious downside of this approach and of test categorization in general is the added complexity.  It&#39;s more work to maintain categories and in this case, move tests into different categories than a simple one category fits all approach.  Also, there&#39;s more work (at least initially) to setup the running of those categories.  As always, I recommend weighing the options and deciding what&#39;s best for your particular situation.  See Glover&#39;s writings for more benefits of test categorization.</p>]]></description></item><item><title>Behavior Driven Development with JUnit 4</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/bdd_junit4.htm</guid><link>http://clintshank.javadevelopersjournal.com/bdd_junit4.htm</link><pubDate>Thu, 14 Dec 2006 22:54:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=bdd%5Fjunit4</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>JUnit 4 makes <a href="http://en.wikipedia.org/wiki/Behavior_driven_development">Behavior Driven Development (BDD)</a>  style testing (or specification) easier.</p><p>Let&#39;s quickly look at an example, the idea stolen from one of <a href="http://www.butunclebob.com/ArticleS.DavidChelimsky.SpecOrganization">David Chelimsky&#39;s blog entries</a>  about specifying the behavior of a stack.  We&#39;re focused here on the specification of an empty stack:</p><pre>// notice the class name specifies the context<br />public class EmptyStack {<p>    private Stack stack = null;<br />    <br />    @Before<br />    public void setUp() {<br />        // set up the context<br />        stack = new Stack();<br />    }</p><p>    <br />    // notice the name focuses on the context<br />    @Test<br />    public void shouldBeEmpty() {<br />        assertTrue(&quot;not empty&quot;, stack.isEmpty());<br />    }</p><p>    <br />    @Test(expected=EmptyStackException.class)<br />    public void shouldComplainOnPeek() {<br />        stack.peek();<br />    }<br />    <br />    <br />    // more specification focused methods<br />}</p></pre><p>The point here is that you can get many of the benefits of BDD (a focus on specification rather than testing) using the familiar JUnit framework.</p><p>Now, if you&#39;re a hardcore BDD&#39;er, then you might complain that you still have to use a test-centric vocabulary.  You still need those Test annotations and method calls like assertEquals rather than <a href="http://www.daveastels.com/">Dave Astels&#39;</a>  preferred shouldEquals calls.</p><p>Also, from the legacy side of the fence, you lose the convention of method names starting with testSomething and class names ending with Test.  It&#39;s sometimes hard to let go of that if you&#39;ve been writing tests for a long time and it&#39;s super clear to spot those test methods and test classes if you&#39;re following a naming convention.  Furthermore, Ruby on Rails has taught us that convention is a good thing.  The test method naming convention doesn&#39;t really bother me so much.  The @Test annotation makes things clear enough and shouldSomething really gets us focused on specification.  However, I haven&#39;t let go of ending the class name with Test.  Maybe it&#39;s more because Ant can pick those tests up easier if there&#39;s a standard naming convention.</p><p>The last negative I can think of is that of consistency.  Having a mix of old style test centric tests and BDD style tests could bother some.</p><p>So, let&#39;s be honest.  What am I really doing?  Well, I am incorporating more and more BDD into my work.  However, I still shy away from creating new classes.  The BDD style really lends itself to many test classes (contexts) per class under test.  In the case of Stack, as David Chelimsky points out, you&#39;d also need AlmostEmptyStack, AlmostFullStack, and FullStack classes to fully specify the behavior.  I just can&#39;t commit myself to writing all those.  But I am focusing more on the set up of a context and the specification methods of that context.  I just may cheat a little and combine contexts into a single class.  So perhaps in the Stack example, I&#39;d combine the empty and almost empty stack contexts under one test class.  You know, I&#39;d set up an empty Stack in setUp and for the almost empty context, I&#39;d do a little more set up (push something) in the appropriate shouldSomething methods to make it almost empty.</p><p>I also revert back to legacy style testing sometimes.  This is usually when I&#39;m modifying an existing, old style test.  It&#39;s just simpler and faster, and typically the context isn&#39;t set up too well for the BDD style.</p><p>So my advice is to use the right tool for the job.  Use BDD style when that makes things clearer and you want to focus on specification.  Use test centric style when that&#39;s easier.  Try to do a better job of focusing more on specification and less on verification, especially when you&#39;re adding new behavior.</p><p>&nbsp;</p>]]></description></item><item><title>Testing Private Methods</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/testingprivates.htm</guid><link>http://clintshank.javadevelopersjournal.com/testingprivates.htm</link><pubDate>Sat, 18 Nov 2006 15:37:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=testingprivates</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>How should I test my private helper methods?  Well, I used to just expose the method by making it accessible to the unit test (typically by making it package scoped).</p><p>So if I had a method like this:</p> <pre>    private void someHelperMethod() {<br />    } </pre> <p>I&#39;d expose it like this:</p> <pre>    /** Exposed for testing purposes only. */<br />    void someHelperMethod() {<br />    } </pre> <p>I&#39;d laugh at people who used the &lt;code&gt;PrivateAccessor&lt;/code&gt; of the <a href="http://sourceforge.net/projects/junit-addons">JUnit-addons</a>  project or directly used reflection to get the method and do a &lt;code&gt;method.setAccessible(true)&lt;/code&gt;.  I&#39;d think, &quot;What&#39;s the big deal?  Just change the access of the method.  Then, you&#39;ll make things easier for your IDE when you want to do a method rename refactoring or just find references to this method.&quot;</p><p>I&#39;ve recently hopped the fence and I&#39;m now campaigning for the other side.</p><p>Now, before I get into the why, I should point out that red flags should have gone up after you read the first question of this entry.  Testing private methods?  Why would you do that?  Believe me, as I&#39;ve mentioned <a href="/testbreaks.htm">here</a> , I think unit tests should focus on black box testing as much as is practically possible and therefore, you shouldn&#39;t be testing private methods.  I&#39;m also familiar with the argument, &quot;You could perhaps move those private methods to a helper class and therefore, they wouldn&#39;t be private.&quot;  But I still believe there are cases where it makes sense to (have and) test private methods.  And in this blog, I&#39;m talking about these exceptional cases.</p><p>So what are some exceptional cases?  Think of a high level method specifying the steps of an algorithm or a method on a mediator/controller-like class collaborating with multiple objects.  You did break that method up into smaller, easier to understand, more communicative methods as described <a href="/smallmethods.htm">here</a> , didn&#39;t you?  So which is easier: setting up the object under test and its collaborating objects (the fixture) and calling the private helper method directly; or setting up the fixture and calling the public, higher level method that does some processing before calling the private helper method?  In the latter case, you surely had to do more set up to navigate down to the same entry point in the private method.  If you didn&#39;t or it wasn&#39;t much more work, then I&#39;m talking about a different context.</p><p>All right, so why the switch?  Well, first off, the real intent is to make them private.  Private leaves no doubt that the method isn&#39;t meant to be used outside the class.</p><p>Along with that is encapsulation.  As multiprocessor systems become more mainstream, exploiting concurrency by multi-threading adds complexity to software development.  Encapsulating as much as possible can only simplify reasoning about thread safety.</p><p>One final reason is that making things private helps static analysis tools like <a href="http://findbugs.sourceforge.net/">FindBugs</a>  and <a href="http://pmd.sourceforge.net/">PMD</a>  better identify dead code that can be eliminated.  &quot;Hey, this method is private and it&#39;s not being called!&quot;  Keeping the code base lean and clean is a key to maintainability.</p><p>The biggest downside, as I&#39;ve hinted at above, is doing things like renaming/changing the signature of the method, or just finding references to it.  The IDE won&#39;t make the appropriate changes to the test or find the reference in the test.  But you&#39;ll find this pretty quickly when you run the test and it fails.  Hint: Maybe you should have changed the test first anyway.</p><p>So join me on this side and remember that testing privates is better meant for special cases.</p><p>&nbsp;</p>]]></description></item><item><title>Comments on The Danger of Mock Objects</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/commentsonmocks.htm</guid><link>http://clintshank.javadevelopersjournal.com/commentsonmocks.htm</link><pubDate>Sun, 24 Sep 2006 16:13:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=commentsonmocks</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Rarely do I disagree with Uncle Bob.&nbsp; I&rsquo;ve learned a lot from reading his writings over the years.&nbsp; He recently blogged about <a href="http://www.butunclebob.com/ArticleS.UncleBob.TheDangerOfMockObjects">mock objects</a>  in response to a <a href="http://beust.com/weblog/archives/000410.html">blog</a>  from Cedric Beust.&nbsp; Check it out, read my comments on Uncle Bob&rsquo;s blog, and decide for yourself.</p><p>&nbsp;</p>]]></description></item><item><title>Break, Then Leave and Pre-Check In Checklist</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/buildscmpart3.htm</guid><link>http://clintshank.javadevelopersjournal.com/buildscmpart3.htm</link><pubDate>Sat, 16 Sep 2006 19:11:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=buildscmpart3</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>My build/SCM blog series (see <a href="/reservingfiles.htm">part 1</a>  and <a href="/afterbuildbreaks.htm">part 2</a>) ends with a look at one of the most annoying things a member can do to his team and a checklist to follow for reducing the chances of breaking a build.</p><p>So what can really irritate the rest of team?  How about checking in a bunch of changes that break the build and then leaving for the day?  This is bad enough for small teams, but consider bigger, distributed teams developing complex applications.  You could have team members who start their day after you&#39;ve left.  If the team follows the rule of not checking in on a broken build, what&#39;s the team supposed to do?  Well, to continue progress, somebody else has to step in and fix the build.  This can really slow a team down.</p><p>A good practice is to wait for a successful build after your last check in before leaving.  After all, you know the most about the changes that would have broken the build.  This practice implies some prerequisites: a continuous integration system that runs often and builds that run quickly.</p><p>Now that I&#39;ve ranted enough, what can you do to reduce the chances of breaking a build in the first place?  Listed below are steps to follow.  It starts at the point where you&#39;re ready to check in.  Essentially, you mimic the continuous integration system on your development workstation.</p><ol><li>Update your view so you have the latest versions of all the files.</li><li>If you use configuration management software that allows hijacking and reserving files (like Rational ClearCase), now is the time to &quot;unhijack&quot; and reserve existing files with changes.  By existing files, I mean files the CM software knows about (not new).  You only need to reserve files if your team follows that practice.  If nobody on the team reserves files, then skip this part, but it&#39;s important to reserve at this point if your team follows this practice to ensure all of your changes can get checked in.</li><li>If necessary, merge any existing files that have been updated and checked in by others since you checked out.  You want your files to represent what will be checked in.  Now, your files will contain your changes merged with the most recently checked in versions.</li><li>Make note of any new files that need to be added to source control and any deleted files that must be removed from source control.  Forgetting to do this can cause a build failure.</li><li>Run the application to make sure your changes function and integrate well.</li><li>Do a clean build, compile and run all the unit tests.  Consider a single ant target that does this for you.</li><li>Check in.  Don&#39;t forget those new and deleted files!</li></ol><p>Do I follow all of these steps on every check in?  No way.  That wouldn&#39;t be practical.  You need to consider the size and impact of your changes.  The bigger they are, the more rigorous you should be.  If I made just a small change, I would probably just make sure the code compiled and unit tests for that change passed.</p><p>Well, that&#39;s it.  Hope you enjoyed.</p><p>&nbsp;</p>]]></description></item><item><title>After the Build Breaks</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/afterbuildbreaks.htm</guid><link>http://clintshank.javadevelopersjournal.com/afterbuildbreaks.htm</link><pubDate>Mon, 28 Aug 2006 13:30:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=afterbuildbreaks</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>The second part of the build/SCM blog series (see <a href="http://clintshank.javadevelopersjournal.com/reservingfiles.htm">part 1</a>) deals with what happens when a build breaks.  This happens, hopefully infrequently, but it happens.  Getting the build back on track should be one of the highest priorities - your build box teammate is down and you need to get him back on his feet.</p>
<p><strong>Ideally</strong>, what should happen is the following:</p>
<ol>
    <li>Notification of a build failure is distributed by e-mail to the team.  This is part of the publishing functionality of CI systems like <a href="http://cruisecontrol.sourceforge.net/">CruiseControl</a>.</li>
    <li>Particularly, whoever checked in since the last successful build analyzes the results.</li>
    <li>The person who broke the build mans up and replies to all, &ldquo;This is me.  I&rsquo;m on it.&rdquo;</li>
    <li> Nobody checks in until the build is fixed unless the check in is for the purpose of fixing the build.</li>
    <li> Somebody fixes the build, obtaining any help necessary.</li>
    <li> (Optional) Once the build is believed to be fixed, the person from step 3 sends an e-mail saying the build should be fixed.</li>
</ol>
<p>Let&rsquo;s talk more about step 3.  I know it could be embarrassing to break the build.  The step is not to call anyone out or lay blame.  The point is to communicate to the team, who may be large and distributed, that somebody is taking responsibility for fixing the build.  Several others may be analyzing and trying to fix the problem and this communication is to reduce that wasted effort.  I have been on teams where the build has been broken for hours and nobody knows if anybody is doing anything about it.</p>
<p>Sometimes nobody is doing anything about it.  If this is a recurring problem, I recommend the use of a Build Nazi (in honor of the <a href="http://en.wikipedia.org/wiki/Soup_Nazi">Seinfeld Soup Nazi</a>).  The job of the Build Nazi is to make sure somebody is responsible for fixing a broken build.  The job is not to fix the build (unless help is needed).  The Build Nazi job is not a fun one and therefore should be rotated.  It is also a controversial role in an agile environment where the practice of collective code ownership is being followed.  Ideally, the team is following the steps above and a Build Nazi is totally unnecessary.  I&rsquo;ve found I&rsquo;ve had to resort to the role for short term periods in times of chaos when the build is breaking more than it is succeeding.   Once things get back on track, the Build Nazi role typically becomes dormant.</p>
<p>The last step I&rsquo;d like to elaborate on is step 4.  One of the worst things to do is check in a bunch of changes that don&rsquo;t have anything to do with fixing the build.  Checking in causes the CI system to start another build that will result in another failure.  Piling on check ins during a broken build prolongs the broken state of the build and therefore the feedback cycle that is all important in agile development.  Another risk is that the fix necessary to correct the original problem must be applied to the check ins that occurred after the first failure, further prolonging the broken state.</p>
<p>I plan on finishing this series next time.  Stay tuned.</p>
<p><br />
</p>]]></description></item><item><title>Anti-Practice: Reserving Files</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/reservingfiles.htm</guid><link>http://clintshank.javadevelopersjournal.com/reservingfiles.htm</link><pubDate>Sun, 20 Aug 2006 18:33:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=reservingfiles</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Here is the first blog in a series discussing some obsolete practices and just plain annoyances regarding builds and source code management.  The context is an agile development environment following the best practices of <a href="http://en.wikipedia.org/wiki/Continuous_Integration">continuous integration</a> (CI) and <a href="http://en.wikipedia.org/wiki/Extreme_Programming_Practices#Collective_code_ownership">collective code ownership</a>.  The team is of medium to large size, possibly distributed, and working different hours, possibly in different time zones.</p>
<p>The first obsolete practice is reserving (locking) a file by default when checking out the file.  (I&rsquo;m using ClearCase terms here).  This is like <a href="http://en.wikipedia.org/wiki/Concurrency_control">pessimistic locking</a> in the database world.  The thought is, &ldquo;I&rsquo;m going to reserve this so that no one else will affect me.  I&rsquo;ll make my changes, then check in.  If anybody else wants to modify the same file, they&rsquo;ll have to wait for me to finish, then deal with merging in their changes.&rdquo;  That doesn&rsquo;t sound like collective code ownership to me.  Sharing the code base means sometimes having to deal with merge issues.</p>
<p>Reserving files prohibits others who are ready to check in.  In the worst case, suppose a person with reserved files leaves for the day (or for vacation).  Others are likely working different hours, so what do they do?  They try to get in touch with you to see what&rsquo;s up.  They can&rsquo;t get a hold of you, but they are ready to check in and move on.  So after some time not hearing from you, do they unreserve the files?  In some stricter environments, what if they don&rsquo;t have rights?  What if they can&rsquo;t get in touch with the select few that have rights to unreserve files?  (By the way, if you do unreserve a file, make sure you tell the person who reserved it that you did that.)  The point is reserving files slows down the team.</p>
<p>There are of course exceptions.  An important change or a change that has a big impact to the system might merit an early reserve on a check out.  In this blog, I&rsquo;m talking about reserving files <em>by default</em>.</p>
<p>The biggest positive of reserving early is finding out that somebody else is working on the same file.  For example, I try to check out a file and reserve it right away and find that I can&rsquo;t because Joe&rsquo;s got the file reserved.  Depending on the circumstances, I may want to know exactly what Joe&rsquo;s doing.  I&rsquo;m not familiar with another way of getting this notification as easily without getting spammed by unwanted notifications.  In other words, I might want to know, upon check out of a file, whom else has the file checked out.&nbsp; For me, this advantage doesn't outweigh the disadvantages mentioned above.<br />
</p>
<p>Next time I&rsquo;ll talk about an annoyance or two that occurs when a build breaks.</p>
<p><br />
</p>]]></description></item><item><title>Checklist for Finding Test Cases</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/testcasechecklist.htm</guid><link>http://clintshank.javadevelopersjournal.com/testcasechecklist.htm</link><pubDate>Sun, 04 Jun 2006 15:19:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=testcasechecklist</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Suppose I'm focused on specifying the behavior of a particular method.  How do I know if I've specified everything?  I'd like to share a checklist of things I think about to help accomplish this.  The goal is to thoroughly specify the behavior of the method by building up a collection of tests following <a href="http://en.wikipedia.org/wiki/Test_driven_development">test-driven development</a>.</p>
<p>I'm going to base my example on <a href="http://www.springframework.org/">Spring</a>'s <font face="Courier New">BeanFactory</font> interface.  Suppose I'm developing a <font face="Courier New">Map</font> backed <font face="Courier New">BeanFactory</font> and I am currently focused on implementing the following method of the <font face="Courier New">BeanFactory</font> interface:</p>
<pre>Object getBean(String beanName) throws BeansException</pre>
<p>Let's call the class I'm developing <font face="Courier New">MapBackedBeanFactory</font>.  When <font face="Courier New">getBean()</font> is called, the implementation will look up the bean in its <font face="Courier New">beanMap</font> field.</p>
<p>When I think about test cases, I think about:</p>
<ol>
    <li>The state of the object under test (each field), i.e., the fixture.  In the example, this would be the <font face="Courier New">beanMap</font>.<br /></li>
    <li>The state of the parameters of the method I'm calling on the object under test.  In the example, there's only one: the <font face="Courier New">beanName</font>.</li>
</ol>
<p>That was pretty obvious.  Who doesn't think about these things?  But what is the checklist?  The checklist consists of thinking about the following for <strong>each</strong> of the above:</p>
<ol>
    <li><u>A good value</u>.  This will execute the normal flow and is the most obvious test.  For <font face="Courier New">beanMap</font>, this means the <font face="Courier New">beanMap</font> will have a good bean mapping.  For the <font face="Courier New">beanName</font>, a good value is a name that will be found in the <font face="Courier New">beanMap</font>.  There may be multiple good values, not really in this case, but think about the classic bowling game.  You'd want tests for a non-mark frame, a spare, and a strike.  I'll also consider multiple good values for things like collections, maps, and arrays.  That is, maybe I'm dealing with a&nbsp; <font face="Courier New">List</font> and I need a <font face="Courier New">List</font> of two good things.  However, I find that most times, one good value in the collection, map, or array is sufficient.&nbsp; This is because I write the iteration code for the single case and a multiple collection test case wouldn't make me write any new code.&nbsp; If I find I need multiple good values, I'll start with the simple cases and work towards the harder.</li>
    <li><u>A negative case</u>.  In #1, I set up the fixture and parameters to get a good result.&nbsp; Now, I want to think of the negative side.&nbsp; So I found beans in #1, but now I want to <strong>not</strong> find a bean.&nbsp; Pass in an unknown <font face="Courier New">beanName</font>.</li>
    <li><u>A null value</u>.  What if the <font face="Courier New">beanMap</font> were null?  That's probably not realistic, so I'm going to skip that.  What if the <font face="Courier New">beanName</font> were null?  That's possible and according to the <font face="Courier New">BeanFactory</font> JavaDoc, it looks like the contract specifies to throw a <font face="Courier New">NoSuchBeanDefinitionException</font>.  I better write that test.  Many times, if you don't handle null, you'll get a <font face="Courier New">NullPointerException</font> and that might be acceptable.  In those cases, I wouldn't write a test (since it wouldn't require any code).</li>
    <li><u>An empty value</u>.  The <font face="Courier New">beanMap</font> could have no mappings or the <font face="Courier New">beanName</font> could be <font face="Courier New">&quot;&quot;</font>.  I think #2 covered us here, so no test is required.</li>
    <li><u>An invalid value</u>.  What if <font face="Courier New">beanMap</font> were invalid?  What if it were a <font face="Courier New">Map</font> of <font face="Courier New">Integer</font>s to bean <font face="Courier New">Object</font>s?  I'm going to assume this is unrealistic in this case.  We would have handled such a situation when the map was loaded.&nbsp; What if the <font face="Courier New">beanName</font> were <font face="Courier New">&quot;invalid&quot;</font>?  Well, we covered that in #2.</li>
    <li><u>An exceptional case</u>.  I'm pretty much talking about handling exceptions here.  Maybe we need to write a test case to see if we handle an exception properly.  The example doesn't have such a case, but suppose the method under test were doing some I/O.  Maybe we'd need to write a test to see if we handled that properly.  In all honesty, even though I think about this, I don't usually write a test to handle exceptions.  I won't get 100% test coverage, but I usually ignore writing the test because checked exceptions force me to write the necessary handling code.</li>
</ol>
<p>That's a lot of stuff to think about for each object field/parameter.  That's the biggest negative - thinking about all those things, all the possibilities, all the time it takes.  Many times, as you saw in the example, most of those things just aren't realistic.</p>
<p>  Sometimes I'll take a different approach.  I'll start with the simple, good case.  I'll write the test and get it to pass by writing the minimal code to do so.&nbsp; In the example, I'd have:</p>
<pre>return beanMap.get(beanName);</pre>
<p>  Then, I'll look at the method I just wrote <strong>word by word</strong> (or maybe token by token).&nbsp; At each word, I'll think about special cases (things like in the checklist) and jot down test cases.  Then, I'll go back to the test, write one of the jotted-down tests, get it to pass, and continue until I'm done.  It's a different perspective that goes a little faster at the risk of not quite catching everything as the first approach.&nbsp; I like this second approach and have been doing it more and more lately.<br /></p>
<p><br /></p>]]></description></item><item><title>How to Pick a Conference Session</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/pickconferencesession.htm</guid><link>http://clintshank.javadevelopersjournal.com/pickconferencesession.htm</link><pubDate>Sun, 14 May 2006 22:32:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=pickconferencesession</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>I just recently attended a conference and had to make some tough choices among some concurrent sessions and tutorials.&nbsp; To help, I came up with an objective scoring system.&nbsp; The system consists of evaluating each session against three categories.&nbsp; Each category is given a score from 1 to 3.&nbsp; Then, the total is tallied to give each session a final score ranging from 3 to 9.&nbsp; The session with the highest score wins.</p>
<p>Quickly, the three categories are:</p>
<ol>
    <li>Current knowledge.&nbsp; How much do I currently know about this?</li>
    <li>Needs.&nbsp; Do I use this now or will I use this in the near future?</li>
    <li>Wants and other miscellaneous factors.&nbsp; How much do I want to go to this?</li>
</ol>
<p>The first category addresses breadth of knowledge.&nbsp; The pragmatic programmers would call this diversifying your <a href="http://www.pragmaticprogrammer.com/talks/HowToKeepYourJob/HowToKeepYourJob.htm">knowledge portfolio</a>.&nbsp; In Scott Ambler terms, attending a session on a topic you don&rsquo;t know much about might help you on your way to becoming a <a href="http://www.agilemodeling.com/essays/generalizingSpecialists.htm">generalizing specialist</a>.&nbsp; It&rsquo;s the factor that addresses learning something new.&nbsp; Give yourself a score of 3 if you know little or nothing of the topic.&nbsp; Give a score of 1 if you&rsquo;re an expert or really proficient.&nbsp; For example, suppose you&rsquo;re a Java guy and don&rsquo;t know much about .NET.&nbsp; Give .NET related classes a score a 3.</p>
<p>The second category addresses your immediate and near term needs.&nbsp; Do you use this now?&nbsp; Will you use this in the next six months?&nbsp; This category addresses the depth factor.&nbsp; Attending such a session may shed some light on something you never knew about something you currently use.&nbsp; You may learn how to use a technology better, some best practices, or some tips and tricks.&nbsp; Give a score of 3 if this is something you use or will use soon.&nbsp; Give it a 1 if you don&rsquo;t see it in your near term future.&nbsp; Give it a 2 if you&rsquo;re not sure.</p>
<p>The last category addresses everything else.&nbsp; How much do you want to go?&nbsp; How much do you want to learn this technology?&nbsp; Maybe it&rsquo;s AJAX or Ruby on Rails and you give it a score of 3 because you really want to learn that hot technology.&nbsp; Maybe Uncle Bob is speaking and you really want to go see him perform.&nbsp; Score it a 3.&nbsp; Or maybe you&rsquo;ll give the category a score of 1 because you think you won&rsquo;t get much out of it.</p>
<p>Add the scores of the three categories to come up with a score for the session.&nbsp; Then pick the session with the highest score for that time slot.&nbsp; What if there&rsquo;s a tie?&nbsp; Well, you could look at the categories and pick the session with the highest score for the category most important to you.&nbsp; I think conference sessions in general are better at the breadth category.&nbsp; How much can you really get out of going to a 90 minute session anyway?&nbsp; Longer tutorials are better at depth.&nbsp; Consider that for helping to break a tie.</p>
<p>What I found is that many times the first two categories cancel each other out.&nbsp; Logically, if you don&rsquo;t know much about something (score 3), then you must not be using it and may not need too in the near term (score 1).&nbsp; On the flip side, if you know a lot about something (score 1), it&rsquo;s probably because you&rsquo;re using it (score 3).&nbsp; However, what&rsquo;s interesting is when you don&rsquo;t know anything about a technology and you&rsquo;re going to use it real soon.&nbsp; That&rsquo;s 6 points right there.</p>
<p>The other negative is that scoring sessions is time consuming and we programmers are notoriously lazy.&nbsp; However, learning is a career investment and investments should be carefully chosen.</p>
<p>I hope this scoring system helps you.&nbsp; I know I was pretty happy with the results.</p>
<p>&nbsp;</p>]]></description></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>Test Smell: Test Breaks After Good Refactoring</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/testbreaks.htm</guid><link>http://clintshank.javadevelopersjournal.com/testbreaks.htm</link><pubDate>Fri, 17 Mar 2006 21:53:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=testbreaks</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Goal: Write a thorough unit test that doesn&rsquo;t require any changes after mercilessly refactoring the object it&rsquo;s testing.</p>
<p>I&rsquo;ve been noticing that I sometimes feel a need to go back and modify my test to be more in line with the object it&rsquo;s testing.  And I&rsquo;m not alone.  David Chelimsky recently wrote a related <a href="http://butunclebob.com/ArticleS.DavidChelimsky.KeepingInfectionInCheck">blog</a>.  That blog, in the context of my goal, focuses more on changing tests because they start drifting away from the code they&rsquo;re testing.</p>
<p>In this blog, I want to talk about changes required because the tests break as a result of good refactoring.  This isn&rsquo;t something that occurs often, but it does happen, and I think it&rsquo;s a code smell.  One of the main advantages of having a test suite is that you can refactor to make the code better or try a different algorithm without worrying whether the final result broke existing functionality.  When the tests break as a result of correct refactoring, I lose that safety net kind of feeling.</p>
<p>So what does it mean when a test breaks as a result of good refactoring?  Well, what jumps out is that the test is too coupled to the main object it&rsquo;s testing.  However, it is a unit test and unit tests are traditionally white box tests and white box tests imply knowledge of the code and that implies coupling.</p>
<p>What about a black box approach to unit testing to reduce coupling?  Elliotte Rusty Harold recently posted a comment on one of his blogs <a href="http://cafe.elharo.com/java/experimental-programming/">Experimental Programming</a>, &ldquo;The class is a black box which is accessed solely through its public interface. The internal details are deliberately opaque, and thus can be changed as necessary to improve performance or other desirable characteristics without breaking client code.&rdquo;<br /> </p>
<p>Yeah, that&rsquo;s what I&rsquo;m talking about, but I think a total black box approach would be too coarse grained, particularly for ensuring 100% test coverage.  Specifically, I&rsquo;m thinking that touching every conditional statement would require a lot of black box test code.  I think the first tip then is to find a balance between black box and white box testing; the sub-goal being to find the appropriate coupling to get 100% coverage with the least amount of test code.  I&rsquo;m trying to keep this in mind when I write tests.</p>
<p>Another technique to help achieve the goal is to shy away from mock objects, particularly strict mock objects.  Martin Fowler wrote an article called &ldquo;<a href="http://www.martinfowler.com/articles/mocksArentStubs.html">Mocks Aren&rsquo;t Stubs</a>&rdquo;.  In it, he describes the difference between mock objects and stubs.  He also describes two styles of testing: state-based and interaction-based.  Interaction-based testing uses lots of mocks, which really couples tests to the implementation details.  This is not what I want if I want to achieve my goal.  So I prefer the state-based approach Martin talks about.</p>
<p>Now, having said that, I do use mocks in certain situations.  They&rsquo;re good at making sure your object made a call on a secondary object:</p>
<pre>   public void testInitRegisters() {<br />&nbsp;&nbsp;&nbsp;   // setup a mock object that expects a register call<br /> &nbsp;&nbsp;   // and inject it into the object under test<br />&nbsp;&nbsp;&nbsp;   objectUnderTest.init();<br />&nbsp;&nbsp;&nbsp;   // verify the mock<br />   }<br /></pre>
<p>Typically, I find that I use mock objects when I&rsquo;m testing <font face="Courier New">void</font> methods, just like the <font face="Courier New">init()</font> method above.  In fact, thinking more about it, it might actually be when the method I need to call on the object I&rsquo;m mocking is <font face="Courier New">void</font>, just like <font face="Courier New">register()</font> method above.  I&rsquo;ll have to pay more attention, but that seems to make sense.  The point is to use mock objects only when they are more practical than the state-based approach, preferring the state-based approach otherwise to reduce test coupling.</p>
<p>Stubs are great for tests whose primary object calls methods that return values from secondary objects.  I use mock libraries to create stubs, particularly for Interfaces and expensive-to-create classes, since it&rsquo;s so easy to do so.  I reduce test coupling by creating lenient stub objects that either ignore unexpected method calls or return empty values (<font face="Courier New">0</font>, <font face="Courier New">null</font>, <font face="Courier New">false</font>) for unexpected method calls.  In <a href="http://www.easymock.org/">EasyMock</a> terms, I&rsquo;m talking about nice controls.</p>
<p>I also use the <a href="http://www.xpuniverse.com/2001/pdfs/Testing03.pdf">Object Mother</a> pattern as a factory to create the stub objects.  This is so that the stub creation code can be shared among many test classes.  I pass the values I want returned into object mother.  The object mother creates the stub object with those values.  In this way, the test has all the knowledge of the canned results.  Then I use a state-based approach to verify everything.  Here&rsquo;s a quick example, putting this all together:</p>
<pre>   private Order order = new Order();<br /></pre>
<pre>   public void testGetTotal() {<br />&nbsp;     // LineItem is an interface.  LineItemMother uses a<br />     &nbsp;// mock library for creating a stub LineItem<br />&nbsp;     LineItem lineItem = LineItemMother.newItem(3, 2.50);<br />      order.add(lineItem);<br />      assertEquals(7.50, order.getTotal(), 0.001);<br />   }<br /></pre>
<p>&nbsp;</p>]]></description></item><item><title>A Logical Ordering of Import Statements</title><guid isPermaLink="true">http://clintshank.javadevelopersjournal.com/importordering.htm</guid><link>http://clintshank.javadevelopersjournal.com/importordering.htm</link><pubDate>Fri, 03 Mar 2006 22:54:00 GMT</pubDate><comments>http://clintshank.javadevelopersjournal.com/console/comments/popup/?f=importordering</comments><dc:creator>Clint Shank</dc:creator><description><![CDATA[<p>Do you care about the order of your Java import statements?&nbsp; Well, maybe not, but I do.&nbsp; The reason is because I like to do a visual check of my dependencies.&nbsp; According to the <a href="http://www.objectmentor.com/resources/articles/granularity.pdf">Acyclic Dependencies Principle</a>, there should be no cycles in packages.&nbsp; Robert Martin wrote <a href="http://www.butunclebob.com/ArticleS.UncleBob.JdependFixture">here</a>, &quot;Remember that the prime motivation for using Object Oriented Design is to manage module dependencies.&quot;&nbsp; One way I check my dependencies is by scanning the import statements of a class or interface to make sure it depends on other, appropriate classes and interfaces.</p>
<p>The rule I use is that you can go up a package hierarchy and over to the right, but you can&rsquo;t go down or to the left.&nbsp; (Props go to <a href="http://gaffney.wsj2.com/">Michael Gaffney</a> for working with me to come up with this rule years ago).&nbsp; Over to the right?&nbsp; I&rsquo;m working in the context of a layered architecture and when I say &ldquo;over to the right,&rdquo; I&rsquo;m talking about something like this:</p>
<pre>   presentation -&gt; business -&gt; persistence -&gt; general utilities</pre>
<p>So starting on the left, dependencies flow to the right.&nbsp; You wouldn't want to go back to the left.&nbsp; That would introduce a cycle.&nbsp; Also, within a layer, you could go up the package hierarchy, but you wouldn't want to go down.</p>
<p>Here&rsquo;s an example.&nbsp; Suppose I&rsquo;m developing a web application and I&rsquo;m working on a class in the presentation layer.&nbsp; I might have something like (contrived):</p>
<pre>   package com.mycompany.myapp.web.struts;</pre>
<pre>   import java.util.List;<br />   import javax.servlet.http.HttpServletRequest;<br />   import javax.servlet.http.HttpServletResponse;<br />   import org.apache.commons.beanutils.PropertyUtils;<br />   import org.apache.struts.action.ActionForm;<br />   import org.apache.struts.action.ActionForward;<br />   import org.apache.struts.action.ActionMapping;</pre>
<pre>   import com.mycompany.myapp.utils.SomeUtil;<br />   import com.mycompany.myapp.domain.SomeDomainObject;<br />   import com.mycompany.myapp.domain.SomeOtherDomainObject;<br />   import com.mycompany.myapp.web.SomethingHigher;<br />   import com.mycompany.myapp.web.utils.SomethingToTheRightWithinModule;</pre>
<p>Now, ideally, I&rsquo;d like to list those imports in the exact opposite order.&nbsp; That way, I could start at the package statement and look down and make sure the imports flow in an acceptable, directed acyclic graph kind of order, following the rule above.&nbsp; In fact, I used to list them in this order, but everybody else lists them in an order more like the above, and so, I accepted defeat and now follow suit.&nbsp; I just start at the bottom and look up.</p>
<p>I only care about ordering among packages here.&nbsp; I don&rsquo;t try to list the imports in dependency order among classes at the same package level.&nbsp; That would be crazy.&nbsp; However, I am strict within the layer of the class I&rsquo;m working with.&nbsp; In the example, that would be the web layer.&nbsp; I&rsquo;m looking at a class in <font face="Courier New">...web.struts</font> and I want to make sure that I&rsquo;m going to the right first, then up, all within <font face="Courier New">com.mycompany.myapp.web</font> in an appropriate package order.</p>
<p>Once I&rsquo;m past the web layer, I loosen up.&nbsp; I just want to make sure all the imports for the next layer are grouped together, and so on.&nbsp; So in the example, all the <font face="Courier New">domain</font> imports would be together, then all the <font face="Courier New">utils</font>, and so on, all the way up to <font face="Courier New">java.util</font>.</p>
<p>You can set up this ordering standard in Eclipse under the Organize Imports preference.</p>
<p>How else could you check your dependencies?&nbsp; There are useful tools out there like <a href="http://www.clarkware.com/software/JDepend.html">JDepend</a>, and I use them.&nbsp; But I still like this import ordering practice.&nbsp; I typically do the manual scan right before check in time.<br /></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></channel></rss>