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

<channel>
	<title>Eric Lefevre-Ardant on Java &#38; Agile</title>
	<atom:link href="http://ericlefevre.net/wordpress/feed/" rel="self" type="application/rss+xml" />
	<link>http://ericlefevre.net/wordpress</link>
	<description>Eric&#039;s Earnest Elucidations</description>
	<lastBuildDate>Thu, 24 May 2012 19:11:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Refactoring to Fantom</title>
		<link>http://ericlefevre.net/wordpress/2012/05/24/refactoring-to-fantom/</link>
		<comments>http://ericlefevre.net/wordpress/2012/05/24/refactoring-to-fantom/#comments</comments>
		<pubDate>Thu, 24 May 2012 19:00:26 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=1084</guid>
		<description><![CDATA[This post in an introduction to Fantom via the refactoring of Java code. TL; DR: Fantom is basically a better Java with a very similar syntax, but with lots of little simplifications and some powerful features such as functions. Let&#8217;s &#8230; <a href="http://ericlefevre.net/wordpress/2012/05/24/refactoring-to-fantom/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>This post in an introduction to Fantom via the refactoring of Java code.</p>
<p>TL; DR: Fantom is basically a better Java with a very similar syntax, but with lots of little simplifications and some powerful features such as functions.</p>
<p><span id="more-1084"></span><br />
<a title="La citerne-basilique by elefevre7, on Flickr" href="http://www.flickr.com/photos/elefevre/6981450339/"><img class="aligncenter" src="http://farm8.staticflickr.com/7045/6981450339_56b029422a.jpg" alt="La citerne-basilique" width="500" height="333" /></a></p>
<p>Let&#8217;s say you want to implement FooBarQix.</p>
<p>For those not in the know, FooBarQix is a variant of <a href="http://rosettacode.org/wiki/FizzBuzz">FizzBuzz</a> using &#8220;Foo&#8221; in place of &#8220;Fizz&#8221; and &#8220;Bar&#8221; in place of &#8220;Buzz.&#8221; One difference is that &#8220;Qix&#8221; plays the same role as &#8220;Foo&#8221; and &#8220;Bar&#8221; for number 7. Another difference is that digits 3, 5 and 7 also cause the results to contain instances of those words. FooBarQix receives a minor celebrity status in France, in November 2011 as <a href="http://www.code-story.net/2011/11/16/foobarqix.html">part of a competition</a> related to the upcoming Devoxx conference in Paris.</p>
<p>&nbsp;</p>
<p>Here are a sample output (the C-style comments are not part of the output):</p>
<pre>1
2
FooFoo
4
BarBar
Foo
QixQix
8
Foo
Bar
11
Foo
Foo // for 13
Qix
FooBarBar // for 15
...
FooQix // for 21
...
FooFooFoo // for 33
...
FooBar // for 51
Bar
BarFoo // for 53
... // up to 100</pre>
<p>Obviously, there are many different possible implementations. Here is one in Java:</p>
<pre>public class FooBarQix {
	public static void main(String[] args) {
		System.out.println(new FooBarQix().asTextUpTo(100));
	}

	public String asTextUpTo(int topNumber) {
		String str = "";
		for (int i = 1; i &lt; = topNumber; i++) { 			str += toText(i) + "\n"; 		} 		return str; 	} 	public static final String[] TEXT = new String[] { "", "", "", "Foo", "", 			"Bar", "", "Qix", "", "" }; 	public String toText(int number) { 		StringBuffer result = new StringBuffer(); 		addTextForDivisible(number, 3, result); 		addTextForDivisible(number, 5, result); 		addTextForDivisible(number, 7, result); 		addTextForDigits(number, result); 		return result.length() &gt; 0 ? result.toString() : Integer
				.toString(number);
	}

	private void addTextForDivisible(int number, int digit, StringBuffer str) {
		if (number % digit == 0) {
			str.append(TEXT[digit]);
		}
	}

	private void addTextForDigits(int numberToConvert, StringBuffer str) {
		String asString = Integer.toString(numberToConvert);
		for (int i = 0; i &lt; asString.length(); i++) {
			int digit = Integer.parseInt(asString.substring(i, i + 1));
			str.append(TEXT[digit]);
		}
	}
}</pre>
<p>I am going to guide you through a refactoring of this from Java to Fantom.</p>
<h2>Direct translation into Fantom code</h2>
<p>At this stage, there are only minor differences:</p>
<ul>
<li>System.out.println() =&gt; Env.cur.out().printLine</li>
<li>&#8216;=&#8217; =&gt; &#8216;:=&#8217; for field initialization</li>
<li>void =&gt; Void</li>
<li>String =&gt; Str</li>
<li>int =&gt; Int</li>
<li>new FooBarQix() =&gt; FooBarQix()</li>
<li>new String[] {&#8230;} =&gt; Str[...]</li>
<li>.toString() =&gt; .toStr()</li>
<li>StringBuffer =&gt; StrBuf</li>
<li>Integer.toString(number) =&gt; number.toStr()</li>
<li>string.substring(i, i+1) =&gt; string[i..i]</li>
<li>static final =&gt; const</li>
</ul>
<p>Which leads us to the following Fantom class:</p>
<pre>public class FooBarQix {
  public static Void main(Str[] args) {
    Env.cur.out(FooBarQix().asTextUpTo(100));
  }

  public Str asTextUpTo(Int topNumber) {
    Str str := "";
    for (Int i := 1; i &lt; = topNumber; i++) {       str += toText(i) + "\n";     }     return str;   }   public const Str[] TEXT := Str["", "", "", "Foo", "",       "Bar", "", "Qix", "", "" ];   public Str toText(Int number) {     StrBuf result := StrBuf();     addTextForDivisible(number, 3, result);     addTextForDivisible(number, 5, result);     addTextForDivisible(number, 7, result);     addTextForDigits(number, result);     return result.size() &gt; 0 ? result.toStr() : number.toStr();
  }

  private Void addTextForDivisible(Int number, Int digit, StrBuf str) {
    if (number % digit == 0) {
      str.add(TEXT[digit]);
    }
  }

  private Void addTextForDigits(Int numberToConvert, StrBuf str) {
    Str asString := numberToConvert.toStr();
    for (Int i := 0; i &lt; asString.size(); i++) {
      Int digit := Int.fromStr(asString[i..i]);
      str.add(TEXT[digit]);
    }
  }
}</pre>
<p>A couple of notes:</p>
<ul>
<li>Unlike Java, Fantom is a pure object-oriented language, so all Java ints have been converted into normal Fantom objects</li>
<li>Str[...] might look like a Java-style array, but it is actually an instance of Fantom&#8217;s List; a variety of methods is therefore available on its instances</li>
<li>void is spelled Void in Fantom, and is an actual Class, although it has no methods available</li>
</ul>
<h2>Syntactic sugar</h2>
<p>Lots of things are redundant in the Java syntax. Here is how they can be simplified in Fantom.</p>
<ul>
<li>Type inference: it is no longer necessary to declare the type of a variable when it is defined with a typed value</li>
<li>Class and method protection scope defaults to public</li>
<li>Env.cur.out().printLine is commonly just written echo()</li>
<li>semi-colons at the end of the lines are optional</li>
<li>pair of parenthesis on method calls are optional (not on constructor calls, though)</li>
<li>List offers a convenient API that allows the chaining of calls, making the construction much clearer</li>
</ul>
<p>Our code now looks like this:</p>
<pre>class FooBarQix {
  static Void main(Str[] args) {
    echo(FooBarQix().asTextUpTo(100))
  }

  Str asTextUpTo(Int topNumber) {
    str := ""
    for (i := 1; i &lt; = topNumber; i++) {       str += toText(i) + "\n"     }     return str   }   const Str[] TEXT := Str[,].fill("", 10).set(3, "Foo").set(5, "Bar").set(7, "Qix")   Str toText(Int number) {     result := StrBuf()     addTextForDivisible(number, 3, result)     addTextForDivisible(number, 5, result)     addTextForDivisible(number, 7, result)     addTextForDigits(number, result)     return result.size &gt; 0 ? result.toStr : number.toStr
  }

  private Void addTextForDivisible(Int number, Int digit, StrBuf str) {
    if (number % digit == 0) {
      str.add(TEXT[digit])
    }
  }

  private Void addTextForDigits(Int numberToConvert, StrBuf str) {
    asString := numberToConvert.toStr
    for (Int i := 0; i &lt; asString.size; i++) {
      Int digit := Int.fromStr(asString[i..i])
      str.add(TEXT[digit])
    }
  }
}</pre>
<h2>Functions as first class objects</h2>
<p>One of the main differences with Java is that functions are available to pass around to other methods. This will be possible in Java 8 sometime in 2013. This has been available on the JVM with Fantom since 2005.<br />
One common way of using a function is via the each()  and map() methods, available on collections, strings, and others.</p>
<p>We&#8217;ll also take this opportunity to replace the list of values by a map. We could have done that in Java as well. However, this construct is a lot more common in a functional language (that is, one where functions are first-class). There is also a nice Map.get() that can take a default value.</p>
<pre>class FooBarQix {
  static Void main(Str[] args) {
    echo(FooBarQix().asTextUpTo(100))
  }

  Str asTextUpTo(Int topNumber) {
    return (1..100).map |Int n| { toText(n) }.join("\n")
  }

  const Map TEXT := [3:"Foo", 5:"Bar", 7:"Qix"]

  Str toText(Int number) {
    result := StrBuf()
    addTextForDivisible(number, 3, result)
    addTextForDivisible(number, 5, result)
    addTextForDivisible(number, 7, result)
    addTextForDigits(number, result)

    return result.size &gt; 0 ? result.toStr : number.toStr
  }

  private Void addTextForDivisible(Int number, Int digit, StrBuf str) {
    if (number % digit == 0) {
      str.add(TEXT[digit])
    }
  }

  private Void addTextForDigits(Int numberToConvert, StrBuf str) {
    numberToConvert.toStr.each |c| { str.add(TEXT.get(c.fromDigit, "")) }
  }
}</pre>
<h2>Completing the work</h2>
<p>A couple of things still bother me: the 3, 5, and 7 digits are repeated in two places. The other thing is that we carry around a string buffer, which is not very elegant.</p>
<p>To remove the string buffer, we&#8217;ll get each method to return a computed partial string and concatenate the results.</p>
<p>As for the redundant digits, we&#8217;ll use the ones already defined in the map of values&#8230; and functions will be put to good and make it really easy to transform those values into strings.</p>
<p>As a additional syntactic sugar, we can omit the generic part of a function signature (when passed to map()) and use &#8220;it&#8221; as a placeholder for the parameter &#8212; or even nothing when there are no ambiguities.</p>
<p>Here is the final result:</p>
<pre>class FooBarQix {
  static Void main(Str[] args) {
    echo(FooBarQix().asTextUpTo(100))
  }

  Str asTextUpTo(Int topNumber) {
    return (1..100).map { toText(it) }.join("\n")
  }

  const Map TEXT := [3:"Foo", 5:"Bar", 7:"Qix"]

  Str toText(Int number) {
    Str result := addTextForDivisibles(number) + addTextForDigits(number)

    return result.size &gt; 0 ? result : number.toStr
  }

  private Str addTextForDivisibles(Int number) {
    return TEXT.keys.map |Int digit -&gt; Str?| { number % digit == 0 ? TEXT[digit] : "" }.join
  }

  private Str addTextForDigits(Int numberToConvert) {
    return numberToConvert.toStr.chars.map { TEXT.get(it.fromDigit, "") }.join
  }
}</pre>
<p>To be sure, it is possible to write Java code that gets close to that. This means using additional libraries such as Guava and using kludges such as inner classes in place of functions. However, this is clearly not natural in Java. Maybe that will change with Java 8.</p>
<h2>Final thoughts</h2>
<p>This post has not addressed a number of features offered by Fantom, such as portability (Fantom code can be run both on the .NET CLR and on the JVM), mixins, modules (&#8220;pods&#8221;), and null-safety. However, I hope to have made clear that Fantom is an intriguing language with a pragmatic syntax. This puts the newer kids on the block such as Kotlin and Ceylon really in an interesting light.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2012/05/24/refactoring-to-fantom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A novel way to spam blogs for SEO</title>
		<link>http://ericlefevre.net/wordpress/2012/03/31/a-novel-way-to-spam-blogs-for-seo/</link>
		<comments>http://ericlefevre.net/wordpress/2012/03/31/a-novel-way-to-spam-blogs-for-seo/#comments</comments>
		<pubDate>Sat, 31 Mar 2012 12:21:25 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[misc]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=1075</guid>
		<description><![CDATA[On March 18th, I received the following email: On 18 March 2012 16:26, Jen Rhee &#60;thisisjenica@gmail.com&#62; wrote: Hi Eric, I came across your site and wanted to share my infographic about Wikipedia and how it&#8217;s redefining the way we research. &#8230; <a href="http://ericlefevre.net/wordpress/2012/03/31/a-novel-way-to-spam-blogs-for-seo/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>On March 18th, I received the following email:</p>
<blockquote><p>On 18 March 2012 16:26, Jen Rhee &lt;thisisjenica@gmail.com&gt; wrote:<br />
Hi Eric,</p>
<p>I came across your site and wanted to share my infographic about Wikipedia and how it&#8217;s redefining the way we research. I saw that you had talked about the first wiki developer, Ward Cunningham, which is why I thought you and your readers might find it interesting! Would you be interested in taking a look? Let me know, as I&#8217;d love to get your thoughts on it!</p>
<p>Thanks,<br />
Jen R.</p></blockquote>
<p>I have never heard of that person. I had mentioned Ward Cunningham a couple of times on my blog, although never in relation to wikis. I thought this was a curious email, and decided to ignore it.</p>
<p><span id="more-1075"></span>One week later, I received another email:</p>
<blockquote><p>On 25 March 2012 23:39, Jen Rhee &lt;thisisjenica@gmail.com&gt; wrote:<br />
Hi Eric,</p>
<p>I reached out to you last week and wanted to follow up with you again, in case you missed my email or possibly didn&#8217;t receive it. I&#8217;ve included my original message below:</p>
<p>I came across your site and wanted to share my infographic about Wikipedia and how it&#8217;s redefining the way we research. I saw that you had talked about the first wiki developer, Ward Cunningham, which is why I thought you and your readers might find it interesting! Would you be interested in taking a look? Let me know, as I&#8217;d love to get your thoughts on it!</p>
<p>Thanks again,<br />
Jen</p></blockquote>
<p>I ignored it again.</p>
<p>Finally, I just today received a third email:</p>
<blockquote><p>On 31 March 2012 13:30, Jen Rhee &lt;thisisjenica@gmail.com&gt; wrote:<br />
Hi Eric,</p>
<p>I wanted to follow up once more to see if you received my previous email regarding a graphic I wanted to share about how Wikipedia is redefining the way we research. My team and I created it, and I would love to get your thoughts.</p>
<p>My apologies if you&#8217;ve received my request already, but let me know if you&#8217;d be interested in taking a look.</p>
<p>Much thanks,<br />
Jen</p></blockquote>
<p>This time, I decided to investigate a bit. It didn&#8217;t take me long to find a Twitter account for a certain Jenica Rhee which looks reasonably legit. But it also turns out that <a href="http://blog.tdobson.net/2012/01/infographic-seo-link-bait/">I am not the only one to receive emails from her</a>. There is even <a href="https://plus.google.com/117666625199895400127/posts/B8n1KfZe8Q2">a whole Google+ thread</a> on the topic.</p>
<p>I must admit that this approach is smarter than the usual. The emails I got are really well written for an automated approach (could there be a real human being behind each of them?). The sample infographics I could find seem surprisingly well made (though accuracy is probably debatable). It is also not obvious how they got my email address, as it is not one of the two or three I use the most &#8212; although it is not hard to find it with a bit of Google&#8217;ing.</p>
<p>All in all, rather clever. And spam-worthy.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2012/03/31/a-novel-way-to-spam-blogs-for-seo/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Io Language: adding slots to messages</title>
		<link>http://ericlefevre.net/wordpress/2012/02/06/io-language-adding-slots-to-messages-2/</link>
		<comments>http://ericlefevre.net/wordpress/2012/02/06/io-language-adding-slots-to-messages-2/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 06:08:49 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[misc]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=1061</guid>
		<description><![CDATA[Week 2 of the Seven Languages in Seven Weeks book is about the Io Language. Day 3 is more specifically on how the flow of control (how messages are passed to an object or to its parent) can be hijacked &#8230; <a href="http://ericlefevre.net/wordpress/2012/02/06/io-language-adding-slots-to-messages-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Week 2 of the <a href="http://pragprog.com/book/btlang/seven-languages-in-seven-weeks">Seven Languages in Seven Weeks</a> book is about the <a href="http://iolanguage.com/">Io Language</a>. Day 3 is more specifically on how the flow of control (how messages are passed to an object or to its parent) can be hijacked to create a DSL.</p>
<p>In this post, I am going to describe an interesting feature in Io, and how I extended it a bit to enhance an XML generator.</p>
<p><span id="more-1061"></span>In the example provided, the following Io code:</p>
<pre>Builder ul(
  li("Io"),
  li("Lua"),
  li("JavaScript"))</pre>
<p>can generate the following output:</p>
<pre>&lt;ul&gt;
&lt;li&gt;
Io
&lt;/li&gt;
&lt;li&gt;
Lua
&lt;/li&gt;
&lt;li&gt;
JavaScript
&lt;/li&gt;
&lt;/ul&gt;</pre>
<p>This is made possible by redefining the <em>forward</em> method (&#8220;slot&#8221; in the terminology of Io), which is responsible for deciding who to apply the method calls (&#8220;message calls&#8221; in Io) to.<br />
The other key thing is that it is possible to obtain the details on a message call, even when this message is not defined, a bit like what <a href="http://apidock.com/ruby/BasicObject/method_missing">method_missing</a> does in Ruby. This is done using <em>call message</em>.</p>
<p>For example, while this would be a normal method definition:</p>
<pre>Builder myMethod := method("I have been called" println)</pre>
<p>you could also do it awkwardly by redefining <em>forward</em> and using <em>call message</em>:</p>
<pre>Builder forward := method(if(call message name == "myMethod", "I have been called" println))</pre>
<p>This leads us to the following program (provided in the book) as a way to implement the Builder called in the example:</p>
<pre>Builder := Object clone

Builder forward := method(
	writeln("&lt;", call message name, "&gt;")
	call message arguments foreach(
		arg,
		content := self doMessage(arg);
		if(content type == "Sequence",
			writeln(content)
		)
	)
	writeln("<!--", call message name, "-->")
)</pre>
<p>The exercise was to add indentation dependent on the depth of the tag. It turns out that slots (that is, members of classes or instances) can added to pretty much anything in Io, so I decided to add a <em>depth</em> slot to arguments. Here is the resulting Io code:</p>
<pre>// create a sub-class ("prototype") of Object
Builder := Object clone

// redefine the forward method in order to intercept unknown method ("message") calls
Builder forward := method(
	// if the message does not have a "depth" attribute ("slot"), add it
	call message hasLocalSlot("depth") ifFalse(call message depth := 0)
	// indentation is "depth"-times a tab
	indent := "\t" repeated(call message depth)
	// open an XML tag, the name being the name of the message,
	// preceded by the indentation
	writeln(indent, "&lt;", call message name, "&gt;")
	// loop on each of the arguments of the message
	call message arguments foreach(
		arg,
		// increase the depth level for the sub-message call
		arg depth := call message depth + 1;
		// call the message represented by the argument on the current instance
		// (or on the current prototype, as it is the case here)
		content := self doMessage(arg);
		// check if the argument turns out to be a normal String
		if(content type == "Sequence",
			// prints the value of the argument, preceded by the indentation
			writeln(indent, content)
		)
	)
	// closes the XML tag
	writeln(indent, "<!--", call message name, "-->")
)</pre>
<p>With this, the folllowing code</p>
<pre>Builder p (
	ul(
		li("Io"),
		li("Lua"),
		li("JavaScript")
	)
)</pre>
<p>produces this result:</p>
<pre>&lt;p&gt;
	&lt;ul&gt;
		&lt;li&gt;
		Io
		&lt;/li&gt;
		&lt;li&gt;
		Lua
		&lt;/li&gt;
		&lt;li&gt;
		JavaScript
		&lt;/li&gt;
	&lt;/ul&gt;
&lt;/p&gt;</pre>
<p>To sum up, we have created a DSL by redefining the way methods are called, introspecting the method call, and finally added a parameter to the method call (!).</p>
<p>If you want to read more about this technique, check out <a href="http://www.bennadel.com/blog/2067-Seven-Languages-In-Seven-Weeks-Io-Day-3.htm">this other post on Io in the 7 Languages book</a>. Curiously, Ben Nadel uses a variable on the Builder to store the current depth. That works, but it seems to me that it behaves just like a global variable, which wouldn&#8217;t be thread-safe. Also, I rather like associating a tag to its corresponding depth.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2012/02/06/io-language-adding-slots-to-messages-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Create hidden files in Apache VFS with the RAM filesystem type</title>
		<link>http://ericlefevre.net/wordpress/2012/02/02/create-hidden-files-in-apache-vfs-with-the-ram-filesystem-type/</link>
		<comments>http://ericlefevre.net/wordpress/2012/02/02/create-hidden-files-in-apache-vfs-with-the-ram-filesystem-type/#comments</comments>
		<pubDate>Thu, 02 Feb 2012 09:57:47 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[test]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=1034</guid>
		<description><![CDATA[Apache VFS is a great way to access different file systems in the same way. I particularly like the custom RAM filesystem in my unit tests in order to check code that eventually accesses the actual file system. For example: &#8230; <a href="http://ericlefevre.net/wordpress/2012/02/02/create-hidden-files-in-apache-vfs-with-the-ram-filesystem-type/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://commons.apache.org/vfs/">Apache VFS</a> is a great way to access different file systems in the same way. I particularly like the custom <a href="http://commons.apache.org/vfs/filesystems.html">RAM filesystem</a> in my unit tests in order to check code that eventually accesses the actual file system.</p>
<p>For example:</p>
<pre>StandardFileSystemManager manager = new StandardFileSystemManager();
manager.init();
manager.resolveFile("ram://root/file.txt").createFile(); // prepare test harness
...
manager.resolveFile("ram://root/file.txt").getName(); // do something useful</pre>
<p>Annoyingly, Apache VFS API provides a way to check if a file/folder is hidden, but, although it is always possible to manually create hidden files on your system, there is no way to mark a file as hidden in the RAM filesystem.</p>
<pre>manager.resolveFile("ram://root/file.txt").isHidden(); // returns false
manager.resolveFile("ram://root/.file.txt").isHidden(); // also returns false</pre>
<p>The solution is to modify the RAM filesystem and customize its checking of the hidden attribute. This means that we need a new RamFileProvider, a new RamFileSystem and finally a new RamFileObject.</p>
<p><span id="more-1034"></span>In this example, all files and folders whose names start with a dot will be considered hidden:</p>
<pre>public class RamFileProvider extends org.apache.commons.vfs2.provider.ram.RamFileProvider {
  @Override
  protected FileSystem doCreateFileSystem(FileName name, FileSystemOptions fileSystemOptions) throws FileSystemException {
    return new RamFileSystem(name, fileSystemOptions);
  }

  private static class RamFileSystem extends org.apache.commons.vfs2.provider.ram.RamFileSystem {
    public RamFileSystem(FileName rootName, FileSystemOptions fileSystemOptions) {
      super(rootName, fileSystemOptions);
    }

    @Override
    protected FileObject createFile(AbstractFileName name) throws Exception {
      return new RamFileObject(name, this);
    }
  }

  private static class RamFileObject extends org.apache.commons.vfs2.provider.ram.RamFileObject {
    public RamFileObject(AbstractFileName name, RamFileSystem ramFileSystemWithHiddenSupport) {
      super(name, ramFileSystemWithHiddenSupport);
    }

    @Override
    public boolean isHidden() throws FileSystemException {
      // this is the important part
      if (getName().getBaseName().startsWith(".")) {
        return true;
      }
      return super.isHidden(); // in practice, this always return false
    }
  }
}</pre>
<p>Finally, this new RamFileProvider must be registered with your existing FileSystemManager. In my case, I get something like that:</p>
<pre>StandardFileSystemManager manager = new StandardFileSystemManager();
manager.init();
manager.addProvider("ram-ext", new RamFileProvider());
manager.resolveFile("ram-ext:///root/file.txt").createFile();
manager.resolveFile("ram-ext:///root/.file.txt").createFile();
...
manager.resolveFile("ram-ext://root/file.txt").isHidden(); // returns false
manager.resolveFile("ram-ext://root/.file.txt").isHidden(); // returns true</pre>
<p>Note that I did not replace the &#8220;ram&#8221; filesystem entirely. Although that would have been my preferred option, that would have taken too much time in my little experiment.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2012/02/02/create-hidden-files-in-apache-vfs-with-the-ram-filesystem-type/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cleaning up test code</title>
		<link>http://ericlefevre.net/wordpress/2012/01/27/cleaning-up-test-code/</link>
		<comments>http://ericlefevre.net/wordpress/2012/01/27/cleaning-up-test-code/#comments</comments>
		<pubDate>Fri, 27 Jan 2012 17:52:03 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=1028</guid>
		<description><![CDATA[My former colleague David just posted an example of verbose test code on his blog (the parts in French have been translated to English by myself): /** * */ @Test public void testGetCustomerOK() { LOGGER.info("======= testGetCustomerOK starting..."); try { CustomerDTO &#8230; <a href="http://ericlefevre.net/wordpress/2012/01/27/cleaning-up-test-code/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>My former colleague <a href="https://twitter.com/#!/dgageot">David</a> just posted an <a href="http://blog.javabien.net/2012/01/27/unit-test-verbosity/">example of verbose test code on his blog</a> (the parts in French have been translated to English by myself):</p>
<pre>/**
 *
 */
@Test
public void testGetCustomerOK() {

  LOGGER.info("======= testGetCustomerOK starting...");

  try {
    CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

    // Check.
    Assert.assertNotNull("Extra not found.", targetDTO);
    Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());

  } catch (CustomerBusinessException exception) {
    LOGGER.error("CustomerBusinessException : {}",
	    exception.getCause());
    Assert.fail(exception.getMessage());
  } catch (UnavailableResourceException exception) {
    LOGGER.error("UnavailableResourceException : {}",
	    exception.getMessage());
    Assert.fail(exception.getMessage());
  } catch (UnexpectedException exception) {
    LOGGER.error("UnexpectedException : {}" +
	    exception.getMessage());
    Assert.fail(exception.getMessage());
  } catch (Exception exception) {
    LOGGER.error("CRASH : " + exception.getMessage());
    Assert.fail(exception.getMessage());
  }

  LOGGER.info("======= testGetCustomerOK done.");
}</pre>
<p>Let&#8217;s see what I&#8217;d do with that.</p>
<p><span id="more-1028"></span>Facing this code, the first thing I would do is remove the logs in the catch clauses, which are clearly obscuring the code the most. They do not provide actual value, since the exception message is used in Assert.fail() calls.</p>
<pre>/**
 *
 */
@Test
public void testGetCustomerOK() {

  LOGGER.info("======= testGetCustomerOK starting...");

  try {
    CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

    // Check.
    Assert.assertNotNull("Extra not found.", targetDTO);
    Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());

  } catch (CustomerBusinessException exception) {
    Assert.fail(exception.getMessage());
  } catch (UnavailableResourceException exception) {
    Assert.fail(exception.getMessage());
  } catch (UnexpectedException exception) {
    Assert.fail(exception.getMessage());
  } catch (Exception exception) {
    Assert.fail(exception.getMessage());
  }

  LOGGER.info("======= testGetCustomerOK done.");
}</pre>
<p>Next, the catching of exceptions and calling Assert.fail() is in fact the same work that the test runner actually does. We can let the test runner handle those cases:</p>
<pre>/**
 *
 */
@Test
public void testGetCustomerOK() throws Exception {

  LOGGER.info("======= testGetCustomerOK starting...");

  CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

  // Check.
  Assert.assertNotNull("Extra not found.", targetDTO);
  Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());

  LOGGER.info("======= testGetCustomerOK done.");
}</pre>
<p>The remaining logs are actually information that can already be known from the test runner, since test results are presented by methods. My guess is that they were added to make the previous logs more readable. They can go now:</p>
<pre>/**
 *
 */
@Test
public void testGetCustomerOK() throws Exception {
  CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

  // Check.
  Assert.assertNotNull("Extra not found.", targetDTO);
  Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());
}</pre>
<p>The &#8220;check&#8221; comment serves no useful purpose. Also, there is an empty comment that obviously adds no value:</p>
<pre>@Test
public void testGetCustomerOK() throws Exception {
  CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

  Assert.assertNotNull("Extra not found.", targetDTO);
  Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());
}</pre>
<p>We are down to 6 lines of code. The first assert does a check that is also done implicitely by the following one. That seems redundant. Also, it is clearly a situation that should <em>not</em> happen in a normal test run. That can go:</p>
<pre>@Test
public void testGetCustomerOK() throws Exception {
  CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

  Assert.assertEquals("accountIds must be the same.", "ABC99", targetDTO.getAccountId());
}</pre>
<p>The remaining assertion has a comment that says what the test does. In some way, there is some value in this. However, in most (all?) cases, the person seeing the error would open the test class anyway and read the code. The test comment seems redundant. At the very least, its value is far from clear. In those situations, I remove the comments:</p>
<pre>@Test
public void testGetCustomerOK() throws Exception {
  CustomerDTO targetDTO = this.serviceImpl.getCustomer("ABC99");

  Assert.assertEquals("ABC99", targetDTO.getAccountId());
}</pre>
<p>OK, a little inlining can now be done:</p>
<pre>@Test
public void testGetCustomerOK() throws Exception {
  Assert.assertEquals("ABC99", this.serviceImpl.getCustomer("ABC99").getAccountId());
}</pre>
<p>The Assert.assertEquals method can also be statically imported:</p>
<pre>@Test
public void testGetCustomerOK() throws Exception {
  assertEquals("ABC99", this.serviceImpl.getCustomer("ABC99").getAccountId());
}</pre>
<p>And the test could use a renaming:</p>
<pre>@Test
public void can_obtain_a_customer_by_account_id() throws Exception {
  assertEquals("ABC99", this.serviceImpl.getCustomer("ABC99").getAccountId());
}</pre>
<p>Hm&#8230; the &#8220;this.&#8221; clause is not really necessary:</p>
<pre>@Test
public void can_obtain_a_customer_by_account_id() throws Exception {
  assertEquals("ABC99", serviceImpl.getCustomer("ABC99").getAccountId());
}</pre>
<p>And&#8230; that&#8217;s it. I&#8217;m down to 4 lines of code. There might be fewer comments, but I believe the result is a lot more readable.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2012/01/27/cleaning-up-test-code/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>More data on productivity of small teams</title>
		<link>http://ericlefevre.net/wordpress/2012/01/13/more-data-on-productivity-of-small-teams/</link>
		<comments>http://ericlefevre.net/wordpress/2012/01/13/more-data-on-productivity-of-small-teams/#comments</comments>
		<pubDate>Fri, 13 Jan 2012 09:44:17 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=1002</guid>
		<description><![CDATA[&#8220;Adding manpower to a late software project makes it later&#8221;. The so-called Brooks&#8217;s Law on productivity of software project is well known, since Fred Brooks&#8217; seminal work The Mythical Man-Month, first published in 1975. That is one of the reasons &#8230; <a href="http://ericlefevre.net/wordpress/2012/01/13/more-data-on-productivity-of-small-teams/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>&#8220;Adding manpower to a late software project makes it later&#8221;. The so-called <a href="http://en.wikipedia.org/wiki/Brooks%27s_law">Brooks&#8217;s Law</a> on productivity of software project is well known, since Fred Brooks&#8217; seminal work <a href="http://en.wikipedia.org/wiki/The_Mythical_Man-Month">The Mythical Man-Month</a>, first published in 1975.</p>
<p>That is one of the reasons I&#8217;m wince a little when a company talks about plans to hire lots of software developers.</p>
<p>This <a href="http://www.qsm.com/risk_02.html">recent study by QSM</a> seems to prove me right. Its conclusion seems to be that Brooks&#8217;s Law can be extended to projects that are not late. At any rate, code is not produced at a faster pace with more manpower.</p>
<p><span id="more-1002"></span><br />
<a title="Corridor by elefevre7, on Flickr" href="http://www.flickr.com/photos/elefevre/5736672222/"><img class="aligncenter" src="http://farm4.staticflickr.com/3587/5736672222_ce521502ca.jpg" alt="Corridor" width="500" height="500" /></a>The idea was to compare the time require to build a 100,000 lines projects, depending on the size of the teal. Results are :</p>
<ul>
<li>32-people teams : 8.9 months</li>
<li>4-people teams : 9.1 months</li>
</ul>
<p>That&#8217;s a one-week difference. 2-3%!</p>
<p>Costs are obviously much in favor of small teams (roughly 8 times cheaper for the same result!). One of the reasons suggested could be that large teams produce many more bugs.</p>
<p>Unfortunately, there are no discussions on other possible explanations, such as complexity in coordinating, communication, the number of managers, location over multiple rooms or sites, skills, turnover, size of the company&#8230; I would have also liked to see other sizes compared. Is there a productivity peak at 2 people ? 6 ? 4 ?</p>
<p>A few years ago, I got into a discussion where one of the persons remarked: &#8220;managing large teams is hard!&#8221; As far as as I&#8217;m concerned, the answer seems to be: &#8220;well, don&#8217;t do it, then.&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2012/01/13/more-data-on-productivity-of-small-teams/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Worse than static methods or final classes?</title>
		<link>http://ericlefevre.net/wordpress/2011/11/28/worse-than-static-methods-or-final-classes/</link>
		<comments>http://ericlefevre.net/wordpress/2011/11/28/worse-than-static-methods-or-final-classes/#comments</comments>
		<pubDate>Mon, 28 Nov 2011 09:53:56 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=911</guid>
		<description><![CDATA[Do you know what&#8217;s worse that static methods or classes marked as final? I&#8217;ll tell you what&#8217;s worse: static methods that return final classes. That only provides private constructors. Here I was, merrily testing my way through a piece of &#8230; <a href="http://ericlefevre.net/wordpress/2011/11/28/worse-than-static-methods-or-final-classes/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Do you know what&#8217;s worse that static methods or classes marked as final? I&#8217;ll tell you what&#8217;s worse: static methods that return final classes. That only provides private constructors.</p>
<p>Here I was, merrily testing my way through a piece of software that sends emails. According to the Java Mail documentation, you are supposed to first create an email session as follows:</p>
<pre>Session mailSession = Session.getInstance(properties);</pre>
<p>(it is worth noting that all what the getInstance() method does is call the private constructor for Session: new Session(props, null)).<br />
Had Session been a more normal class, I could have mocked it like that:</p>
<pre>Session mockSession = mock(Session.class);</pre>
<p>and probably checked how it is being passed around like this:</p>
<pre>verify(someService).startEmailSession(mockSession);</pre>
<p>What follows is what I have to do instead.</p>
<p><strong><span id="more-911"></span>The case of static methods</strong></p>
<p>If getInstance() had been an instance method, I would have been able to mock it:</p>
<pre>Session mockSessionProvider = mock(Session.class);
Session mockSessionInstance = mock(Session.class);
when(mockSessionProvider.getInstance()).thenReturn(mockSessionInstance);</pre>
<p>Unfortunately, a static method cannot easily be mocked with Mockito (other mocking frameworks support that, but I believe they make the tests too obscure). So, first step: create a wrapper class just for the builder method.</p>
<pre>public class SessionProvider {
	public Session getInstance(Properties properties) {
		return Session.getInstance(properties);
	}
}</pre>
<p><strong>The case of final classes</strong></p>
<p>So far, so (relatively) good. However, since Session is a final class, the usual mocking mecanism under Mockito does not work:</p>
<pre>SessionProvider mockSessionProvider = mock(SessionProvider.class);
Session mockSessionInstance = mock(Session.class); // fails because Session is final
when(mockSessionProvider.getInstance()).thenReturn(mockSessionInstance);</pre>
<p><strong>The case of private constructors</strong></p>
<p>Another option would have been to instantiate the session instance, but that fails too, since the constructor is private:</p>
<pre>SessionProvider mockSessionProvider = mock(SessionProvider.class);
Session sessionInstance = new Session(properties, null); // fails because constructor is private
when(mockSessionProvider.getInstance()).thenReturn(sessionInstance);</pre>
<p>A third way might have been to call the original Session.getInstance() to create the test object:</p>
<pre>SessionProvider mockSessionProvider = mock(SessionProvider.class);
Session sessionInstance = Session.getInstance(properties);
when(mockSessionProvider.getInstance()).thenReturn(sessionInstance);</pre>
<p>That would work, but that also opens a whole new can of worms. Session does not implement the equals() method, so if I want to check the value of the Session instance passed around, I must either:</p>
<ul>
<li>compare with the pointer to the sessionInstance &#8212; the issue is that there is no way to check that the session has not been changed (any call to a setter method on the session instance will have no effect on the comparison of pointers)</li>
<li>implement a generic deep equal matcher for Mockito &#8212; something we did at my company, but that I am reluctant to do myself</li>
<li>use an argument captor to catch the instance passed and test &#8212; which produces a fair amount of awkward lines of test</li>
<li>create a custom argument matcher &#8212; which hides the comparison in a separate class or method</li>
<li>yet another is to wrap the instance of Session in yet another class, such as SessionInstance &#8212; which would require us to also wrap any service that takes an instance of Session</li>
</ul>
<p>So we also need a wrapper for the Session instance:</p>
<pre>public class SessionInstance {
	private final Session session;

	public SessionInstance(Session session) {
		this.session = session;
	}

	public Session getSession() {
		return session;
	}
}</pre>
<p>Which forces us to change the SessionProvider:</p>
<pre>public class SessionProvider {
	public SessionInstance getInstance(Properties properties) {
		return new SessionInstance(Session.getInstance(properties));
	}
}</pre>
<p>At last, we can mock this way:</p>
<pre>SessionProvider mockSessionProvider = mock(SessionProvider.class);
SessionInstance mockSessionInstance = mock(SessionInstance.class);
when(mockSessionProvider.getInstance()).thenReturn(mockSessionInstance);</pre>
<p>Done? Hardly. All other, possibly mockable, classes from third-parties that rely on instances of Session must now also by wrapper. For example, a third-party JavaMailTransport that requires an instance of Session now needs its own wrapper if I want to test it. Sigh&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2011/11/28/worse-than-static-methods-or-final-classes/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>I avoid method variables in my test methods</title>
		<link>http://ericlefevre.net/wordpress/2011/11/24/i-avoid-method-variables-in-my-test-methods/</link>
		<comments>http://ericlefevre.net/wordpress/2011/11/24/i-avoid-method-variables-in-my-test-methods/#comments</comments>
		<pubDate>Thu, 24 Nov 2011 11:04:01 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=982</guid>
		<description><![CDATA[Here is a typical example of a test method @Test public void should_search_by_path() { Searcher searcher = new Searcher(); Path location = new Path("somewhere"); String data = "data"; searcher.putAt(data, location); assertThat(searcher.findAt(location), is(data)); } It seems that many developers consider this &#8230; <a href="http://ericlefevre.net/wordpress/2011/11/24/i-avoid-method-variables-in-my-test-methods/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Here is a typical example of a test method</p>
<pre>@Test
public void should_search_by_path() {
	Searcher searcher = new Searcher();
	Path location = new Path("somewhere");
	String data = "data";

	searcher.putAt(data, location);

	assertThat(searcher.findAt(location), is(data));
}</pre>
<p>It seems that many developers consider this good code. I don&#8217;t. My main gripe here is that the presence of variables does not add much useful information. Instead, they make the code too verbose.</p>
<p>A first rewrite would produce something like that:</p>
<pre>@Test
public void should_search_by_path() {
	Searcher searcher = new Searcher();
	searcher.putAt("data", new Path("somewhere"));

	assertThat(searcher.findAt(new Path("somewhere")), is("data"));
}</pre>
<p>Shorter, which is good. I also like the fact it makes clear that it is the <em>value</em> of the parameters that matter, and not their <em>pointers</em>.<br />
We can go further by leveraging local static methods.</p>
<pre>@Test
public void should_search_by_path() {
	Searcher searcher = new Searcher();
	searcher.putAt("data", path("somewhere"));

	assertThat(searcher.findAt(path("somewhere")), is("data"));
}

private static Path path(String path) {
	return new Path(path);
}</pre>
<p>(a static method is not mandatory, but I think it makes its intention of being a utility method clearer)<br />
And, finally, if this test class is dedicated to the Searcher class, I would probably make the searcher variable a field, as it would be used in most test methods.</p>
<pre>private Searcher searcher = new Searcher();

@Test
public void should_search_by_path() {
	searcher.putAt("data", path("somewhere"));

	assertThat(searcher.findAt(path("somewhere")), is("data"));
}

private static Path path(String path) {
	return new Path(path);
}</pre>
<p>This is more lines than the original example. However, the searcher variable is on top of the class and the path() method is at the bottom, far out of the way of the test methods. Indeed, I would often have several such static methods at the bottom of my classes (and, rarely, one or two more instance variables at the top). I even tend to do so when I have such a single method using them.</p>
<p>Beside the fact that the method has fewer lines, I also like that it makes for more fluent code. It almost reads like a story &#8220;when the searcher is being put a String of value &#8216;data&#8217; at the path of name &#8216;somewhere&#8217;, then it should be able to assert that the String found at the path of name &#8216;somewhere&#8217; has value &#8216;data&#8217;&#8221;.</p>
<p>Another example, so that my position is clear:</p>
<pre>@Test
public void should_find_by_address() {
	String aValidAddress = "10 Downing Street";
	Person aPerson = new Person("David Cameron");
	contacts.put(aValidAddress, aPerson);

	assertThat(contacts.get(aValidAddress), is(aPerson));
}</pre>
<p>I&#8217;d very much rewrite this as follows:</p>
<pre>@Test
public void should_be_able_to_find__a_person_when_storing_with_a_valid_address() {
	contacts.put("10 Downing Street", person("David Cameron"));

	assertThat(contacts.get("10 Downing Street"), is(person("David Cameron")));
}</pre>
<p>Any thoughts?</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2011/11/24/i-avoid-method-variables-in-my-test-methods/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Java&#8217;s varargs are for unit tests</title>
		<link>http://ericlefevre.net/wordpress/2011/11/21/javas-varargs-are-for-unit-tests/</link>
		<comments>http://ericlefevre.net/wordpress/2011/11/21/javas-varargs-are-for-unit-tests/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 16:53:30 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[conferences]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=947</guid>
		<description><![CDATA[At Devoxx last week, Joshua Bloch argued during his talk &#8220;The Evolution of Java: Past, Present, and Future&#8221; that varargs are only &#8220;somewhat useful&#8221;. I think he is overlooking some usages, particularly in tests. Here is my case. A reminder &#8230; <a href="http://ericlefevre.net/wordpress/2011/11/21/javas-varargs-are-for-unit-tests/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At <a href="http://www.devoxx.com/">Devoxx</a> last week, Joshua Bloch argued during his talk &#8220;The Evolution of Java: Past, Present, and Future&#8221; that varargs are only &#8220;somewhat useful&#8221;. I think he is overlooking some usages, particularly in tests. Here is my case.</p>
<p>A reminder on how varargs work: essentially, they allow the last parameter of a method to be made of zero to many values of the same type.<br />
For example, a method like this:</p>
<pre>int max(int... values) {...};</pre>
<p>is used by code like that:</p>
<pre>int maximum = max(1, 2, 7, 0);
int maximum = max(1);</pre>
<p>In truth, that form is only moderately useful in production code. It turns out that, on my projects at least, it is not so common for methods to be called with varying number of parameters. And in those cases, it is often acceptable to simply overload a method with more parameters.</p>
<p>There are however at least two cases where varargs shine.</p>
<p>One is in utilities classes. For example, Math.max() only takes exactly two parameters. Which comparisons between 3 or more elements very awkward. If a varargs had been used, Math.max(3, Math.max(1, 4)) would be written Math.max(3, 1, 4). Agreed, that does not happen that often. But it does occasionally.<br />
(I must admit that I do not understand exactly why Math.max() has not been modified to take a varargs nowadays)</p>
<p>However, the biggest benefit, I believe, is in the writing of tests.<br />
Tests tend to contain lots of variations in the values passed to the code under test. And it is critical to keep the clutter to a minimum.<br />
For example, here is how a typical series of tests might look like</p>
<pre>@Test
public void should_find_the_longest_name_for_a_single_user() {
	List users = new ArrayList();
	users.add(new User("eric"));
	assertThat(findLongestName(users), is("eric"));
}</pre>
<pre>@Test
public void should_find_the_longest_name_when_shorted_is_first() {
	List users = new ArrayList();
	users.add(new User("eric"));
	users.add(new User("cecile"));
	assertThat(findLongestName(users), is("cecile"));
}</pre>
<pre>@Test
public void should_find_the_longest_name_when_longest_is_first() {
	List users = new ArrayList();
	users.add(new User("cecile"));
	users.add(new User("eric"));
	assertThat(findLongestName(users), is("cecile"));
}</pre>
<pre>@Test(expected = RuntimeException.class)
public void should_fail_when_search_for_the_longest_name_with_no_users() {
	assertThat(findLongestName(new ArrayList()), is("eric"));
}</pre>
<p>Of course, they can be made a bit nicer using the varargs in Arrays.asList():</p>
<pre>@Test
public void should_find_the_longest_name_for_a_single_user() {
	assertThat(findLongestName(asList(new User("eric"))), is("eric"));
}

@Test
public void should_find_the_longest_name_when_shorted_is_first() {
	assertThat(findLongestName(asList(new User("eric"),
		new User("cecile"))), is("cecile"));
}

@Test
public void should_find_the_longest_name_when_longest_is_first() {
	assertThat(findLongestName(asList(new User("cecile"),
		new User("eric"))), is("cecile"));
}

@Test(expected = RuntimeException.class)
public void should_fail_when_search_for_the_longest_name_with_no_users() {
	findLongestName(Arrays.asList());
}</pre>
<p>However, the real goodness comes when writing our own builder method:</p>
<pre>private static List users(String... names) {
	List users = new ArrayList();
	for (String name : names) {
		users.add(new User(name));
	}
	return users;
}</pre>
<p>(side note: I like this type of methods to be private -so that I get notified when they are not used anymore- and static -mostly because they look nicer in italic, which makes it clearer that they are not part of the code being tested-)</p>
<p>which allow our tests to become:</p>
<pre>@Test
public void should_find_the_longest_name_for_a_single_user() {
	assertThat(findLongestName(users("eric")), is("eric"));
}

@Test
public void should_find_the_longest_name_when_shorted_is_first() {
	assertThat(findLongestName(users("eric", "cecile")), is("cecile"));
}

@Test
public void should_find_the_longest_name_when_longest_is_first() {
	assertThat(findLongestName(users("cecile", "eric")), is("cecile"));
}

@Test(expected = RuntimeException.class)
public void should_fail_when_search_for_the_longest_name_with_no_users() {
	findLongestName(users());
}</pre>
<p>Tests become a lot shorter, consistent, and easier to read. In fact, at this point, it is worth grouping the tests (at least those that do not throw an exception) into a single one:</p>
<pre>@Test
public void should_find_the_longest_name_for_a_single_user() {
	assertThat(findLongestName(users("eric")), is("eric"));
	assertThat(findLongestName(users("eric", "cecile")), is("cecile"));
	assertThat(findLongestName(users("cecile", "eric")), is("cecile"));
}

@Test(expected = RuntimeException.class)
public void should_fail_when_search_for_the_longest_name_with_no_users() {
	findLongestName(users());
}</pre>
<p>Final note: I prefer not to group those builder methods into a general utilities class &#8212; I tend to duplicate them in each test class. One reason is that I prefer keeping much of the test code close together. Another is that I tend to change the name of the method from test class to test class to make the code more fluent. Also, I think that DRY principles are not as important in the tests as they are in the production code.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2011/11/21/javas-varargs-are-for-unit-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Play Framework and Guice: use providers in Guice modules</title>
		<link>http://ericlefevre.net/wordpress/2011/05/08/play-framework-and-guice-use-providers-in-guice-modules/</link>
		<comments>http://ericlefevre.net/wordpress/2011/05/08/play-framework-and-guice-use-providers-in-guice-modules/#comments</comments>
		<pubDate>Sun, 08 May 2011 20:19:56 +0000</pubDate>
		<dc:creator>Eric Lefevre-Ardant</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[test]]></category>
		<category><![CDATA[guice]]></category>
		<category><![CDATA[play framework]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://ericlefevre.net/wordpress/?p=923</guid>
		<description><![CDATA[Play Framework has a Guice module. Unfortunately, its use is fairly limited compared to what Guice can do. In this post, I describe how it is configured on my current personal project. In general, when I test classes that have &#8230; <a href="http://ericlefevre.net/wordpress/2011/05/08/play-framework-and-guice-use-providers-in-guice-modules/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.playframework.org/">Play Framework</a> has a <a href="http://www.playframework.org/modules/guice">Guice module</a>. Unfortunately, its use is fairly limited compared to what Guice can do. In this post, I describe how it is configured on my current personal project.</p>
<p><a title="Spring in Paris, when days last longer and pianists play in the street by elefevre7, on Flickr" href="http://www.flickr.com/photos/elefevre/5632590160/"><img class="aligncenter" src="http://farm6.static.flickr.com/5269/5632590160_d094d455c4.jpg" alt="Spring in Paris, when days last longer and pianists play in the street" width="500" height="500" /></a></p>
<p>In general, when I test classes that have dependencies, my favorite approach is to pass those dependencies to the constructor:</p>
<pre>public class MyService {
	private final MyDependency myDependency;

	public MyService(MyDependency myDependency) {
		this.myDependency = myDependency;
	}
}</pre>
<p>Which makes creating test harnesses with Mockito reasonably easy:</p>
<pre>
public class MyServiceTest extends UnitTest {
	@Test
	public void shouldComputeAResult() {
		MyDependency mockMyDependency = mock(MyDependency.class);
		when(mockMyDependency.findSomeValue()).thenReturn("some value");

		MyService service = new MyService(mockMyDependency);

		assertThat(service.computeSomething(), equalTo("result"));
	}
}</pre>
<p>However, it appears that Guice, at least under <a href="http://www.playframework.org/modules/guice-1.1.1/home">version 1.1.1 of its Play module</a>, can only be used with Play to inject into static members:</p>
<pre>@InjectSupport
public class MyService {
	@Inject
	static MyDependency myDependency;
	// no constructor (a default constructor will be
	// generated automatically by Play Framework)
}</pre>
<p>The @InjectSupport is what makes the Guice module detect that the class requires dependencies (a class that extends either com.google.inject.AbstractModule or play.modules.guice.GuiceSupport must also be present in the classpath).</p>
<p>This makes it hard to instrument classes under test, as the value for a mock instance of MyDependency is shared amongst all tests that run currently.</p>
<pre>public class MyServiceTest extends UnitTest {
	@Test
	public void shouldComputeAResult() {
		MyDependency mockMyDependency = mock(MyDependency.class);
		when(mockMyDependency.findSomeValue()).thenReturn("some value");

		MyService service = new MyService();
		// static values are brittle;
		// they should not be touched in unit tests
		service.myDependency = mockMyDependency; // yuck!

		assertThat(service.computeSomething(), equalTo("result"));
	}
}</pre>
<p>Many subtle problems may occur when injecting dependencies in this way. For example, all instances of MyServices used concurrently will point to the same dependencies instances, so it is possible that tests will behave in inconsistent ways. Also, it makes it harder to default to sensible (null) dependencies, since tests running in the same JVM will by default use dependencies set by the first test.</p>
<p>The solution I&#8217;m using is to add providers in your Guice module:</p>
<pre>public class GuicyModule extends AbstractModule {
	@Override
	public void configure() {
		// no code needed
	}

	@Provides
	public MyService getMyService(MyDependency myDependency) {
		return new MyService(myDependency);
	}
}</pre>
<p>In this way, you are making sure that the dependencies are passed as you wish. Also, it will not be necessary to add any sort of Guice-related code in my services:</p>
<pre>public class MyService {
	private final MyDependency myDependency;

	public MyService(MyDependency myDependency) {
		this.myDependency = myDependency;
	}
}</pre>
<p>The downside is that you do have a few more lines to maintain, which is never fun. Better than the alternative, though.</p>
<p>My thanks to <a href="http://blog.javabien.net/">David Gageot</a> who told me about providers in Guice.</p>
]]></content:encoded>
			<wfw:commentRss>http://ericlefevre.net/wordpress/2011/05/08/play-framework-and-guice-use-providers-in-guice-modules/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

