<?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>Alexandre Martins &#187; Java</title>
	<atom:link href="http://blog.m.artins.net/category/programming/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.m.artins.net</link>
	<description>On Agile Software Development</description>
	<lastBuildDate>Thu, 12 Aug 2010 20:09:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Hamcrest: Improving Reducer Implementations</title>
		<link>http://blog.m.artins.net/hamcrest-improving-reducer-implementations/</link>
		<comments>http://blog.m.artins.net/hamcrest-improving-reducer-implementations/#comments</comments>
		<pubDate>Tue, 08 Sep 2009 13:22:00 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=253</guid>
		<description><![CDATA[In the beginning of the year I posted about the ways you can use Hamcrest out of test code, together with hamcrest-collections. This combination allows us to write different kinds of matchers to select and reject items from lists, as well as applying map and reduce to them. After a while making use of them [...]]]></description>
			<content:encoded><![CDATA[<p>In the beginning of the year I posted about the ways you can use <a href="http://blog.m.artins.net/hamcrest-out-of-test-code">Hamcrest out of test code</a>, together with hamcrest-collections. This combination allows us to write different kinds of matchers to select and reject items from lists, as well as applying map and reduce to them. After a while making use of them on my current project, I wanted to share what I liked a lot, and what I didn't like a lot. My friend <a href="http://lizdouglass.wordpress.com">Liz Douglass</a> has also written a <a href="http://lizdouglass.wordpress.com/2009/09/07/lists-maps-etc">post sharing our experience</a>, and I will just complement it a bit...</p>
<h2>What I Liked A Lot</h2>
<p>There's no much to write here, as we all know that this combination is quite powerful when you're looking for writing code that reads more like english language, making it much easier to express the intent of your code. Not to mention that we get rid of for loops everywhere in the codebase.</p>
<h2>What I Didn't Liked A Lot</h2>
<p>One aspect I didn't like since the beginning when implementing Reducers is that they are coupled to one specific type. It reduces a list of one type into a result of the same type. And from the <a href="http://en.wikipedia.org/wiki/MapReduce">Wikipedia definition of Map and Reduce</a>... </p>
<p><cite><br />
<strong>"Map" step:</strong> The master node takes the input, chops it up into smaller sub-problems, and distributes those to worker nodes.<br />
</cite></p>
<p><cite><br />
<strong>"Reduce" step:</strong> The master node then takes the answers to all the sub-problems and combines them in a way to get the output - the answer to the problem it was originally trying to solve.<br />
</cite></p>
<p>... we can see that it doesn't mention that the result should be of the same type as the original one, after applying the reducer. And that's exactly what I wanted to do instead. People said I was trying to combine both Map and Reduce into a single implementation. I kind of disagree with that, because the fact that I am reducing a list into a result of a different type, it doesn't mean that I am transforming the original input (like multiplying each item in a list of integers by 2, before concatenating them). Confusing?</p>
<p>Let me try to explain it using an example. Given we have a list of integers...</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
List<Integer> list = Lists.create(1, 2, 3);
</pre>
<p>and that I want to concatenate these numbers into a string. With the current <a href="http://code.google.com/p/hamcrest-collections">hamcrest-collections</a> implementation, that would be possible doing something like...</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
Iterable<String> listOfStrings = FunctionMapper.map(list, new Function<Integer, String>() {
    public String apply(Integer number) {
        return String.valueOf(number);
    }
});

String result = Reduction.reduce(listOfStrings, new Reducer<String>() {
    public String apply(String first, String previous) {
        return first.concat("+").concat(previous);
    }
});

Assert.assertEquals("1+2+3", result);
</pre>
<p>It's quite a lot of code just to concatenate a list of numbers! One day while pairing with <a href="http://watchitlater.com/blog">Tom Czarniecki</a>, we decided to reimplement the <a href="http://code.google.com/p/hamcrest-collections/source/browse/trunk/hamcrest-collections/src/org/hamcrestcollections/Reduction.java">Reduction</a> and <a href="http://code.google.com/p/hamcrest-collections/source/browse/trunk/hamcrest-collections/src/org/hamcrestcollections/Reducer.java">Reducer</a> classes, so that we could create more flexible and simple Reducer implementations, and of course writing almost half the lines of code.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public interface Reducer<T, U> {
    U apply(T first, U previous);
}
</pre>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public class Reduction {

    public static <T, U> U reduce(List<T> list, U initialValue, Reducer<T, U> reducer) {
        U currentValue = initialValue;
        for (T item : list) {
            currentValue = reducer.apply(item, currentValue);
        }
        return currentValue;
    }
}
</pre>
<p>To do the same number concatenation with this new implementation, is just a matter of defining a new Reducer, that concatenates them in a string.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
Assert.assertEquals("1+2+3", Reduction.reduce(list, "", new Reducer<Integer, String>() {
    public String apply(Integer first, String previous) {
        return previous.concat("+").concat(String.valueOf(first));
    }
}));
</pre>
<p>Much simpler!</p>
<h3>Advantages Of This New Implementation</h3>
<ol>
<li>Do I have to mention again that it's much cleaner?</li>
<li>We use java.util.List instead of Iterable.</li>
<li>No exception is thrown if the list to reduce is empty. It just uses the initial value provided on the reducer implementation.</li>
<li>Flexibility to reduce a list into a result of any type.</li>
</ol>
<p>Hope you enjoy it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/hamcrest-improving-reducer-implementations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hamcrest Out Of Test Code!</title>
		<link>http://blog.m.artins.net/hamcrest-out-of-test-code/</link>
		<comments>http://blog.m.artins.net/hamcrest-out-of-test-code/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 12:38:30 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Behaviour-Driven Development]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Domain-Driven Design]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=168</guid>
		<description><![CDATA[It's been a while since I read some interesting posts showing creative uses of Hamcrest library out of test code. Since then I've been proscrastinating to implement my own version, trying strongly typed java delegates. Thankfully this week I came across a nice API called hamcrest-collections. It uses Hamcrest to implement features such as select, [...]]]></description>
			<content:encoded><![CDATA[<p>It's been a while since I read <a href="http://joe.truemesh.com/blog/000705.html">some</a> <a href="http://jroller.com/ghettoJedi/entry/using_hamcrest_for_iterators">interesting</a> <a href="http://cromwellian.blogspot.com/2006/07/fun-with-generics-and-cglib-functional.html">posts</a> showing creative uses of <a href="http://code.google.com/p/hamcrest/">Hamcrest</a> library out of test code. Since then I've been proscrastinating to implement my own version, trying <a href="http://weblogs.java.net/blog/alexwinston/archive/2005/04/strongly_types_1.html">strongly typed java delegates</a>. </p>
<p>Thankfully this week I came across a nice API called <a href="http://code.google.com/p/hamcrest-collections/">hamcrest-collections</a>. It uses Hamcrest to implement features such as <strong><code>select</code></strong>, <strong><code>reject</code></strong>, <strong><code>map</code></strong>, <strong><code>reduce</code></strong> and <strong><code>zip</code></strong> familiar from languages like Ruby and Python. </p>
<h2>Selectors</h2>
<p>Selectors can be used to select or reject items that matches a given Matcher, from any iterable object. It reminds me the <a href="http://martinfowler.com/apsupp/spec.pdf">Specification Pattern</a> from <a href="http://domaindrivendesign.org/">Domain-Driven Design</a>, which is also used for querying objects that satisfies defined specifications.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public static final Person john = new Person("John", 28);
public static final Person nicole = new Person("Nicole", 12);
public static final Person ryan = new Person("Ryan", 23);
public static final Person nathan = new Person("Nathan", 18);

public static final List<Person> list() {
    return Arrays.asList(john, nicole, ryan, nathan);
}</pre>
<p><br/><br />
The code below selects from the list of users defined above, the ones that are under twenty.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
@Test
public void should_select_only_people_under_twenty_years_old() {
    List<Person> users = Person.list();
    Iterable<Person> underTwentyList = select(users, underAge(20));
    assertThat(underTwentyList, hasItems(nicole, nathan));
    assertThat(underTwentyList, not(hasItems(john, ryan)));
}
</pre>
<p><br/><br />
The code below rejects all the users that are under twenty.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
@Test
public void should_reject_every_people_under_twenty_years_old() {
    List<Person> users = Person.list();
    Iterable<Person> aboveTwentyList = reject(users, underAge(20));
    assertThat(aboveTwentyList, hasItems(john, ryan));
    assertThat(aboveTwentyList, not(hasItems(nicole, nathan)));
}</pre>
<p><br/></p>
<h2>Map and Reduce</h2>
<p>Map is used to apply a function onto each item in any iterable object, whereas Reduce combines all these elements, applying a Reducer implementation. In our example, we map the timesTwo function, that doubles each element in the list, and then we reduce it by adding up all of them.</p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
@Test
public void should_double_each_number_in_the_list_then_sum_all_of_them() {
    List<Integer> numbers = Arrays.asList(1, 2, 3);
    MultiplyBy timesTwo = new MultiplyBy(2);

    Iterable<Integer> result = map(numbers, timesTwo);
    assertThat(result, hasItems(2, 4, 6));

    Integer sum = reduce(result, new Sum());
    assertThat(sum, equalTo(12));
}</pre>
<p><br/></p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public class MultiplyBy implements Function<Integer, Integer> {
    private Integer factor;

    public MultiplyBy(Integer factor) {
        this.factor = factor;
    }

    public Integer apply(Integer number) {
        return (int)number * factor;
    }
}</pre>
<p><br/></p>
<pre style="border: solid gray 1px; width: 90%; padding: 10px;">
public class Sum implements Reducer<Integer> {
    public Integer apply(Integer first, Integer second) {
        return first + second;
    }
}</pre>
<p><br/></p>
<p>Despite the bias created by some developers, that Hamcrest should not be used anywhere else but test code, specially after JUnit has defined it as its new matcher library, just ignore it and add these features to your runtime library, so that you can let your creativity drive you when developing. Get rid of "for" loops from your life! <img src='http://blog.m.artins.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/hamcrest-out-of-test-code/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Spring MVC, almost there!</title>
		<link>http://blog.m.artins.net/spring-mvc-almost-there/</link>
		<comments>http://blog.m.artins.net/spring-mvc-almost-there/#comments</comments>
		<pubDate>Tue, 30 Sep 2008 09:07:49 +0000</pubDate>
		<dc:creator>Alexandre Martins</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Spring]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://blog.m.artins.net/?p=94</guid>
		<description><![CDATA[One of the things I really like about Spring 2.5 is the new set of annotations for defining controllers. Now you don't have to extend any superclass to turn your class into a controller, just add the @Controller annotation on the top of the class definition and that's it, you got one (still have to [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things I really like about <a href="http://www.springframework.org/">Spring 2.5</a> is the new set of annotations for defining controllers.<br />
Now you don't have to extend any superclass to turn your class into a controller, just add the <a href="http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/web/portlet/mvc/Controller.html">@Controller</a> annotation on the top of the class definition and that's it, you got one (still have to define it as a bean in the XML file). Another cool feature in this set, is the combination of the <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMapping.html">@RequestMapping</a> and <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestParam.html">@RequestParam</a> annotations.</p>
<pre name="code" class="java">
@Controller
public class ProductController {

	@Autowired
	private MemberRepository repository;

	@RequestMapping(value="/product", method=RequestMethod.GET)
	public String product(@RequestParam(value="id") String id, ModelMap model) {
		model.addAttribute("product", repository.getProduct(id));
		return "product/view";
	}
}
</pre>
<p><a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMapping.html">@RequestMapping</a> gives you flexibility to map methods in the controller to whatever URIs and <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMethod.html">HTTP methods</a> (default to <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestMethod.html#GET">RequestMethod.GET</a>) you like. They are not dependent on another or on controller's name. This really turns things easier when mapping your methods to <a href="http://en.wikipedia.org/wiki/RESTful">RESTful</a> URIs. The only downside in this implementation is that it doesn't allow you to pull out parameters from an URI. If you want to grab some data from the URL, you are going to have to do it the old fashioned way, like:</p>
<p><strong>mystore/product?id=123456</strong></p>
<p>But on the other hand the <a href="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/web/bind/annotation/RequestParam.html">@RequestParam</a> annotation frees you from the dirty job of extracting parameters from a request. Thus, you don't even need to know about the <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletRequest.html">HttpServletRequest</a> and <a href="http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/http/HttpServletResponse.html">HttpServletResponse</a> objects. To retrieve a parameter from a request, just add it as a method parameter and define it as a @RequestParam. The value attribute on the annotation should match the URL parameter name.</p>
<pre name="code" class="java">
@RequestMapping("/products")
public String products(@RequestParam(value="letter", required=false) String letter, ModelMap model) {
	checkLetter(letter);
	model.addAttribute("products", repository.getProducts(letter));
	return "product/list";
}
</pre>
<p>You also have the option of defining a request parameter as required or not (default set to required), so as in the example above, the method would be able to handle requests coming from both <strong>mystore/products</strong>, to list all existent products, and <strong>mystore/products?letter=A</strong>, to list all existent products starting with the letter 'A'. Really neat!</p>
<p>The good news is that Spring 3.0 is coming out next November, and it will include the URI templating functionality. According to <a href="http://www.springify.com/archives/16">Springify</a> blog, you will be able to define a URI like mystore/product/123456, and that will map to the controller method as follows:</p>
<pre name="code" class="java">
@RequestMapping("/product/${id}")
public String product(@RequestParam("id") String id, ModelMap model) {
	model.addAttribute("product", repository.getProduct(id));
	return "product/view";
}
</pre>
<p>So let's wait for it!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.m.artins.net/spring-mvc-almost-there/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
