<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
    <channel>
        <title>Groovy - Blogs at Near Infinity</title>


        <link>http://www.nearinfinity.com/blogs/</link>
        <description>Employee Blogs</description>
        <language>en</language>
        <copyright>Copyright 2011</copyright>
        <lastBuildDate>Thu, 16 Jun 2011 19:40:19 -0500</lastBuildDate>
        <generator>http://www.sixapart.com/movabletype/</generator>
        <docs>http://www.rssboard.org/rss-specification</docs>
        
        <item>
            <title>Gradle Class July 18-20 by Tim Berglund</title>
            <description><![CDATA[<p>Near Infinity is proud to host a new Gradle Expert Training class, taught by Tim Berglund, the Author of the Gradle O'Reilly Book Series. This is an intensive and highly practical 3-day Gradle course. You will become familiar with all major concepts of Gradle and how to best use Gradle for simple as well as complex build scenarios. This course is packed with hands-on exercises.
<br /><br />To learn more please visit Gradeware's <a href="http://gradleware.com/training.html">Gradle Expert Training</a> course description. To register visit Gradeware's <a href="http://www.regonline.com/builder/site/Default.aspx?EventID=980125">Gradle course registration</a> web page.
<br /><br />Be sure to check out our <a href="../../trainingcenter/coursecatalog/upcoming/">Upcoming NIC-U Training Courses</a> page for information on more upcoming courses.]]></description>
            <link>http://www.nearinfinity.com/blogs/gray_herter/gradle_class_july_18-20_by_tim.html</link>
            <guid>http://www.nearinfinity.com/blogs/gray_herter/gradle_class_july_18-20_by_tim.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">gradle</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
            <pubDate>Thu, 16 Jun 2011 19:40:19 -0500</pubDate>
        </item>
        
        <item>
            <title>Database-Backed Refreshable Beans with Groovy and Spring 3</title>
            <description><![CDATA[<p>In 2009 I published a <a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=groovier+spring">two-part</a> series of articles on IBM developerWorks entitled <a href="http://www.ibm.com/developerworks/java/library/j-groovierspring1.html">Groovier</a> <a href="http://www.ibm.com/developerworks/java/library/j-groovierspring2.html">Spring</a>. The articles showed how Spring supports implementing beans in Groovy whose behavior can be changed at runtime via the "refreshable beans" feature. This feature essentially detects when a Spring bean backed by a Groovy script has changed, recompiles it, and replaces the old bean with the new one. This feature is pretty powerful in certain scenarios, for example in PDF generation; mail or any kind of template generation; and as a way to implement runtime modifiable business rules. One specific use case I showed was how to implement PDF generation where the Groovy scripts reside in a database, allowing you to change how PDFs are generated by simply updating Groovy scripts in your database.</p>

<p>In order to load Groovy scripts from a database, I showed how to implement custom <code>ScriptFactoryPostProcessor</code> and <code>ScriptSource</code> classes. The <code>CustomScriptFactoryPostProcessor</code> extends the default Spring <code>ScriptFactoryPostProcessor</code> and overrides the <code>convertToScriptSource</code> method to recognize a database-based script, e.g. you could specify a script source of <code>database:com/nearinfinity/demo/GroovyPdfGenerator.groovy</code>. There is also <code>DatabaseScriptSource</code> that implements the <code>ScriptSource</code> interface and which knows how to load Groovy scripts from a database.</p>

<p>In order to put these pieces together, you need to do a bit of configuration. In the articles I used Spring 2.5.x which was <i>current at the time in early 2009</i>. The configuration looked like this:</p>

<pre class="prettyprint">
&lt;bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
    &lt;!-- set data source props, e.g. driverClassName, url, username, password... --&gt;
&lt;/bean&gt

&lt;bean id="scriptFactoryPostProcessor"
  class="com.nearinfinity.spring.scripting.support.CustomScriptFactoryPostProcessor"&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;

&lt;lang:groovy id="pdfGenerator"
  script-source="database:com/nearinfinity/demo/DemoGroovyPdfGenerator.groovy"&gt;
    &lt;lang:property name="companyName" value="Database Groovy Bookstore"/&gt;
&lt;/lang:groovy&gt;
</pre>

<p>In Spring 2.5.x this works because the <code>&lt;lang:groovy&gt;</code> tag looks for a Spring bean with id "scriptFactoryPostProcessor" and if one exists it uses it, if not it creates it. In the above configuration we created our own "scriptFactoryPostProcessor" bean for <code>&lt;lang:groovy&gt;</code> tags to utilize. So all's well...until you move to Spring 3.x at which point the above configuration no longer works. This was pointed out to me by João from Brazil who tried the sample code in the articles with Spring 3.x, and it did not work. After trying a bunch of things, we eventually determined that in Spring 3.x the <code>&lt;lang:groovy&gt;</code> tag looks for a <code>ScriptFactoryPostProcessor</code> bean whose id is "org.springframework.scripting.config.scriptFactoryPostProcessor" not just "scriptFactoryPostProcessor." So once you figure this out, it is easy to change the above configuration to:</p>

<pre class="prettyprint">
&lt;bean id="org.springframework.scripting.config.scriptFactoryPostProcessor"
  class="com.nearinfinity.spring.scripting.support.CustomScriptFactoryPostProcessor"&gt;
    &lt;property name="dataSource" ref="dataSource"/&gt;
&lt;/bean&gt;

&lt;lang:groovy id="pdfGenerator"
  script-source="database:com/nearinfinity/demo/DemoGroovyPdfGenerator.groovy"&gt;
    &lt;lang:property name="companyName" value="Database Groovy Bookstore"/&gt;
&lt;/lang:groovy&gt;
</pre>

<p>Then, everything works as expected and the Groovy scripts can reside in your database and be automatically reloaded when you change them. So if you download the article sample code as-is, it will work since the bundled Spring version is 2.5.4, but if you update to Spring 3.x then you'll need to modify the configuration in applicationContext.xml for example #7 (EX #7) as shown above to change the "scriptFactoryPostProcessor" bean to be "org.springframework.scripting.config.scriptFactoryPostProcessor." Note there is a scheduled JIRA issue <a href="https://jira.springframework.org/browse/SPR-5106">SPR-5106</a> that will make the <code>ScriptFactoryPostProcessor</code> mechanism pluggable, so that you won't need to extend the default <code>ScriptFactoryPostProcessor</code> and replace the default bean, etc. But until then, this hack continues to work pretty well.</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/database-backed_refreshable_be.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/database-backed_refreshable_be.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy spring</category>
            
            <pubDate>Sat, 30 Oct 2010 11:49:06 -0500</pubDate>
        </item>
        
        <item>
            <title>Selenium Mojo : Protoype Bindings in Selenium</title>
            <description><![CDATA[<font style="font-size: 1.25em;"><b>Introduction</b></font><br /><br />On my current project we have been involved in converting some of the hundreds of manual tests that are run by our Test Team every release into a suite of automated Selenium RC tests.<br /><br />During the course of this adventure my crew found several instances where XPath and native JavaScript were not sufficiently expressive to find elements in some of our more complicated interfaces. <br /><br />Since our web app uses the Prototype/Scriptaculous JavaScript framework we wanted to find a way to make the locating power of Prototype available within Selenium RC.<br /><br />We developed approaches for both Selenium 0.9.2 and Selenium 1.0.3 (which had better programmatic support for adding JavaScript user extensions to Selenium).<br /><br /><br /><font style="font-size: 1.25em;"><b>Selenium 0.9.2</b></font><br /><br />Selenium RC provides the capability to add "user extensions" to augment its JavaScript core. <br /><br />See <a href="http://seleniumhq.org/docs/08_user_extensions.html">http://seleniumhq.org/docs/08_user_extensions.html</a> for detailed information on how to set this up. <br /><br />We wrote the following user-extension.js file:<br /><br /><pre class="prettyprint">Selenium.prototype.setupProtoypeJS = function() {<br />&nbsp;&nbsp;&nbsp; id = selenium.browserbot.getCurrentWindow().$;<br />&nbsp;&nbsp;&nbsp; css = selenium.browserbot.getCurrentWindow().$$;<br />}</pre><br />In our code we have a base class for all our test cases. To this we added our own waitForPage() method:<br /><br /><pre class="prettyprint">public void waitForPage() {<br />&nbsp;&nbsp;&nbsp; selenium.waitForPage('60000')<br />&nbsp;&nbsp;&nbsp; proc.doCommand('setupPrototypeJS', [])<br />}</pre><br />Thus every time the page reloads (which clears the JavaScript context) we call waitForPage() and this command is re-executed. It creates two global variables (id and css) and binds them to Prototype's $ and $$ functions respectively.<br /><br /><i>Note: The reason we choose id and css instead of $ and $$ was that Groovy considers $ in Strings to be a special character and we would have had to escape it each time it was used</i>.<br /><br />The Prototype selectors can now be used in Selenium RC like this:<br /><br /><pre class="prettyprint">selenium.click("dom=id('foo')")<br />selenium.click("dom=css('.bar')")<br />selenium.click("dom=css('span.foo a.baz')")</pre><br /><i>Note: You still have to specify the dom locator type so Selenium RC will know to execute your locator string as JavaScript.&nbsp; <br /></i><br /><br /><font style="font-size: 1.25em;"><b>Selenium 1.0.3</b></font><br /><br />In more recent version of Selenium RC the project added the setExtensionJs() method. This allows you to set extension JavaScript programmatically prior to starting the selenium client:<br /><br /><pre class="prettyprint">selenium = new DefaultSelenium(...)<br />selenium.setExtensionJs('...')<br />selenium.start()</pre><br />This made it much easier to implement our Prototype bindings. The only trick was that the JavaScript seems to be executed prior to having access to a page context and is also only executed once. This required us to take a different approach.<br /><br />We created id and css as global functions instead of variables. This allowed us to defer accessing the current window until the functions were actually invoked. &nbsp; <br /><br /><pre class="prettyprint">selenium.setExtensionJs('''<br />        id = function(value) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;    return selenium.browserbot.getCurrentWindow().$(value);<br /><div id=":w0" class="ii gt">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; } <br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; css = function(value) {<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return selenium.browserbot.<wbr>getCurrentWindow().$$(value);<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />''');</div></pre> <br /><i>Note: The above code snippet is written in Groovy which allows multiline Strings.<br /></i><br />The Prototype selectors are used in Selenium RC like before:<br /><br /><pre class="prettyprint">selenium.click("dom=id('foo')")<br />selenium.click("dom=css('.bar')")<br />selenium.click("dom=css('span.foo a.baz')")</pre><br /><br /><br />I would be interested in hearing feedback from anyone who has a chance to use this technique!<br />]]></description>
            <link>http://www.nearinfinity.com/blogs/stephen_mouring_jr/selenium_mojo_protoype_binding.html</link>
            <guid>http://www.nearinfinity.com/blogs/stephen_mouring_jr/selenium_mojo_protoype_binding.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">JavaScript</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Testing</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Web Development</category>
            
            
            <pubDate>Sat, 24 Apr 2010 14:00:36 -0500</pubDate>
        </item>
        
        <item>
            <title>Making Cobertura Reports Show Groovy Code with Maven</title>
            <description><![CDATA[ <p>A recent project started out life as an all-Java project that used Maven as the build tool. Initially we used <a href="http://www.atlassian.com/software/clover/">Atlassian Clover</a> to measure unit test coverage. Clover is a great product for Java code, but unfortunately it only works with Java code because it works at the Java source level. (This was the case as of Spring 2009, and I haven't checked since then.) As we started migrating existing code from Java to Groovy and writing new code in Groovy, we started to lose data about unit test coverage because Clover does not understand Groovy code. To remedy this problem we switched from Clover to <a href="http://cobertura.sourceforge.net/">Cobertura</a>, which instruments at the bytecode level and thus works with Groovy code. Theoretically it would also work with any JVM-based language but I'm not sure whether or not it could handle something like Clojure or not.</p>

<p>In any case, we only cared about Groovy so Cobertura was a good choice. With the <a href="http://mojo.codehaus.org/cobertura-maven-plugin/">Cobertura Maven</a> plugin we quickly found a problem, which was that even though the code coverage was running, the reports only showed coverage for Java code, not Groovy. This blog shows you how to display coverage on Groovy code  when using Maven and the Cobertura plugin. In other words, I'll show how to get Cobertura reports to link to the real Groovy source code in Maven, so you can navigate Cobertura reports as you normally would.</p>

<p>The core problem is pretty simple, though it took me a while to figure out how to fix it. Seems to be pretty standard in Maven: I know what I want to do, but finding out how to do it is the <i>really</i> hard part. The only thing you need to do is tell Maven about the Groovy source code and where it lives. The way I did this is to use the Codehaus <a href="http://mojo.codehaus.org/build-helper-maven-plugin/">build-helper-maven-plugin</a> which has an add-source goal. The add-source goal does just what you would expect; it adds a specified directory (or directories) as a source directory in your Maven build. Here's how you use it in your Maven pom.xml file:</p>

<pre class="prettyprint">
&lt;plugin&gt;
    &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt;
    &lt;artifactId&gt;build-helper-maven-plugin&lt;/artifactId&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;phase&gt;generate-sources&lt;/phase&gt;
            &lt;goals&gt;
                &lt;goal&gt;add-source&lt;/goal&gt;
            &lt;/goals&gt;
            &lt;configuration&gt;
                &lt;sources&gt;
                    &lt;source&gt;src/main/groovy&lt;/source&gt;
                &lt;/sources&gt;
            &lt;/configuration&gt;
        &lt;/execution&gt;
    &lt;/executions&gt;
&lt;/plugin&gt;
</pre>

<p>In the above code snippet, we're  using the "build-helper-maven-plugin" to add the src/main/groovy directory. That's pretty much it. Run Cobertura as normal, view the reports, and you should now see coverage on Groovy source code as well as Java.</p>
]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/making_cobertura_reports_show.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/making_cobertura_reports_show.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Testing</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">cobertura</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">maven</category>
            
            <pubDate>Tue, 15 Dec 2009 23:33:19 -0500</pubDate>
        </item>
        
        <item>
            <title>Be careful with Groovy&apos;s optional parens on method calls!</title>
            <description><![CDATA[<p>My current project (a web application) has a module that is almost entirely written in Groovy.&nbsp; <b>Note:</b> We are using the latest version 1.6.5 of Groovy.</p><p>In one of the methods we had some logic similar to the following:<br /><br /></p><code> def myMethodToProcessTheList(def listOfThings) {<br /></code><blockquote><code>if (listOfThings &amp;&amp; listOfThings.size &lt; 0) {<br />&nbsp;&nbsp;&nbsp; //Do my logic<br /></code><code>}<br /></code></blockquote><code>}</code><br /><br />When the above code is run using Java 5 everything works wonderfully.&nbsp; However when we pushed the code out to our server running Java 6 we got an interesting error stating that it couldn't compare java.util.ArrayList to java.lang.Integer.<br /><br />The problem is actually that the size method needs the parens after it (<b>Note:</b> The Groovy docs actually do state that methods with at least <u>ONE</u> param can omit the parens).&nbsp; I realize now that it would make sense that parameter-less methods would need parens because how else would Groovy distinguish between methods and property accessors?&nbsp; I did find one forum <a href="http://old.nabble.com/TestApp.groovy-pre-Grails-1.1-td22437010.html">post</a> that indicated that in Groovy, lists have special properties that act like the spread-dot operator.&nbsp; That is why the listOfThings.size returned the ArrayList instead of a number.<br /><br />So why does this work in Java 5 but not Java 6?&nbsp; That is a great question, one of which I really don't have a definitive answer.&nbsp; I'm not completely sure if this purely a Java 5/Java 6 difference or simply a difference between the IBM Java 5/Java 6 JVM.<br /><br />If anyone has a theory as to why it would work one way on Java 5 and the other in Java 6, I would love to hear it.<br /><code></code><blockquote><code></code></blockquote>]]></description>
            <link>http://www.nearinfinity.com/blogs/chris_rohr/becareful_with_groovys_optiona.html</link>
            <guid>http://www.nearinfinity.com/blogs/chris_rohr/becareful_with_groovys_optiona.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">ArrayList</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">ibm</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">jvm</category>
            
            <pubDate>Wed, 18 Nov 2009 16:20:17 -0500</pubDate>
        </item>
        
        <item>
            <title>Groovy, sometimes you still need a semicolon.</title>
            <description><![CDATA[Like Javascript, semicolons are optional in Groovy except for when they aren't optional. These examples are both pretty contrived, though I found both because they're actually something that I've written, and could both be written better. That's not really the point I'm making though. When something doesn't compile when it looks like it clearly should sometimes it's hard to track down why, and it's surprising to learn that it's because you need a semicolon.<br /><br /><b>Example the first: </b>Generics at the end of a line:<br /><br /><blockquote><pre>def list = [1,2,3] as List&lt;Integer&gt;<br />println list<br /></pre></blockquote><br />If you try to compile this in Groovy it will give you the error message: 'unexpected token: println', however this:<br /><br /><blockquote><pre>def list = [1,2,3] as List&lt;Integer&gt;;<br />println list</pre></blockquote>Gives the expected output.<br /><br /><br /><b>Example the second: </b>Ambiguous Closures<br /><br /><blockquote><pre>{-&gt; assert GroovyClosureTest == owner.getClass() }()<br />{-&gt; assert GroovyClosureTest == delegate.getClass() }()<br /></pre></blockquote><br />I don't think you'd really ever need to do something like this, but a closure can be defined and called on a single line. Because of Groovy's special closure parameter syntax (<i>e.g. list.each() {} being synonomous with list.each({})</i>) the compiler thinks I'm passing the second closure into the first as an argument. Again a semicolon is needed to seperate the two lines:<br /><br /><blockquote><pre>{-&gt; assert GroovyClosureTest == owner.getClass() }();<br />{-&gt; assert GroovyClosureTest == delegate.getClass() }()<br /></pre></blockquote><br />]]></description>
            <link>http://www.nearinfinity.com/blogs/john_cato/groovy_sometimes_you_still_nee.html</link>
            <guid>http://www.nearinfinity.com/blogs/john_cato/groovy_sometimes_you_still_nee.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
            
            <pubDate>Thu, 05 Nov 2009 14:40:30 -0500</pubDate>
        </item>
        
        <item>
            <title>Groovification</title>
            <description><![CDATA[ <p>Last week I tweeted about groovification, which is defined thusly:</p>

<p><i>groovification.</i> noun. the process of converting java source code into groovy source code (usually done to make development more fun)</p>

<p>On my main day-to-day project, we've been writing unit tests in Groovy for quite a while now, and recently we decided to start implementing new code in Groovy rather than Java. The reason for doing this is to gain more flexibility in development, to make testing easier (i.e. in terms of the ability to mock dependencies in a trivial fashion), to eliminate a lot of Java boilerplate code and thus write less code, and of course to make developing more fun. It's not that I hate Java so much as I feel Java simply isn't innovating anymore and hasn't for a while, and isn't adding features that I simply don't want to live without anymore such as closures and the ability to do metaprogramming when I need to. In addition, it isn't removing features that I don't want, such as checked exceptions. If I know, for a fact, that I can handle an exception, I'll handle it appropriately. Otherwise, when there's nothing I can do anyway, I want to let the damn thing propagate up and just show a generic error message to the user, log the error, and send the admin team an email with the problem details.</p>

<p>This being, for better or worse, a Maven project, we've had some interesting issues with mixed compilation of Java and Groovy code. The <a href="http://groovy.codehaus.org/">GMaven plugin</a> is easy to install and works well but currently has some outstanding issues related to Groovy stub generation, specifically it cannot handle <a href="http://jira.codehaus.org/browse/MGROOVY-108">generics</a> or <a href="http://jira.codehaus.org/browse/MGROOVY-109">enums</a> properly right now. (Maybe someone will be less lazy than me and help them fix it instead of complaining about it.) Since many of our classes use generics, e.g. in service classes that return domain objects, we currently are not generating stubs. We'll convert existing classes and any other necessary dependencies to Groovy as we make updates to Java classes, and we are implementing new code in Groovy. Especially in the web controller code, this becomes trivial since the controllers generally depend on other Java and/or Groovy code, but no other classes depend on the controllers. So starting in the web tier seems to be a good choice. Groovy combined with implementing controllers using the Spring @MVC annotation-based controller configuration style (i.e. no XML configuration), is making the controllers <i>really</i> thin, lightweight, and easy to read, implement, and test.</p>

<p>I estimate it will take a while to fully convert all the existing Java code to Groovy code. The point here is that we are doing it piecemeal rather than trying to do it all at once. Also, whenever we convert a Java file to a Groovy one, there are a few basics to make the classes Groovier without going totally overboard and spending loads of time. First, once you've used <a href="http://www.jetbrains.com/idea/">IntelliJ's</a> move refactoring to move the .java file to the Groovy source tree (since we have src/main/java and src/main/groovy) you can then use IntelliJ's handy-dandy "Rename to Groovy" refactoring. In IntelliJ 8.1 you need to use the "Search - Find Action" menu option or keystroke and type "Rename to..." and select "Rename to Groovy" since they goofed in version 8 and that option was left off a menu somehow. Once that's done you can do a few simple things to make the class a bit more groovy. First, get rid of all the semi-colons. Next, replace getter/setter code with direct property access. Third, replace for loops with "each"-style internal iterators when you don't need the loop index and "eachWithIndex" where you do. You can also get rid of some of the redundant modifiers like "public class" since that is the Groovy default. That's not too much at once, doesn't take long, and makes your code Groovier. Over time you can do more groovification if you like.</p>

<p>The most common gotchas I've found have to do with code that uses anonymous or inner classes since Groovy doesn't support those Java language features. In that case you can either make a non-public named class (and it's OK to put it in the same Groovy file unlike Java as long as it's not public) or you can refactor the code some other way (using your creativity and expertise since we are not <a href="http://www.nearinfinity.com/blogs/scott_leberknight/thinking_matters.html">monkeys</a>, right?). This can sometimes be a pain, especially if you are using a lot of them. So it goes. (And yes, that is a <a href="http://en.wikipedia.org/wiki/Slaughterhouse-Five">Slaughterhouse Five</a> reference.)</p>

<p>Happy groovification!</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/groovification.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/groovification.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">gmaven</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
            <pubDate>Mon, 04 May 2009 17:22:38 -0500</pubDate>
        </item>
        
        <item>
            <title>Groovy&apos;s Safe Navigation Operator Not as Safe as I Thought</title>
            <description><![CDATA[<p>The safe navigation operator is almost certainly my favorite operator in Groovy. It allows you to guard against <code>NullPointerException</code>(s) much more cleanly than defining a nasty if/else mess. Consider the following example.</p>

<pre name="code" class="prettyprint lang-groovy">
class Book {
    String title
    Author author
}

class Author {
    String firstName
    String lastName
}

def author = new Author(firstName:'Jason')
def book = new Book(title:'Say no to NPEs', author:author)

println book.author?.lastName
</pre>

<p>Did you see that <code>?.</code> operator on the last line of the code sample? That's the safe navigation operator, and it's the equivalent of writing the following if statement (although it's much more readable).</p>

<pre name="code" class="prettyprint lang-groovy">
if (book.author != null) {
    println book.author.lastName
}
</pre>

<p>The safe navigation operator essentially checks to see if the object you're about to invoke a method on is <code>null</code>. If it is <code>null</code>, it simply skips the method invocation and returns <code>null</code>. If it isn't <code>null</code>, it proceeds as usual. It works for method chaining too, so if you're worried about <code>book</code> being <code>null</code>, you could write</p>

<pre name="code" class="prettyprint lang-groovy">
println book?.author?.lastName
</pre>

<p>This way, if either <code>book</code> or <code>author</code> are <code>null</code>, you simply print out <code>null</code> instead of causing a NullPointerException.</p>

<p>Since learning about the safe navigation operator, I've used it successfully in dozens of classes without any problem. Until last week. Consider the following line of code .</p>

<pre name="code" class="prettyprint lang-groovy">
println book?.author?.firstName?.trim().concat(" is great.")
</pre>

<p>Thanks to the safe navigation operator we can write this concatenation of <code>firstName</code> and a sentence fragment without worrying about <code>NullPointerException</code>(s) and ugly if blocks. Or so I thought.</p>

<p>Looking at this line of code, I thought for sure I was safe from any sneaky <code>NullPointerException</code>. If <code>book</code>, <code>author</code> or <code>firstName</code> are <code>null</code> I'll simply end up printing <code>null</code> and not have to worry about the <code>concat()</code> method. After all, if the <code>trim()</code> method succeeds, there's no sense in guarding it's result for <code>null</code>. And that's where I was wrong.</p>

<p>I naively assumed the method chain would stop once the safe navigation operator encountered a <code>null</code> when in fact it does not. While the <code>trim()</code> method is safe from being called on a <code>null</code> <code>firstName</code> object, it will return <code>null</code>, upon which the <code>concat()</code> method is called. Oops!</p>
]]></description>
            <link>http://www.nearinfinity.com/blogs/jeff_kunkle/groovys_safe_navigation_operat.html</link>
            <guid>http://www.nearinfinity.com/blogs/jeff_kunkle/groovys_safe_navigation_operat.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
            
            <pubDate>Tue, 14 Apr 2009 06:50:00 -0500</pubDate>
        </item>
        
        <item>
            <title>Groovy + Spring = Groovier Spring</title>
            <description><![CDATA[<p>If you're into Groovy and Spring, check out my <a href="http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=groovier+spring">two-part</a> series on <a href="http://www.ibm.com/developerworks/">IBM developerWorks</a> on using Groovy together with Spring's dynamic language support for potentially more flexible (and interesting) applications. In <a href="http://www.ibm.com/developerworks/java/library/j-groovierspring1.html">Part 1</a> I show how to easily integrate Groovy <i>scripts</i> (i.e. .groovy files containing one or more classes) into Spring-based applications. In <a href="http://www.ibm.com/developerworks/java/library/j-groovierspring2.html">Part 2</a> I show how to use the "refreshable beans" feature in Spring to automatically and transparently reload Spring beans implemented in Groovy from pretty much anywhere including a relational database, and why you might actually are to do something like that!</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/groovy_spring_groovier_spring.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/groovy_spring_groovier_spring.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">dynamic</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">spring</category>
            
            <pubDate>Tue, 06 Jan 2009 23:23:32 -0500</pubDate>
        </item>
        
        <item>
            <title>The &quot;N matchers expected, M recorded&quot; Problem in EasyMock</title>
            <description><![CDATA[<p><a href="http://www.easymock.org/">EasyMock</a> is a Java dynamic mocking framework that allows you to record expected behavior of mock objects, play them back, and finally verify the results. As an example, say you have an interface <code>FooService</code> with a method <code>List&lt;Foo> findFoos(FooSearchCriteria criteria, Integer maxResults, String[] sortBy)</code> and that you have a <code>FooSearcher</code> class which uses a <code>FooService</code> to perform the actual searching. With EasyMock you could test that the <code>FooSearcher</code> uses the <code>FooService</code> as it should <i>without needing to also test the actual FooService implementation</i>. It is important in unit tests to isolate dependent collaborators so they can be tested independently. One thing I pretty much always forget when using EasyMock is that if you use any <a href="http://www.jdocs.com/link/org/easymock/IArgumentMatcher.html">IArgumentMatcher</a>s in your expectations, then <i>all</i> the arguments must use an <code>IArgumentMatcher</code>. Going back to the <code>FooSearcher</code> example, you might start out with the following test (written in Groovy for convenience):</p>

<pre class="prettyprint">void testSearch() {
  def service = createMock(FooService)
  def searcher = new FooSearcher(fooService: service, maxAllowedResults: 10)
  def criteria = new FooSearchCriteria()
  def sortCriteria = ["bar", "baz"] as String[]
  def expectedResult = [new Foo(), new Foo()]
  expect(service.findFoos(criteria, 10, sortCriteria)).andReturn(expectedResult)
  replay service
  def result = searcher.search(criteria, "bar", "baz")
  assertSame expectedResult, result
  verify service
}
</pre>

<p>The above test fails with the following error message:</p>

<pre class="prettyprint">java.lang.AssertionError: 
  Unexpected method call findFoos(com.acme.FooSearchCriteria@ea443f, 10, [Ljava.lang.String;@e41d4a):
    findFoos(com.acme.FooSearchCriteria@ea443f, 10, [Ljava.lang.String;@268cc6): expected: 1, actual: 0
	at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:29)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45)
	at $Proxy0.findFoos(Unknown Source)
	at com.acme.FooSearcher.search(FooSearcher.java:19)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    ...
</pre>

<p>We expected a call to <code>findFoos</code> which takes a <code>FooSearchCriteria</code>, an integer, and a string array describing the sort conditions. But from the error message, EasyMock told us that the expected method was not called and so verification of the mock behavior failed. What happened? Well, basically the string array that was expected was not the string array actually passed as the argument. Look back at the stack trace and specifically the array arguments: the actual argument was <code>[Ljava.lang.String;@e41d4a</code> while the expected argument was <code>[Ljava.lang.String;@268cc6</code>. The <code>FooSearcher.search</code> method's signature is <code>List&lt;Foo> FooSearchCriteria criteria, String... sortBy)</code> - the varargs that are passed to <code>FooSearcher.search</code> are getting packed into a new array when called and that new array is subsequently passed into the <code>FooService</code> which is what causes the difference between the expected and actual array arguments!</p>

<p>To make sure that arguments such as arrays and other complex objects are matched properly by the mock object, EasyMock provides <a href="http://www.jdocs.com/link/org/easymock/IArgumentMatcher.html">IArgumentMatcher</a> to compare the expected and actual arguments to method calls. Essentially, it is like performing a logical "assertEquals" on the arguments. One of the matchers EasyMock provides is obtained via the static <a href="http://www.jdocs.com/easymock/2.2/org/easymock/EasyMock.html#M-aryEq(T[])">aryEq</a> method in the <a href="http://www.jdocs.com/easymock/2.2/org/easymock/EasyMock.html">EasyMock</a> class. So for example if you had a method that took a single array argument, you could make an expectation of mock behavior like this:</p>

<pre class="prettyprint">def myArray = ["foo", "bar", "baz"] as String[]
expect(someObject.someMethod(EasyMock.aryEq(myArray)).andReturn(anotherObject)
</pre>

<p>Here you tell EasyMock to expect a call to <code>someMethod</code> on <code>someObject</code> with <code>myArray</code> as the sole argument, and to return <code>anotherObject</code>. Cool, so let's try to fix the failing test above using <code>EasyMock.aryEq</code> (which was imported statically using <code>import static</code>):</p>

<pre class="prettyprint">void testSearch() {
  def service = createMock(FooService)
  def searcher = new FooSearcher(fooService: service, maxAllowedResults: 10)
  def criteria = new FooSearchCriteria()
  def sortCriteria = ["bar", "baz"] as String[]
  def expectedResult = [new Foo(), new Foo()]
  // Try to use EasyMock's aryEq() to ensure the expected array argument equals the actual argument...
  expect(service.findFoos(criteria, 10, aryEq(sortCriteria))).andReturn(expectedResult)
  replay service
  def result = searcher.search(criteria, "bar", "baz")
  assertSame expectedResult, result
  verify service
}
</pre>

<p>This test <i>also</i> fails with the following error message:</p>

<pre class="prettyprint">java.lang.IllegalStateException: 3 matchers expected, 1 recorded.
	at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:41)
	at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:33)
	at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:26)
	at org.easymock.internal.RecordState.invoke(RecordState.java:64)
	at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:24)
	at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:45)
	at $Proxy0.findFoos(Unknown Source)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    ...
</init></init></pre>

<p>Wait, shouldn't that have made EasyMock ensure that the supplied argument was verified using an <code>IArgumentMatcher</code>, specifically an <a href="http://www.jdocs.com/easymock/2.2/org/easymock/internal/matchers/ArrayEquals.html">ArrayEquals</a> matcher? Well, sort of. And this is where I always forget what the "N matchers expected, M recorded" error message means and fumble around for a few minutes while I remember. In short, the rule is this:</p>

<p><strong>If you use an argument matcher for one argument, you must use an argument matcher for <i>all</i> the arguments.</strong></p>

<p>So in the above example, we recorded one matcher via the call to <code>aryEq</code>. Now EasyMock will expect an argument matcher for all the arguments in the expectation, and there are three arguments. Now this makes sense. We need to add argument matchers for the other arguments as well. So let's now fix the test:</p>

<pre class="prettyprint">void testSearch() {
  def service = createMock(FooService)
  def maxResults = 10
  def searcher = new FooSearcher(fooService: service, maxAllowedResults: maxResults)
  def criteria = new FooSearchCriteria()
  def sortCriteria = ["bar", "baz"] as String[]
  def expectedResult = [new Foo(), new Foo()]
  // If you define one matcher for an expected argument, you need to define them for all the arguments!
  expect(service.findFoos(isA(FooSearchCriteria), eq(maxResults), aryEq(sortCriteria))).andReturn(expectedResult)
  replay service
  def result = searcher.search(criteria, "bar", "baz")
  assertSame expectedResult, result
  verify service
}
</pre>

<p>Now the test passes as we expect it to. We used several other common types of argument matchers here via the static <code>isA</code> and <code>eq</code> argument matchers. The <a href="http://www.jdocs.com/easymock/2.2/org/easymock/EasyMock.html#M-isA(Class%3CT%3E)">isA</a> matcher ensures the argument is an instance of the specified class, while the <a href="http://www.jdocs.com/easymock/2.2/org/easymock/EasyMock.html#M-eq(T)">eq</a> matcher checks that the actual argument equals the expected argument via the normal Java equality check, i.e. <code>expected.equals(actual)</code>. So in summary, if you ever receive the dreaded "N matchers expected, M recorded" error message from EasyMock, you know you need to ensure that all arguments to an expectation use a matcher. And, if you got this far and were dying to mention that if you're using Groovy to test Java code there are easier ways in Groovy to test than using a framework like EasyMock, you're right for the most part. There are still some things you cannot do when testing Java code using Groovy. I plan to go into that more in a future blog post.</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/the_n_matchers_expected_m.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/the_n_matchers_expected_m.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">easymock</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">testing</category>
            
            <pubDate>Tue, 30 Sep 2008 17:43:21 -0500</pubDate>
        </item>
        
        <item>
            <title>Groovy Fun With ObjectRange</title>
            <description><![CDATA[<p>I ran into a situation the other day with Groovy that baffled me at first. Let's create a range  from 0.0 to 10.0 and then use it to check if a certain number is contained within that range, like this:</p>

<pre class="prettyprint">groovy:000> r = 0.0..10.0
===> 0.0..10.0
groovy:000> r.contains(5.6)
===> false
</pre>

<p>WTF? The number 5.6 is <i>not</i> contained in the range 0.0 to 10.0? I beg to differ. So what's actually going on here? Using the shell we can do some more digging, interrogating the range object to see what its bounds are, what values it contains if you iterate it, and so on:</p>

<pre class="prettyprint">groovy:000> r = 0.0..10.0
===> 0.0..10.0
groovy:000> r.class
===> class groovy.lang.ObjectRange
groovy:000> r.from.class
===> class java.math.BigDecimal
groovy:000> r.to.class
===> class java.math.BigDecimal
groovy:000> r.each { print " $it " }  
 0.0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0  10.0 ===> 0.0..10.0
groovy:000> r.contains 5 
===> true
groovy:000> r.contains 5.0
===> true
groovy:000> r.contains 5.6
===> false
</pre>

<p>So what did we learn? First, the range is an <code>ObjectRange</code> whose bounds are <code>BigDecimal</code>s. Second, that iterating by default iterates in increments of one. And third that the <code>contains</code> method does not quite do what I would expect by default. Looking at Groovy's <code>ObjectRange</code> class makes it clear exactly what's going on, so let's look:</p>

<pre class="prettyprint">public boolean contains(Object value) {
  Iterator it = iterator();
  if (value == null) return false;
  while (it.hasNext()) {
    try {
      if (DefaultTypeTransformation.compareEqual(value, it.next())) return true;
    } catch (ClassCastException e) {
      return false;
    }
  }
  return false;
}
</pre>

<p>The Groovy <code>ObjectRange</code>'s <code>contains</code> method defines containment as whether a value is contained within the values <i>generated by its iterator</i>. By now many of my <b>many millions</b> of readers are about to post a comment telling me the problem, so I'll preempt that temptation by adding a few more lines of interaction with the Groovy shell:</p>

<pre class="prettyprint">groovy:000> r.containsWithinBounds 5.0
===> true
groovy:000> r.containsWithinBounds 5.6
===> true
</pre>

<p>Aha! So <code>contains</code> doesn't do what you might think it should, but <code>containsWithinBounds</code> does. Its JavaDoc says "Checks whether a value is between the from and to values of a Range." Conspicuously there is no JavaDoc on the <code>contains</code> method to tell me that what it actually does is check whether a value is contained within the <i>discrete values</i> generated by the iterator. Let's try more more thing:</p>

<pre class="prettyprint">groovy:000> r.containsWithinBounds 5
ERROR java.lang.ClassCastException: java.lang.Integer
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...
</pre>

<p>Oops! Not only do you need to call <code>containsWithinBounds</code> rather than <code>contains</code>, you also need to call it with the correct type, as there is no coercion going on since it uses <code>Comparable.compareTo()</code> under the covers.</p>

<p>Notwithstanding all the recent activity regarding all the <a href="http://www.ruby-forum.com/topic/157034">Ruby security flaws</a> recently discovered, how does Ruby handle inclusion of a number within a range? Here's some irb output:</p>

<pre class="prettyprint">>> r = 0.0..10.0
=> 0.0..10.0
>> r.class
=> Range
>> r.begin.class
=> Float
>> r.end.class
=> Float
>> r.each { |item| print " #{item} " }
TypeError: can't iterate from Float
        from (irb):53:in `each'
        from (irb):53
>> r.include? 5
=> true
>> r.include? 5.0
=> true
>> r.include? 5.6
=> true
</pre>

<p>To me this is more <i>semantically</i> and <i>intuitively</i> correct behavior. First, while I can create a range with float bounds, I cannot iterate that range - for <i>non-integral</i> numbers, how exactly can you define the next item after 0.0 for example? 0.1, 0.01, 0.001, and so on till infinity. Second, the <code>include?</code> method behaves as I would expect no matter what type of argument I pass. I am able to iterate ranges of integral numbers, however, which could arguably also be confusing since the behavior of the method depends on the type. Then again, that's pretty much what polymorphic method behavior is about I suppose.</p>

<pre class="prettyprint">>> r = 0..10
=> 0..10
>> r.each { |item| print " #{item} " }
 0  1  2  3  4  5  6  7  8  9  10 => 0..10
</pre>

<p>In the case of integers Ruby uses an increment of one by default. You could use the <code>step</code> method to get a different increment, e.g.:</p>

<pre class="prettyprint">>> r.step(2) { |item| print " #{item} " }
 0  2  4  6  8  10 => 0..10
</pre>

<p>So what's the point of all this? That Ruby is better than Groovy? Nope. I really like both languages. I think there are a couple of points that were reinforced to me:</p>

<p>First, RTFM (or source code --> RTFC). Even though Groovy's <code>contains</code> method doesn't behave how <i>I</i> think it should, there is the method I was looking for with <code>containsWithinBounds</code>.</p>

<p>Second, having a shell to play around with short snippets of code is really, really useful, without needing to create a class with a main method just to play around with code.</p>

<p>Third, documentation and semantics matter. If something doesn't feel intuitively correct based on how similar things act, it is more likely to cause confusion and errors. In this case, since my unit test immediately caught the error, I was able to figure the problem out in a few minutes.</p>

<p>Finally, following on from the last point, unit tests continue to remain valuable. Of course anyone who knows me would roll their eyes over my anal-ness (which Mac's dictionary is telling me is not really a word but I don't care at the moment) expecting me to get something about unit testing in somehow.</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/groovy_fun_with_objectrange.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/groovy_fun_with_objectrange.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">JRuby</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">range</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">ruby</category>
            
            <pubDate>Wed, 25 Jun 2008 15:34:02 -0500</pubDate>
        </item>
        
        <item>
            <title>Verify EasyMock Behavior When Expecting Exceptions</title>
            <description><![CDATA[<p>Often when writing unit tests I use <a href="http://www.easymock.org/">EasyMock</a> to mock dependencies of the class under test. And many times I need to test that a certain type of exception is thrown during a test. Sometimes I need both, for example I am using a mock to simulate a dependency that throws an exception <i>and</i> I want my test to verify the appropriate exception was indeed thrown and that the mock was called properly. In those cases, I use a simple little trick: use a try/finally block along with a <a href="http://www.junit.org/">JUnit</a> "<code>@Test(expected = FooException.class</code>" annotation on my test method. Voila! Now you can verify mock behavior and verify the exception was thrown at the same time. This is cleaner than using a catch block and asserting the correct exception was thrown, since you rely on JUnit to verify the exception using the "expected" attribute of the @Test annotation. For example:</p>

<pre class="prettyprint">@Test(expected = ThrottleException.class)
public void testSomethingWithDependencies() {
    // Create mock
    Rocket mainBooster = createMock(Rocket.class);
	
    // Record behavior
    mainBooster.ignite();
    
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class);
    
    // Replay mock
    replay(rocket);
    
    // Create object with dependency on mainBooster
    SpaceShuttle shuttle = new SpaceShuttle(rocket);    
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    try {
        shuttle.blastOff();
    }
    finally {
        verify(rocket);
    }
}
</pre>

<p>If instead of writing tests in Java you write them in <a href="http://groovy.codehaus.org/">Groovy</a>, the above code could be a little bit Groovier, though not much. (In an earlier <a href="http://www.sleberknight.com/blog/sleberkn/entry/20080321">post</a> I showed how you can write unit tests in Groovy and still use JUnit instead of <code>GroovyTestCase</code> if you like.)</p>

<pre class="prettyprint">@Test(expected = ThrottleException)
void testSomethingWithDependencies() {
    // Create mock
    def mainBooster = createMock(Rocket)
    
    // Record behavior
    mainBooster.ignite()
    
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class)
    
    // Replay mock
    replay rocket
    
    // Create object with dependency on mainBooster
    def shuttle = new SpaceShuttle(rocket)
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    try {
        shuttle.blastOff()
    }
    finally {
        verify rocket
    }
}
</pre>

<p>Even more Groovy in this case would be to extend <code>GroovyTestCase</code> and use its <code>shouldFail</code> method, like so:</p>

<pre class="prettyprint">void testSomethingWithDependencies() {
    // Create mock
    def mainBooster = createMock(Rocket)
	
    // Record behavior
    mainBooster.ignite()
	
    // Simluate an invalid call to 'throttleUp'
    expect(rocket.throttleUp(-10000L)).andThrow(ThrottleException.class)
    
    // Replay mock
    replay rocket
    
    // Create object with dependency on mainBooster
    def shuttle = new SpaceShuttle(rocket)
    
    // Now try to perform a 'blast off' and
    // verify the mock behavior was as expected
    shouldFail(ThrottleException) {
        shuttle.blastOff()
    }
    verify rocket
}
</pre>

<p>The <code>GroovyTestCase</code> version is probably the cleanest of the above three options. If you're not into Groovy, you can still use the JUnit  "<code>@Test(expected = BarException.class)</code>" together with a try/finally/verify in plain Java unit tests for a cleaner test experience.</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/verify_easymock_behavior_when_expecting.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/verify_easymock_behavior_when_expecting.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Testing</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">easymock</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">testing</category>
            
            <pubDate>Tue, 13 May 2008 14:51:08 -0500</pubDate>
        </item>
        
        <item>
            <title>Configuring easyb with maven 2 (maven-easyb-plugin)</title>
            <description><![CDATA[If you aren't familiar with BDD then this blog isn't for you.  If you've used RSpec or you have read a little about BDD and you want to kick the tires with a very simple BDD implementation in Groovy (aka easyb) and you want to use maven 2, then maybe you will get a tiny bit of use from this.

<br /><br />
Here is a fully functional pom file that works with easyb 0.8 and maven-easyb-plugin 0.8.  
<pre class="prettyprint lang-xml">
&lt;project&gt;

  &lt;modelversion&gt;4.0.0&lt;/modelversion&gt;
  &lt;groupid&gt;com.trial.easyb&lt;/groupid&gt;
  &lt;artifactid&gt;easyb-trial&lt;/artifactid&gt;
  &lt;version&gt;0.1&lt;/version&gt;

  &lt;dependencies&gt;
    &lt;dependency&gt;
        &lt;groupid&gt;org.easyb&lt;/groupid&gt;
        &lt;artifactid&gt;easyb&lt;/artifactid&gt;
        &lt;version&gt;0.8&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupid&gt;junit&lt;/groupid&gt;
        &lt;artifactid&gt;junit&lt;/artifactid&gt;
        &lt;version&gt;4.4&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;

  &lt;repositories&gt;
    &lt;repository&gt;
      &lt;id&gt;easyb&lt;/id&gt;
      &lt;url&gt;http://www.easyb.org/repo/&lt;/url&gt;
    &lt;/repository&gt;
  &lt;/repositories&gt;
  &lt;pluginrepositories&gt;
    &lt;pluginrepository&gt;
      &lt;id&gt;easyb&lt;/id&gt;
      &lt;url&gt;http://www.easyb.org/repo/&lt;/url&gt;
    &lt;/pluginrepository&gt;
  &lt;/pluginrepositories&gt;

  &lt;build&gt;
    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupid&gt;org.easyb&lt;/groupid&gt;
        &lt;artifactid&gt;maven-easyb-plugin&lt;/artifactid&gt;
        &lt;version&gt;0.8&lt;/version&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;goals&gt;
              &lt;goal&gt;test&lt;/goal&gt;
              &lt;goal&gt;storyReport&lt;/goal&gt;
            &lt;/goals&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
        &lt;configuration&gt;
          &lt;easybtestdirectory&gt;${basedir}/src/test/stories&lt;/easybtestdirectory&gt;
          &lt;storyreport&gt;${project.build.directory}/easyb-stories.txt&lt;/storyreport&gt;
          &lt;xmlreport&gt;${project.build.directory}/easyb/report.xml&lt;/xmlreport&gt;
        &lt;/configuration&gt;
      &lt;/plugin&gt;
    &lt;/plugins&gt;
  &lt;/build&gt;  

&lt;/project&gt;
</pre>


Gotchas (at least it got me). For the maven-easyb-plugin easyb:storyReport goal:
<br /><br />
The pom file xmlReport configuration has a default value which is:
<br /><br />
          <xmlreport>${project.build.directory}/easyb/report.xml</xmlreport>

<br /><br />
If you change it (as per the maven-easyb-plugin documentation) be sure to change the the storyReport which is being renamed to xmlReport to help avoid confusion:
<br /><br />
          <xmlreport>${project.build.directory}/easyb-report.xml</xmlreport>
<br /><br />
So, to recap, if you change the value in the pom.xml file you MUST also pass in the storyReport (soon to be renamed to xmlReport) parameter to maven and they have to match.]]></description>
            <link>http://www.nearinfinity.com/blogs/bryan_weber/configuring_easyb_with_maven_2.html</link>
            <guid>http://www.nearinfinity.com/blogs/bryan_weber/configuring_easyb_with_maven_2.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
            
            <pubDate>Tue, 29 Apr 2008 17:29:31 -0500</pubDate>
        </item>
        
        <item>
            <title>ProjectEuler problem 1 in C, Groovy, Lisp, Perl, Python, and Ruby</title>
            <description><![CDATA[<p>Updated 2008-05-02: new Python implementation using sum() -- thanks Pete!
</p><p>My <a href="http://www.nearinfinity.com/blogs/page/seths?entry=nice_python">blog post</a> about the <a href="http://projecteuler.net/index.php?section=problems&amp;id=1">first problem</a> in <a href="http://projecteuler.net/">Project Euler</a> went strange places. I was just trying to learn Python by solving a barely non-trivial problem. Maybe it was a full moon, not sure, but it wound up in a tangle of gcc, groovyc, and <a href="http://www.emacswiki.org/cgi-bin/wiki/CompiledFile">.elc</a>. Happily, some good performance improvements were suggested and I've tried to incorporate them below.
<a name="toc"> </a>

</p><p>This is a really long post. Here's the skeleton:
  </p><ol>
    <li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#runtime">Runtime environment</a>
    </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#results">Results</a>
    </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#code">Code</a> (alphabetically by language)
      <ol type="a">
        <li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_c">C</a>
        </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_g">Groovy</a>
        </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_l">Lisp</a>
        </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_pe">Perl</a>
        </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_py">Python</a>
        </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_r">Ruby</a>
      </li></ol>
    </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#facepalm">Big O(rly)?</a>
    </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#wrapup">Wrap up</a>
    </li><li><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#extras">Extras</a>
  </li></ol>
<p></p>
<a name="runtime"> </a><h2>Runtime environment</h2>
<ul>
  <li><b>Machine</b>: Powerbook Pro, 10.5.2, 2x 2.16 GHz Core 2 Duo
  </li><li><b>Userspace programs</b>: Finder, Terminal
  </li><li><b>Battery conservation mode</b>: Better Performance (plugged in)
  </li><li><b>C</b>: GCC 4.0.1 (Apple Inc. build 5465)
  </li><li><b>Groovy</b>: 1.5.5 JVM: 1.5.0_13-119
  </li><li><b>Lisp</b>: GNU Emacs 22.1.1
  </li><li><b>Perl</b>: v5.8.8, built for darwin-thread-multi-2level
  </li><li><b>Python</b>: 2.5.1
  </li><li><b>Ruby</b>: 1.8.6 (2007-09-24 patchlevel 111) [universal-darwin9.0]
</li></ul>
<a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#toc">(top)</a>
<a name="results"> </a>
<h2>Results</h2>
<p>No cheesy graphs this time, just better organized numbers. Each row has one implementation of the problem. The 10**x columns show how many milliseconds it took the implementation to sum the multiples of three and five less than that number. Each implementation was run seven times for each column, and the average runtime is shown below. A test harness was written to execute the scripts automatically; I disabled the screensaver, started the tests, and went to bed.</p>
<table>
  <thead>
    <tr>
      <th>Code</th>
      <th>10**1</th>
      <th>10**2</th>
      <th>10**3</th>
      <th>10**4</th>
      <th>10**5</th>
      <th>10**6</th>
      <th>10**7</th>
      <th>Comments</th>
    </tr>
  </thead>
  <tbody>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_c">first.c</a></td><td>5</td><td>5</td><td>5</td><td>5</td><td>11</td><td>65</td><td>648</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_g1">first.groovy</a></td><td>928</td><td>929</td><td>1065</td><td>1643</td><td>2155</td><td>7998</td><td>52732</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_g2">second.groovy</a></td><td>920</td><td>1004</td><td>1189</td><td>1353</td><td>1806</td><td>3243</td><td>19620</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_g3">third.groovy</a></td><td>914</td><td>880</td><td>936</td><td>1181</td><td>1421</td><td>2545</td><td>12835</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_pl1">first.pl</a></td><td>8</td><td>8</td><td>10</td><td>26</td><td>192</td><td>1886</td><td>18845</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_pl2">second.pl</a></td><td>8</td><td>8</td><td>8</td><td>11</td><td>36</td><td>378</td><td>3062</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_py1">first.py</a></td><td>22</td><td>22</td><td>23</td><td>35</td><td>160</td><td>1506</td><td>14939</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_py2">second.py</a></td><td>147</td><td>22</td><td>21</td><td>24</td><td>53</td><td>422</td><td>4242</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_py3">third.py</a></td><td>22</td><td>22</td><td>22</td><td>24</td><td>51</td><td>405</td><td>4081</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_py4">fourth.py</a></td><td>21</td><td>22</td><td>21</td><td>22</td><td>26</td><td>156</td><td>1580</td><td>Credit goes to Pete <a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#comment4">below</a></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_r1">first.rb</a></td><td>9</td><td>8</td><td>9</td><td>20</td><td>134</td><td>1420</td><td>14288</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_r2">second.rb</a></td><td>9</td><td>8</td><td>9</td><td>17</td><td>100</td><td>1075</td><td>10818</td><td></td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_l">first.el</a></td><td></td><td></td><td></td><td></td><td></td><td></td><td>20141</td><td>10^1...6 not available</td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_l">second.el</a></td><td></td><td></td><td></td><td></td><td></td><td></td><td>8172</td><td>Actually first.elc</td></tr>
    <tr><td><a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#lang_ri">instant.rb</a></td><td>8</td><td>8</td><td>8</td><td>8</td><td>8</td><td>8</td><td>8</td><td></td></tr>
  </tbody>
</table>
<p>
<a name="code"> </a>
</p><h2>Code</h2>
<a name="lang_c"> </a>
<h3>C</h3>
<pre class="prettyprint">#include &lt;stdio.h>
#include &lt;math.h>

#define multiple_of(a, b) ((a == 0 || b == 0) ? 0 : a % b == 0)

int main(int argc, char** argv)
{
    int exp = atoi(argv[1]);
    double sum = 0;
    int i;

    for (i = 3; i &lt; pow(10, exp); i++)
        if (multiple_of(i, 3) || multiple_of(i, 5))
            sum += i;

    printf("%0.0f\n", sum);

    return 0;
}

</pre>
<a name="lang_g"> </a>
<h3>Groovy</h3>
<a name="lang_g1"> </a><pre class="prettyprint">// first.groovy
exp = Integer.parseInt(args[0])

mof = { val, test -> val &amp;&amp; test &amp;&amp; test % val == 0 }
mof3 = mof.curry(3)
mof5 = mof.curry(5)

sum = 0 as BigDecimal

(3..&lt;(10**exp)).each {
    if (mof3(it) || mof5(it)) {
        sum += it
    }
}

println sum
</pre>
<hr>
<a name="lang_g2"> </a><pre class="prettyprint">// second.groovy
def exp = Integer.parseInt(args[0])

def mof = { val, test -> val &amp;&amp; test &amp;&amp; test % val == 0 }
def mof3 = mof.curry(3)
def mof5 = mof.curry(5)

def sum = 0 as BigInteger

(3..&lt;(10**exp)).each {
    if (mof3(it) || mof5(it)) {
        sum += it
    }
}

println sum
</pre>
<hr>
<a name="lang_g3"> </a><pre class="prettyprint">// third.groovy
def exp = Integer.parseInt(args[0])

def sum = 0 as BigInteger

for (int i = 3; i &lt; 10 ** exp; i++)
    if (i % 3 == 0 || i % 5 == 0)
        sum += i

println sum
</pre>
<a name="lang_l"> </a>
<h3>Lisp</h3>
<pre class="prettyprint">; first.el
(defun multiple_of (a b)
  (= 0 (% a b))
)

(defun val-to-add (val)
  (cond
   ((multiple_of val 3) val)
   ((multiple_of val 5) val)
   (0)
   )
  )

(defun sum-of-3or5-multiples (exp)
  (let ((num 3) (sum 0.0))
    (while (&lt; num (expt 10 exp))
      (setq sum (+ sum (val-to-add num)))
      (setq num (1+ num))
      )
    sum
    )
  )

(sum-of-3or5-multiples 7)
</pre>
<a name="lang_pe"> </a>
<h3>Perl</h3>
<a name="lang_pl1"> </a><pre class="prettyprint">#!/usr/bin/env perl -w
# first.pl
use strict;

my $exp = $ARGV[0];
my $sum = 0;

sub multiple_of {
    my ($val, $tgt) = @_;
    return $val % $tgt == 0;
}

for my $i (3 ... 10 ** $exp - 1) {
    if (multiple_of($i, 3) || multiple_of($i, 5)) {
        $sum += $i
    }
}

print "$sum\n"
</pre>
<hr>
<a name="lang_pl2"> </a><pre class="prettyprint">#!/usr/bin/env perl -w
# second.pl

use strict;

my $exp = $ARGV[0];
my $sum = 0;

for my $i (3 ... 10 ** $exp - 1) {
    if ($i % 3 == 0 || $i % 5 == 0) {
        $sum += $i
    }
}

print "$sum\n"
</pre>
<a name="lang_py"> </a>
<h3>Python</h3>
<a name="lang_py1"> </a><pre class="prettyprint"># first.py
import sys

def multiple_checker(val):
    return lambda test: test and val and test % val == 0

mof3 = multiple_checker(3)
mof5 = multiple_checker(5)

sum = 0

for i in range(10 ** int(sys.argv[1])):
    if mof3(i) or mof5(i):
        sum = sum + i

print sum
</pre>
<hr>
<a name="lang_py2"> </a><pre class="prettyprint"># second.py
import sys

exp = int(sys.argv[1])
sum = 0

for mof3or5 in set(range(3, 10**exp, 3)) | set(range(5, 10**exp, 5)):
    sum = sum + mof3or5

print sum
</pre>
<hr>
<a name="lang_py3"> </a><pre class="prettyprint"># third.py
import sys

exp = int(sys.argv[1])
sum = 0

for mof3or5 in set(xrange(3, 10**exp, 3)) | set(xrange(5, 10**exp, 5)):
    sum = sum + mof3or5

print sum
</pre>
<hr>
<a name="lang_py4"> </a><pre class="prettyprint"># fourth.py
import sys

exp = int(sys.argv[1])
total = sum(xrange(3, 10**exp, 3)) + sum(xrange(5, 10**exp, 5)) - sum(xrange(15, 10**exp, 15))

print total
</pre>
<a name="lang_r"> </a>
<h3>Ruby</h3>
<a name="lang_r1"> </a><pre class="prettyprint"># first.rb
exp = ARGV[0].to_i
sum = 0

def is_mult(large, small)
  large % small == 0
end

for i in 3..(10 ** exp - 1)
  next unless is_mult(i, 3) or is_mult(i, 5)
  sum = sum + i
end

puts sum
</pre>
<hr>
<a name="lang_r2"> </a><pre class="prettyprint"># second.rb
exp = ARGV[0].to_i
sum = 0

for i in 3..(10 ** exp - 1)
  next unless i % 3 == 0 or i % 5 == 0
  sum = sum + i
end

puts sum
</pre>
<a href="http://www.nearinfinity.com/blogs/page/seths?entry=projecteuler_problem_1_in_c#toc">(top)</a>
<p>
<a name="facepalm"> </a>
</p><h2>Big O(rly)?</h2>
<p>Well... sigh... all of the code above works correctly but is slow and naïve. All of the approaches above take more time as the largest multiple increases. I was ignorantly, happily tweaking code down this road until fortunately <a href="http://www.nearinfinity.com/blogs/page/rdonaway">Bob</a> clued me in. The <b>best</b> approach takes the same amount of time as the largest multiple increases. Why? There's a simple equation for this, calculating an  <a href="http://en.wikipedia.org/wiki/Evaluating_sums#Arithmetic_series">arithmetic series</a>.
<a name="lang_ri"> </a></p><pre class="prettyprint"># instant.rb
ceil = 10 ** ARGV[0].to_i - 1

def series_of_multiples(val, ceiling)
  diff = val
  vals = ceiling / val
  last_val = val + diff * (vals - 1)
  (val + last_val) / 2.0 * vals
end

def som(v, c) series_of_multiples(v, c).to_i end

puts som(3, ceil) + som(5, ceil) - som(15, ceil)
</pre>

<a name="wrapup"> </a>
<h2>Wrap up</h2>
<ul>
  <li>I got a lot more out of this than a quick glance at Python. It was good to calculate a series or two, but much better to build a little test harness.
  </li><li>Groovy performance tested out well here. I would avoid using some of its features in tight loops. I'm confident that <i>Monsieur LaForge et son amis</i> will optimize that concern away eventually.
  </li><li>I thought I could love it, I really wanted to love it, it's loved by many for many good reasons, but Python started to chafe me. It's so hard to nail down exactly why... it's chock full of goodness, but just seems to need more Kool-Aid than Groovy and especially Ruby. Perl's Kool-Aid threshold is a well-known constant, at least until the <a href="http://www.parrotcode.org/">Parrot</a> changes things drastically.
  </li><li>Cosine similarity + arithmetic series = it's good to work with a friendly, helpful PhD. in math. Thanks Bob :-)
</li></ul>
<h2>Extras</h2>
<p>The Python test harness. Probably needs tweaking for Wintel boxes.
</p><pre class="prettyprint">import sys
import re
from datetime import timedelta, datetime
from os import system

#
# prefix used to run scripts. Trailing whitespace matters!
#
vms = { 
        'el':           'emacs --script ',
        'elc':          'emacs --script ',
        'groovy':       'groovy ',
        'out':          './',
        'pl':           'perl ',
        'py':           'python ',
        'rb':           'ruby '
        }

# Configurable parameters
# 
DEFAULT_MIN = 1
DEFAULT_MAX = 7
min = DEFAULT_MIN       # min "max" val = 10 ** min
max = DEFAULT_MAX       # max "max" val = 10 ** max
reps = 7                # times to repeat each test, then average the results


# Helper method
def td_to_ms(delta):
    val = delta.microseconds / 1000.0
    val = val + delta.seconds * 1000
    val = val + delta.days * 24 * 60 * 60 * 1000
    return val

#
# "main"
#
for script in sys.argv[1:]:
    ext = script.split('.').pop()
    if not ext in vms:
        print 'ignoring', script, 'unrecognized extension'
        continue

    vm = vms[ext]

    # the lisp files hardcode the max values :(
    if re.search('^el', ext):
        max = min
    else: # reset to defaults, needed when running multiple types of tests
        max = DEFAULT_MAX
        min = DEFAULT_MIN

    # gotta like list comprehensions
    runs = [0 for x in range(max - min + 1)]

    for rep in xrange(reps):
        for exp in xrange(min, max + 1):
            start = datetime.now()
            system('%s%s %s >/dev/null' % (vm, script, exp))
            end = datetime.now()
            runs[exp - min] = runs[exp - min] + td_to_ms(end - start)

    for i in xrange(len(runs)):
        runs[i] = int(runs[i] / reps)

    print script.split('/').pop(), runs

    # see, isn't it strange how python leaves you hanging at the end
    # of the last scope in the file?
</pre>]]></description>
            <link>http://www.nearinfinity.com/blogs/seth_schroeder/projecteuler_problem_1_in_c.html</link>
            <guid>http://www.nearinfinity.com/blogs/seth_schroeder/projecteuler_problem_1_in_c.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Java</category>
            
                <category domain="http://www.sixapart.com/ns/types#category">Ruby</category>
            
            
            <pubDate>Tue, 29 Apr 2008 08:37:50 -0500</pubDate>
        </item>
        
        <item>
            <title>Wackiness With String, GString, and Equality in Groovy</title>
            <description><![CDATA[<p>We ran into this one today while writing a Groovy unit test. Check out the following GroovyShell session:</p>

<pre class="prettyprint">groovy:000> test = []
===> []
groovy:000> (1..10).each { test &lt;&lt; "Item $it" }
===> 1..10
groovy:000> test                               
===> [Item 1, Item 2, Item 3, Item 4, Item 5, Item 6, Item 7, Item 8, Item 9, Item 10]
groovy:000> test.contains("Item 1")
===> false
</pre>

<p>Um...what? We started by adding items to a list, e.g. "Item 1", "Item 2", and so on. Then we simply ask whether the list contains an item we know (or think) is there. But no, it prints false! How can <code>test</code> possibly not contain "Item 1?" First, what's going on here? Look at this second example:</p>

<pre class="prettyprint">groovy:000> test = []
===> []
groovy:000> (1..10).each { test &lt;&lt; "Item $it" }
===> 1..10
groovy:000> test
===> [Item 1, Item 2, Item 3, Item 4, Item 5, Item 6, Item 7, Item 8, Item 9, Item 10]
groovy:000> println test[0].class 
class org.codehaus.groovy.runtime.GStringImpl
===> null</pre>

<p>Ah ha! The items in the list aren't strings. So what? Look at this code:</p>

<pre class="prettyprint">groovy:000> a = "Item 2"
===> Item 2
groovy:000> a.class
===> class java.lang.String
groovy:000> n = 2
===> 2
groovy:000> b = "Item $n"
===> Item 2
groovy:000> b.class
===> class org.codehaus.groovy.runtime.GStringImpl
groovy:000> a == b
===> true
groovy:000> b == a
===> true
groovy:000> a.equals(b)
===> false
groovy:000> b.equals(a)
===> false
</pre>

<p><code>a</code> is a normal Java String, whereas <code>b</code> is a Groovy GString. Even more interesting (or perhaps confusing), a <code>==</code> comparison yields true, but a comparison using <code>equals()</code> is false! So back in the original example where we checked if the 'test' list contained 'Item 1', the <code>contains()</code> method (which comes from Java not Groovy) uses <code>equals()</code> to compare the values and responds that in fact, no, the list does not contain the <i>String</i> "Item 1." Without getting too much more detailed, how to fix this? Look at this example:</p>

<pre class="prettyprint">groovy:000> test = []
===> []
groovy:000> (1..10).each { test &lt;&lt; "Item $it".toString() }
===> 1..10
groovy:000> test
===> [Item 1, Item 2, Item 3, Item 4, Item 5, Item 6, Item 7, Item 8, Item 9, Item 10]
groovy:000> test.contains('Item 1')
===> true
</pre>

<p>Now it returns true, since in the above example we explicitly forced evaluation of the GStrings in the list by calling <code>toString()</code>. The Groovy web site <a href="http://groovy.codehaus.org/Strings#Strings-GStrings">explains</a> about GString lazy evaluation stating that "GString uses lazy evaluation so its not until the toString() method is invoked that the GString is evaluated."</p>

<p>Ok, so we now understand <i>why</i> the observed behavior happens. The second question is whether or not this is something likely to confuse the You-Know-What out of developers and whether it should behave differently. To me, this could easily lead to some subtle and difficult to find bugs and I think it should work like a developer expects without requiring an understanding of whether GStrings are lazily-evaluated or not. Lazy evaluation always seems to come at a price, for example in ORM frameworks it can easily result in the "n + 1 selects" problem.</p>

<p>For comparison, let's take a look at similar Ruby example in an irb session:</p>

<pre class="prettyprint">>> test = []
=> []
>> (1..10).each { |n| test &lt;&lt; "Item #{n}" }
=> 1..10
>> test
=> ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10"]
>> test.include? "Item 1"
=> true
</pre>

<p>Ruby "does the right thing" from just looking at the code. Ruby 1, Groovy 0 on this one. I don't actually know whether Ruby strings evaluate the expressions immediately or not, and should not need to care. Code that looks simple should not require understanding the implementation strategy of a particular feature. Otherwise it is broken in my opinion.</p>]]></description>
            <link>http://www.nearinfinity.com/blogs/scott_leberknight/wackiness_with_string_gstring_and.html</link>
            <guid>http://www.nearinfinity.com/blogs/scott_leberknight/wackiness_with_string_gstring_and.html</guid>
            
                <category domain="http://www.sixapart.com/ns/types#category">Groovy</category>
            
            
                <category domain="http://www.sixapart.com/ns/types#tag">groovy</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">GString</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">java</category>
            
                <category domain="http://www.sixapart.com/ns/types#tag">ruby</category>
            
            <pubDate>Thu, 20 Mar 2008 14:44:18 -0500</pubDate>
        </item>
        
    </channel>
</rss>

