<?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>Jorge Manrubia &#187; Development</title>
	<atom:link href="http://jorgemanrubia.net/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://jorgemanrubia.net</link>
	<description>Personal Page</description>
	<lastBuildDate>Sat, 26 Jun 2010 07:36:42 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Dependency injection and other Java necessary evils</title>
		<link>http://jorgemanrubia.net/2010/05/30/dependency-injection-and-other-java-necessary-evils/</link>
		<comments>http://jorgemanrubia.net/2010/05/30/dependency-injection-and-other-java-necessary-evils/#comments</comments>
		<pubDate>Sun, 30 May 2010 22:39:14 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/?p=470</guid>
		<description><![CDATA[Lately I often find myself thinking about how much I have changed my mind about Java. For a long time I have been interested in the Java Platform and I have tried to be educated on its good practices, patterns and trends. Today, I can say I am not interested in the Java platform anymore. [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I often find myself thinking about how much I have changed my mind about Java. For a long time I have been interested in the Java Platform and I have tried to be educated on its good practices, patterns and trends. Today, I can say I am not interested in the Java platform anymore. In the process, I have learned the wonders of Ruby, <a href="http://rubyonrails.org/">Rails</a>, true Behavioral-Driven Development and a community full of brilliant developers who consider that beautiful code is a primary goal and that software development has to be fun.</p>

<p>In this post I would like to talk about three recurrent Java features I have changed my mind about in recent times: from loving them I have finished considering them as necessary evils you have to live with.</p>

<ul>
<li>Dependency injection</li>
<li>Strong type system</li>
<li>Object disorientation</li>
</ul>

<h3>Dependency injection</h3>

<p>The <a href="http://martinfowler.com/articles/injection.html">dependency injection (<acronym title="Dependency Injection">DI</acronym>) pattern</a> is about separation of concerns. The concern of wiring object dependencies is extracted from objects and centralized in some kind of factory facility that, using some configuration information on how object are wired together, instantiates and configure these objects for you. This pattern is in the core of <a href="http://www.springsource.org/">Spring</a> and is implemented by <a href="http://code.google.com/p/google-guice/">Google Guice</a>.</p>

<p>So why are <acronym title="Dependency Injection">DI</acronym> solutions so important in Java? I think the main reason is because they are the only way to enable good unit testing. Sure there are other benefits, like minimizing coupling between objects or avoiding to write the same wiring boilerplate code again and again, but these are not as important as testing. While you will hardly find yourself in the need of changing a JDBC <acronym title="Data Access Object">DAO</acronym> for a <acronym title="Java Persistence API">JPA </acronym>one, you will always need to mock dependencies when writing unit tests. And for doing so, you need to isolate these dependencies first.</p>

<p>And the Java <code>new</code> operator makes this task very difficult. It is just so rigid. You don&#8217;t have any mechanism for faking it once it is coded within your objects. The alternative usually implies implementing a full ecosystem of interfaces, their implementations enabling the dependency injection (in the form of constructors or setter methods), and factories for instantiating the configured objects. And since the boilerplate code this approach implies is considerable, you would rather use an external <acronym title="Dependency Injection">DI</acronym> library that makes the work for you. So external <acronym title="Dependency Injection">DI</acronym> solutions are good but, from a testing perspective, they solve a problem created by the Java new operator.</p>

<p>I realized of this problem when I tried to build something serious with Rails. The first thing I did was to look which dependency-injection solutions were available for Rails. I you look for <acronym title="Dependency Injection">DI</acronym> in Rails there is a good chance you end up reading this <a href="http://weblog.jamisbuck.org/2008/11/9/legos-play-doh-and-programming">article by Jamis Buck</a>. That post summarized his clarifying experience with <acronym title="Dependency Injection">DI</acronym> libraries in Ruby:</p>

<ul>
<li>He first created <a href="http://copland.rubyforge.org/">Copland</a>: a port of the Java <a href="http://hivemind.apache.org/">Hivemind</a>.</li>
<li>He then created <a href="http://needle.rubyforge.org/">Needle</a> as a more Ruby-like approach to a <acronym title="Dependency Injection">DI</acronym> solution.</li>
<li>He finally concluded that <acronym title="Dependency Injection">DI</acronym> frameworks are unnecessary in Ruby (he talks about <acronym title="Dependency Injection">DI</acronym> tools, not about the pattern itself).</li>
</ul>

<p>In my opinion, Ruby examples used by Jamis are not the best. I think a key aspect in Ruby is that <code>new</code> is just a class method. This means that classes in Ruby are by definition factories, and you can fake them directly when testing. Let me show you an example with a <code>Person</code> class that depends on <code>Mouth</code>, since to say something, a person has to open his mouth.</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color:#9966CC; font-weight:bold;">class</span> Mouth<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#CC0066; font-weight:bold;">open</span><br />
&nbsp; &nbsp; <span style="color:#996600;">&quot;Very complex, slow and sophisticated processing here&quot;</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span><br />
<br />
<span style="color:#9966CC; font-weight:bold;">class</span> Person<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> say_hi<br />
&nbsp; &nbsp; Mouth.<span style="color:#9900CC;">new</span>.<span style="color:#CC0066; font-weight:bold;">open</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>If you want to test this behavior with RSpec, you would do something like:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">describe <span style="color:#996600;">&quot;Person&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; it <span style="color:#996600;">&quot;should open the mouth to say hi&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; <span style="color:#0066ff; font-weight:bold;">@person</span> = Person.<span style="color:#9900CC;">new</span><br />
&nbsp; &nbsp; mouth = mock<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;mouth&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; mouth.<span style="color:#9900CC;">should_receive</span><span style="color:#006600; font-weight:bold;">&#40;</span>:<span style="color:#CC0066; font-weight:bold;">open</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; Mouth.<span style="color:#9900CC;">should_receive</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:new</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">and_return</span><span style="color:#006600; font-weight:bold;">&#40;</span>mouth<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; <span style="color:#0066ff; font-weight:bold;">@person</span>.<span style="color:#9900CC;">say_hi</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>Since the Ruby <code>new</code> method is just a class method, it can be stubbed the way you want to inject the dependencies. This is a key aspect when testing with Ruby. You get used to it quickly because it is a natural thing from the programmer point of view. What is difficult is to go back to Java after knowing it, because of the big mess you have to create to achieve the same thing.</p>

<p>Another nice feature of Java <acronym title="Dependency Injection">DI</acronym> solutions is that they manage the scope of objects for you. The usual default approach is to create an object each time is requested. But sometimes it is needed to have a singleton scope for some objects. Spring or Guice let you configure the scope in a declarative way and they manage the scope for you. The scope management is a production thing. For testing, you just create the objects you want to test directly.</p>

<p>If you hardcode a singleton object in Java you have to take care of cleaning its state between test cases. And this is just laborious and not elegant. <acronym title="Dependency Injection">DI</acronym> frameworks offers a very nice solution for this problem. In Ruby, you still can test singleton classes because you <a href="http://blog.ardes.com/2006/12/11/testing-singletons-with-ruby">can modify the Singleton module to expose a reset method that regenerates the single instance each time</a>. This solution is possible by dynamic capabilities of Ruby. Again, I think it is nice just to be able to use the singleton object directly.</p>

<p>Another approach for the singleton problem is to have a <a href="http://pivotallabs.com/users/chad/blog/articles/219-avoiding-constants-in-rails">global configuration object as a simple hash</a>. In testing time you can override the contents of the hash. Again, Ruby syntax and symbols make to look nice something that seems scary if you come from the java World.</p>

<p>Regarding the scope problem, the solution offered by <acronym title="Dependency Injection">DI</acronym> frameworks is probably more pure. They are also more complete. For example, Guice let you specify how the injected objects are created through the <a href="http://code.google.com/docreader/#p=google-guice&amp;s=google-guice&amp;t=ProviderBindings">concept of providers</a>. The thing is that with power comes complexity. Having many options is never for free. Even if you say: &#8220;I will only use a 10% of Guice&#8221; the rest of options are still there in the form of documentation and code. For example, they make you choose about what approach to take. And my point is that with a pure Ruby approach, without external tools, you can solve the most common cases in a much simpler way. I suppose it is a matter of taste, but I enjoy that approach much more.</p>

<h3>Strong types system</h3>

<p>I really don&#8217;t intend to talk about advantages and disadvantages of dynamic-typing and static-typing. But I would like to show an example of something that in my opinion is wrong. It is related to <a href="http://code.google.com/intl/en/webtoolkit/doc/latest/DevGuideCodingBasicsOverlay.html">GWT concept of overlay types</a>. It is a solution for managing JSON data as Java objects with GWT. This approach proposes to create a Java replication of the JSON data with getters/setters for the properties. The java code has to be mixed with the javascript code to be executed via <a href="http://googlewebtoolkit.blogspot.com/2008/07/getting-to-really-know-gwt-part-1-jsni.html">JSNI</a>. An example taken from the GWT page:</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">class</span> Customer <span style="color: #000000; font-weight: bold;">extends</span> JavaScriptObject <span style="color: #009900;">&#123;</span><br />
<br />
&nbsp; <span style="color: #666666; font-style: italic;">// Overlay types always have protected, zero-arg constructors</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">protected</span> Customer<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><br />
<br />
&nbsp; <span style="color: #666666; font-style: italic;">// Typically, methods on overlay types are JSNI</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">native</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getFirstName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #666666; font-style: italic;">/*-{ return this.FirstName; }-*/</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #000000; font-weight: bold;">native</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Astring+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">String</span></a> getLastName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> &nbsp;<span style="color: #666666; font-style: italic;">/*-{ return this.LastName; &nbsp;}-*/</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div>

<p>To me, it is like an implementation of the RY (Repeat Yourself) principle. I mean, do we need strong types that much? If this is the best abstraction you can do with Java of JSON data (and probably it is), then there must be something wrong with the language, because JSON data is only about structures of key/value pairs that can be nested.</p>

<p>Parsing JSON data with Ruby or Javascript is trivial. I will use the former in the next example. It shows how one line of javascript code can convert a JSON string into a plain Javascript object (using the JSON parsing utility of JQuery).</p>

<div class="codecolorer-container javascript blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #003366; font-weight: bold;">var</span> personJSON <span style="color: #339933;">=</span> <span style="color: #3366CC;">'{&quot;name&quot;: &quot;Jorge&quot;}'</span><span style="color: #339933;">;</span><br />
<span style="color: #003366; font-weight: bold;">var</span> person <span style="color: #339933;">=</span> $.<span style="color: #660066;">parseJSON</span><span style="color: #009900;">&#40;</span>personJSON<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
person.<span style="color: #000066;">name</span><span style="color: #339933;">;</span> <span style="color: #006600; font-style: italic;">//Jorge</span></div></div>

<h3>Object disorientation</h3>

<p>The JSON example is a concrete example where dynamic typing just makes more sense. But to me, the essential problem of strong types is that they make more difficult to represent mental abstractions with code, because every single piece must fit in a very strict puzzle of types. And this means that you are forced to code a lot of things that have nothing to do with your domain, but with the type system of the language.</p>

<p>Take for example the next GWT design. In GWT, widgets that trigger click events implements an interface <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/event/dom/client/HasClickHandlers.html">HasClickHandler</a>. This interface defines the contract of registering <a href="http://google-web-toolkit.googlecode.com/svn/javadoc/1.6/com/google/gwt/event/dom/client/ClickHandler.html">ClickHandler</a> objects, which are responsible of processing click events. This is a materialization of the <a href="http://martinfowler.com/eaaDev/PassiveScreen.html">Passive View pattern</a>: a view without any state with controllers performing all the work. The idea is to have a very thin view that can be faked in controllers tests.</p>

<p>Discussions about the pattern apart, there is no any possible human explanation that justify the existence of <code>HasClickHandler</code>. And by &#8220;human&#8221; I am not being sarcastic. From a human point of view, it makes no sense. It makes sense under the constraints imposed by testing tools and, specially, by the Java language itself, where the only way to specify behavior in a modular way is through the addition of interfaces defining the contract.</p>

<p>Object disorientation is what happens when you go from &#8220;My view has a button I have to test&#8221; to &#8220;My view is stupid, I am going to create a <code>HasClickHandler</code> getter in its interface so I can fake it when testing&#8221;. As of today, no technical choice is free of this problem, but in the case of Java I think its effects are just overwhelming.</p>

<p>When considering using GWT a project I am working on, I was impressed by <a href="http://code.google.com/intl/en/events/io/2009/sessions/GoogleWebToolkitBestPractices.html">this presentation of Ray Ryan</a>. I loved the principles and patterns discussed there for architecting the client part of a web application. The good thing about the presentation it that it focused on the concepts. The bad thing it that he showed very little example code.</p>

<p>It was when I saw how <a href="http://blog.hivedevelopment.co.uk/2009/08/google-web-toolkit-gwt-mvp-example.html">an example implementing those principles</a> looked, that I decided I was going to study javascript hard. And it wasn&#8217;t because the authors didn&#8217;t make an excellent work with the example, but because I understood I wasn&#8217;t going to have fun programming that way. The bad thing is not that implementing the basic GWT &#8220;hello world&#8221; in the proposed way took 600 lines of code (without tests). The bad thing was how ugly everything looked, from top to bottom. And since having fun and beautiful code are two very important things to me, I discarded GWT, I studied javascript and JQuery hard, and worked a lot learning how to mount a good testing environment for this technologies and a Rails backend. And I don&#8217;t regret at all of how things are going. Of course, there are other problems but those will be for another post.</p>

<p>It is curious. 7 years ago, Eric Evan&#8217;s warned the world about how important was to focus on the domain on his seminar <a href="http://www.amazon.com/exec/obidos/ASIN/0321125215/ref=nosim/jorgmanrpersp-20">Domain-Driven Design</a> book. Both design and code should reflect it as much as possible. In this time, despite of the big impact the book had in the Java community and all the discussions surrounding it, there is no still a mainstream implementation of many of the concepts he proposed. I wouldn&#8217;t say it is only due to Java being a poor language for representing the domain with code, but I think it has something to do with it.</p>

<h3>Conclusion</h3>

<p>I always find very difficult to explain what do I think is wrong with Java to other people. After writing this post, I still think the best way to understand it is to study other platforms and paradigms. In fact, the Java Platform offers nowadays a variety of languages, and some of them, like Groovy or Scala, are starting to attract a lot of attention. I still don&#8217;t know anything about Scala but I have used Groovy quite extensively and, although it has the same <code>new</code> operator problem that Java, it is a very nice alternative.</p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2010/05/30/dependency-injection-and-other-java-necessary-evils/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Testing PURE javascript templates from RSpec</title>
		<link>http://jorgemanrubia.net/2010/05/02/testing-pure-javascript-templates-from-rspec/</link>
		<comments>http://jorgemanrubia.net/2010/05/02/testing-pure-javascript-templates-from-rspec/#comments</comments>
		<pubDate>Sun, 02 May 2010 19:21:39 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/?p=427</guid>
		<description><![CDATA[The traditional Rails approach for AJAX has been using RJS templates. Following this approach, controllers respond to requests by rendering javascript code that is executed in the page on the fly, being the main benefit that you can use a powerful set of ruby helpers for specifying the javascript to be generated. Although this technique [...]]]></description>
			<content:encoded><![CDATA[<p>The traditional Rails approach for <acronym title="Asynchronous JavaScript and XML">AJAX</acronym> has been using RJS templates. Following this approach, controllers respond to requests by rendering javascript code that is executed in the page on the fly, being the main benefit that you can use a powerful set of ruby helpers for specifying the javascript to be generated. Although this technique has shown to be a productive way of adding ajax to web interfaces, it also has serious drawbacks and has been explicitly discouraged by first-class experts on Rails and Javascript like <a href="http://yehudakatz.com/">Yehuda Katz</a>: check  <a href="http://events.jquery.com/jquery-conference-2009/presentations/jQueryConf.pdf">these slides</a> or <a href="http://www.slideshare.net/wycats/jquery-presentation-to-rails-developers-110063">these</a>. It is worth to notice that <a href="http://guides.rails.info/3_0_release_notes.html#action-view">Rails 3 has redefined its <acronym title="Asynchronous JavaScript and XML">AJAX</acronym> approach</a> encouraging an unobtrusive use of javascript. This way you can still use the remote Rails helpers without being tied to a concrete Javascript library.</p>

<p>In my opinion, it just makes sense to have a server sending and receiving data in the form of JSON, and rich clients taking all the responsibility of rendering the UI and handling user interactions using <acronym title="HyperText Markup Language">HTML</acronym>, <acronym title="Cascading Style Sheets">CSS</acronym> and Javascript. The key is that this approach enables you to architect the client part of your application. If some part of the client behavior is left to the server, it becomes more difficult to have a consistent architecture in the client part because concerns are mixed. And without a consistent architecture in the client, it is difficult to provide the user experience that is becoming more and more demanded in today web applications.</p>

<p>So, if you want to render everything in the client using Javascript, you need a good system for creating the <acronym title="HyperText Markup Language">HTML</acronym>, and here it is where javascript templating systems appear. In this post I would like to explain how to test <a href="http://beebole.com/pure/">PURE</a> Javascript templates using <a href="http://rspec.info/">RSpec</a>. I chose to use <a href="http://beebole.com/pure/">PURE</a> because it is a production-ready system for rendering JSON data. The other solid approach seems to be <a href="http://jtemplates.tpython.com/">JTemplates</a>, but it doesn&#8217;t appear to be as actively maintained as PURE. There is also a <a href="http://wiki.github.com/nje/jquery/jquery-templates-proposal">proposal for including a templating system in JQuery</a> that was initially submitted by Microsoft. There is already a <a href="http://github.com/nje/jquery-tmpl">demonstration implementation</a> of the proposal but it is still in the incubation phase.</p>

<h3>Tools</h3>

<p>I am using <a href="http://rspec.info/">RSpec</a> and an amazing set of tools for running javascript from Ruby code:</p>

<ul>
<li><a href="http://github.com/mynyml/harmony">Harmony</a>: which wraps <a href="http://github.com/jbarnette/johnson/">Johnson</a> and <a href="http://github.com/jeresig/env-js">env.js</a> letting you run javascript code in a <acronym title="Document Object Model">DOM</acronym> environment from ruby.</li>
<li><a href="http://github.com/mynyml/holygrail">Holy Grail</a>: the Harmony plugin for Rails. It allows you to run javascript code in the context of your view tests.</li>
</ul>

<p>Just follow the instructions in the sites or Harmony and Holy Grail for installing them. For the installation of Holy Grail with RSpec, <a href="http://kenmayer.mp/blog/getting-holygrail-to-work-with-rspec-cucumber">read this article from Ken Mayer</a>.</p>

<h3>The example</h3>

<p>For the sake of simplicity I will try to keep the PURE part as minimal as possible. I want to render the following <code>person</code> object.</p>

<div class="codecolorer-container javascript blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="javascript codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;name&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Jorge&quot;</span><span style="color: #009900;">&#125;</span></div></div>

<p>And I will use the following PURE template:</p>

<div class="codecolorer-container html4strict blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="html4strict codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #009900;">&lt;<a href="http://december.com/html/4/element/div.html"><span style="color: #000000; font-weight: bold;">div</span></a> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;person-template&quot;</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;name&quot;</span><span style="color: #66cc66;">/</span>&gt;</span></div></div>

<p>Although in practice you will be using <a href="http://beebole.com/pure/documentation/rendering-with-directives/">PURE directives</a> for sure, for the example I will use the <a href="http://beebole.com/pure/documentation/auto-rendering/">PURE auto-rendering mechanism</a>.</p>

<p>What I want is to write a RSpec view spec to test that the template renders JSon as expected:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">describe <span style="color:#996600;">&quot;persons/_person_template.html.erb&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; it <span style="color:#996600;">&quot;should render a proper container for the person&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; person = <span style="color:#006600; font-weight:bold;">&#123;</span>:name<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;Jorge&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span><br />
&nbsp; &nbsp; render_javascript_template<span style="color:#006600; font-weight:bold;">&#40;</span>person<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>rendered_text<span style="color:#006600; font-weight:bold;">|</span><br />
&nbsp; &nbsp; &nbsp; rendered_text.<span style="color:#9900CC;">should</span> have_selector<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;div.name&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:content</span><span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;Jorge&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>The helper method <code>render_javascript_template</code> receives a model object to render, and yields to a closure providing it with the result of the rendered template. The rendered text can be then checked using, in this case, <a href="http://github.com/brynary/webrat">Webrat</a> matchers. The code of this helper method is shown bellow.</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color:#9966CC; font-weight:bold;">module</span> ViewHelpers<br />
&nbsp; <br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> render_javascript_template<span style="color:#006600; font-weight:bold;">&#40;</span>data<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; render<br />
&nbsp; &nbsp; include_javascript_files<br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">yield</span> do_render_javascript_template<span style="color:#006600; font-weight:bold;">&#40;</span>data<span style="color:#006600; font-weight:bold;">&#41;</span> &nbsp; &nbsp;<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> include_javascript_files<br />
&nbsp; &nbsp; <span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#123;</span>jquery.<span style="color:#9900CC;">js</span> pure.<span style="color:#9900CC;">js</span><span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>file<span style="color:#006600; font-weight:bold;">|</span> js<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;load('public/javascripts/#{file}');&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#125;</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> as_javascript_string<span style="color:#006600; font-weight:bold;">&#40;</span>text<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; text.<span style="color:#CC0066; font-weight:bold;">split</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;<span style="color:#000099;">\n</span>&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">collect</span><span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">|</span>line<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#996600;">&quot;'#{line}'&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'+'</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> template_id_from_path<span style="color:#006600; font-weight:bold;">&#40;</span>template_path<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; template_path.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>^<span style="color:#006600; font-weight:bold;">&#40;</span>.<span style="color:#006600; font-weight:bold;">+</span>\<span style="color:#006600; font-weight:bold;">/</span>_<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">&quot;&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>_<span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">&quot;-&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#CC0066; font-weight:bold;">gsub</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">/</span>.<span style="color:#9900CC;">html</span>.<span style="color:#9900CC;">erb</span>$<span style="color:#006600; font-weight:bold;">/</span>, <span style="color:#996600;">&quot;&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> do_render_javascript_template<span style="color:#006600; font-weight:bold;">&#40;</span>data<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; json_data = as_javascript_string<span style="color:#006600; font-weight:bold;">&#40;</span>data.<span style="color:#9900CC;">to_json</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; template_id = template_id_from_path<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9966CC; font-weight:bold;">class</span>.<span style="color:#9900CC;">description_parts</span>.<span style="color:#9900CC;">first</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; js<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;var data=$.parseJSON(#{json_data});&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; js<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;var $template = $('##{template_id}').clone().appendTo($('&lt;div&gt;&lt;/div&gt;'));&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; js<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;var renderedElement = $template.autoRender(data);&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; <br />
&nbsp; &nbsp; <span style="color:#0000FF; font-weight:bold;">return</span> js<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;$('&lt;div&gt;&lt;/div&gt;').append(renderedElement).html()&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>The <code>render_javascript_template</code> method has to do basically two things before rendering the templates using PURE:</p>

<ul>
<li>Rendering the template that contains the <acronym title="HyperText Markup Language">HTML</acronym> of the template (in this example it is the ERB file itself).</li>
<li>Including the required javascript files of PURE and JQuery.</li>
</ul>

<p>The order of these steps is important: if you don&#8217;t invoke <code>render</code> before requiring the javascript files, JQuery won&#8217;t work properly.</p>

<p>The method that does the work is <code>do_render_javascript_template</code>. It basically does three things:</p>

<ul>
<li>It converts the json of the data to be rendered to a form suitable to be injected in the javascript runtime as a string literal (javascript doesn&#8217;t admit multi-lines literals).</li>
<li>It then obtains the template <acronym title="Cascading Style Sheets">CSS</acronym> id that is going to be used to locate the template node we want to use. It obtains it from the file path of the template, which is specified in the outer describe of the spec.</li>
<li>Finally it invokes the PURE auto-rendering process with the template. The only tip is that it appends an artificial container to the template because PURE fails if the template node hasn&#8217;t a parent. In the same way, before calling the JQuery function <code>html()</code>, an artificial root node is added because JQuery ignore root nodes with elements detached from the <acronym title="Document Object Model">DOM</acronym>.</li>
</ul>

<h3>Conclussions</h3>

<p>While I test all my javascript code using <a href="http://visionmedia.github.com/jspec/">JSpec</a>, it didn&#8217;t fit well for testing my PURE templates. I had read about Harmony and I wondered if it would be possible to make the testing of PURE templates using RSpec and the powerful Webrat matchers. It happened to be not only possible, but a surprisingly fast and comfortable way of testing the templates. I am willing to see a templating system finally included with JQuery, but PURE is a powerful and fast choice that works today. I really think Javascript templates are here to stay.</p>

<p>The code of this post is availabe as a <a href="http://gist.github.com/387503">gist at github</a>.</p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2010/05/02/testing-pure-javascript-templates-from-rspec/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>On Eclispe buddy class loading and performance problems</title>
		<link>http://jorgemanrubia.net/2010/02/09/on-eclispe-buddy-class-loading-and-performance-problems/</link>
		<comments>http://jorgemanrubia.net/2010/02/09/on-eclispe-buddy-class-loading-and-performance-problems/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 21:42:50 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/?p=322</guid>
		<description><![CDATA[At work we have been experiencing serious performance problems with the Eclipse feature we are developing. We have just solved the problem and I would like to share the chain of events that caused it. I will elaborate on this a little bit, but in a few words: If you want to wait for jobs [...]]]></description>
			<content:encoded><![CDATA[<p>At work we have been experiencing serious performance problems with the Eclipse feature we are developing. We have just solved the problem and I would like to share the chain of events that caused it. I will elaborate on this a little bit, but in a few words:</p>

<ul>
<li>If you want to wait for jobs in Eclipse Junit Plugin tests, <a href="https://jira.jboss.org/jira/browse/JBIDE-2128">use this method</a> instead of the proposed in the second edition of the book <a href="http://www.amazon.com/exec/obidos/ASIN/0321228472/ref=nosim/jorgmanrpersp-20"><em>Eclipse: Building Commercial-Quality Plug-Ins</em></a>.</li>
<li>The <code>global</code> buddy class loading policy can affect performance seriously. It is logical and they warn you about it. I can confirm it is true. </li>
</ul>

<h3>Waiting for jobs in Eclipse JUnit Plugin Tests</h3>

<p>The <a href="http://www.eclipse.org/pde/">Eclipse PDE</a> provides a launcher that let you test your plugins using JUnit. It basically instantiates a new Eclipse workbench and, when it is up, the tests are run inside it. When writing tests, a common need is waiting for jobs to finish. After launching a job for testing its results, the job is run in a separate thread, so the test code will continue running if you don&#8217;t stop it.</p>

<p>The book <a href="http://www.amazon.com/exec/obidos/ASIN/0321228472/ref=nosim/jorgmanrpersp-20"><em>Eclipse: Building Commercial-Quality Plug-Ins</em></a> is an excellent resource for learning Eclipse plugin development. It proposes some utility methods for using with Eclipse Plugin tests. One of this methods is indeed <code>waitForJobs()</code>:</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> waitForJobs<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>Platform.<span style="color: #006633;">getJobManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">currentJob</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><br />
&nbsp; &nbsp; delay<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
<span style="color: #009900;">&#125;</span></div></div>

<p>This implementation worked well for us until one day we decided to divide a plugin that had become too big. I started by creating a new plugin extracting some code of the plugin along with its tests. But the tests always failed launching a <code>NoClassDefFoundError</code> exception. I was totally convinced that this problem was related to the way we had configured class dependencies between plugins. We use Groovy and the exception was always launched from the groovy libraries referenced from groovy compiled code. I spend a lot of time trying to figure out what was going on. It was a colleague who pointed out that it seemed that the test code was not waiting for the job under test to finish. And he was right. After searching in google I found <a href="waitforjobs">a more robust implementation of the <code>waitForJobs()</code></a> method:</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000066; font-weight: bold;">void</span> waitForJobs<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000066; font-weight: bold;">long</span> start <span style="color: #339933;">=</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">currentTimeMillis</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span>Job.<span style="color: #006633;">getJobManager</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">isIdle</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; delay<span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">500</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span> <span style="color: #009900;">&#40;</span><a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Asystem+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">System</span></a>.<span style="color: #006633;">currentTimeMillis</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-</span>start<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&gt;</span> MAX_IDLE <span style="color: #009900;">&#41;</span> <br />
&nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <a href="http://www.google.com/search?hl=en&amp;q=allinurl%3Aruntimeexception+java.sun.com&amp;btnI=I%27m%20Feeling%20Lucky"><span style="color: #003399;">RuntimeException</span></a><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;A long running task detected&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div>

<p>Using this approach solved the problem. This would had nothing to do with performance if I hadn&#8217;t messed up with the class loading configuration trying to solve it. Basically I made many of our plugins to use a <code>global</code> buddy class loading policy and, once the problem was solved, I didn&#8217;t undo it. And, while we perceived a poor performance in our plugin, it wasn&#8217;t until recently that we discovered the cause was precisely that <code>global</code> policy (we thought it was a problem with the development installation of the system our product connects to). And this brings me to the next section.</p>

<h3>Eclipse Buddy Class Loading</h3>

<p>The Eclipse core platform runs on a sophisticated runtime for Java components (<a href="http://www.eclipse.org/equinox/">Equinox</a>, an <a href="http://en.wikipedia.org/wiki/Osgi">OSGI</a> implementation). This runtime provides a powerful architecture for installing and running Java modules (bundles or plugins). For doing so, it redefines completely the class loading system of the Standard Java Platform. When running inside Eclipse, each bundle has its own class loader. Bundles declare in their manifests how do they relate to other bundles, so their class loaders know how to locate external classes.</p>

<p>When a bundle <em>A</em> depends on a bundle <em>B</em> it can access its exported classes with no problem. The problem comes when it is <em>B</em> who wants to load classes from <em>A</em> dynamically,  but it can&#8217;t depend on it (because it would create a circular dependence, or just because it doesn&#8217;t make sense). For example, the <em>Log4j</em> bundle can&#8217;t depend on a bundle that provides a <code>log4.properties</code> configuration file but it still wants to locate it in execution time. We have a number of scenarios like this in our application, where some bundles need to load classes/resources from other bundles they don&#8217;t know in execution time.</p>

<p>In these situations <a href="http://wiki.eclipse.org/index.php/Context_Class_Loader_Enhancements#Buddy_Policy">Eclipse Buddy Class Loading</a> come to the rescue (another approach, better but more complex, is to use <a href="http://www.eclipsezone.com/articles/extensions-vs-services/">extension points</a> for allowing plugins to be extended in execution time). Buddy policies allow one bundle to declare that it needs to load classes from other bundles (buddies). When a bundle class loader fails to locate some class, it starts searching for it in the declared buddies. The system can configure a number of policies that determine the way classes are searched:</p>

<ul>
<li><code>dependent</code>: search in bundles that directly or indirectly depend on the bundle.</li>
<li><code>required</code>: search in bundles that explicitly declare themselves as buddies of the caller bundle.</li>
<li><code>global</code>: search in all the bundles.</li>
</ul>

<p>There are <a href="http://wiki.eclipse.org/index.php/Context_Class_Loader_Enhancements#Buddy_Policy_2">others policies available</a> but I think the first two are the most common. Buddy policies are configured in the <code>MANIFEST.MF</code> file of the bundle that needs to load the classes. For example, in the manifest of the <code>org.apache.log4j</code> plugin you can find this:</p>

<div class="codecolorer-container properties blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="properties codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Eclipse-BuddyPolicy: registered</div></div>

<p>Since it uses a <code>registered</code> policy, if you want your bundle to provide a properties file for log4j, you should declare your bundle as a buddy of Log4J.</p>

<div class="codecolorer-container properties blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="properties codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Eclipse-RegisterBuddy: org.apache.log4j</div></div>

<p>With a <code>dependent</code> policy this last step is not necessary. As it is obvious, <code>registered</code> is more efficient than <code>dependent</code>, and this one is more efficient than <code>global</code>. In a product like our feature, which is big but not huge, when we changed from <code>global</code> to <code>dependent</code> we observed a huge performance boost, specially the first time the product functions were launched (which is when classes are loaded).</p>

<p>When you try to solve a mysterious bug for long time enough, you are so satisfied when yo do it that you don&#8217;t spend too much time blaming yourself for having produced it. And that was my state after this one&#8230;</p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2010/02/09/on-eclispe-buddy-class-loading-and-performance-problems/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using macros to create custom example groups in RSpec</title>
		<link>http://jorgemanrubia.net/2010/01/16/using-macros-to-create-custom-example-groups-in-rspec/</link>
		<comments>http://jorgemanrubia.net/2010/01/16/using-macros-to-create-custom-example-groups-in-rspec/#comments</comments>
		<pubDate>Sat, 16 Jan 2010 01:25:54 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/2010/01/16/using-macros-to-create-custom-example-groups-in-rspec/</guid>
		<description><![CDATA[I am involved in a personal project where I am developing a web application with Rails. I am using RSpec and Cucumber, and I am following an outside-in, behavior-driven development approach, as recommended in the excellent RSpec Book. In this post I would like to share a problem I found and how I solved it. [...]]]></description>
			<content:encoded><![CDATA[<p>I am involved in a personal project where I am developing a web application with <a href="http://rubyonrails.org/">Rails</a>. I am using <a href="http://rspec.info/">RSpec</a> and <a href="http://cukes.info/">Cucumber</a>, and I am following an outside-in, behavior-driven development approach, as recommended in <a href="http://pragprog.com/titles/achbd/the-rspec-book">the excellent RSpec Book</a>. In this post I would like to share a problem I found and how I solved it.</p>

<p>It started when I tried to refactor some duplicated code in my controllers specs. It was related to the authentication system. Specs should test their behavior in both authenticated and insecure contexts, to be sure that anything happens if an anonymous user sends a <code>POST</code> action to your <code>WorldDestroyerController</code>. For example:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">describe UserSessionsController, <span style="color:#996600;">&quot;DELETE destroy&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; should_require_login <span style="color:#ff3333; font-weight:bold;">:delete</span>, <span style="color:#ff3333; font-weight:bold;">:destroy</span> <br />
<br />
&nbsp; context <span style="color:#996600;">&quot;authenticated user&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; before<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:each</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; login_as_user<br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<br />
&nbsp; &nbsp; it <span style="color:#996600;">&quot;should destroy the user session&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; <span style="color:#0066ff; font-weight:bold;">@current_user_session</span>.<span style="color:#9900CC;">should_receive</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:destroy</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; delete <span style="color:#ff3333; font-weight:bold;">:destroy</span><br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<br />
&nbsp; &nbsp; it <span style="color:#996600;">&quot;should redirect to the login page&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; delete <span style="color:#ff3333; font-weight:bold;">:destroy</span><br />
&nbsp; &nbsp; &nbsp; response.<span style="color:#9900CC;">should</span> redirect_to login_path<br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span> &nbsp;<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>The next fragment was recurrent in all my examples.</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">context <span style="color:#996600;">&quot;authenticated user&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; before<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:each</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; login_as_user<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <br />
&nbsp; ...</div></div>

<p>For every example in the example group, it basically stubs the controller method that validates sessions in order to get a valid one when invoked (I am using <a href="http://github.com/binarylogic/authlogic">authlogic</a>). I wanted to create a macro <code>context_authenticated</code> so I could code the previous example like this:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">describe UserSessionsController, <span style="color:#996600;">&quot;DELETE destroy&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; should_require_login <span style="color:#ff3333; font-weight:bold;">:delete</span>, <span style="color:#ff3333; font-weight:bold;">:destroy</span> <br />
<br />
&nbsp; context_authenticated <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; it <span style="color:#996600;">&quot;should destroy the user session&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; <span style="color:#0066ff; font-weight:bold;">@current_user_session</span>.<span style="color:#9900CC;">should_receive</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:destroy</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; delete <span style="color:#ff3333; font-weight:bold;">:destroy</span><br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<br />
&nbsp; &nbsp; it <span style="color:#996600;">&quot;should redirect to the login page&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; delete <span style="color:#ff3333; font-weight:bold;">:destroy</span><br />
&nbsp; &nbsp; &nbsp; response.<span style="color:#9900CC;">should</span> redirect_to login_path<br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span> &nbsp;<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>My first attempt was to write a macro that included the before block and yielded to the block provided in the invocation:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color:#9966CC; font-weight:bold;">def</span> context_authenticated<br />
&nbsp; context <span style="color:#996600;">&quot;authenticated user&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; before<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:each</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; login_as_user<br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">yield</span> <span style="color:#008000; font-style:italic;">#Wrong</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>The examples failed because the <code>before(:each)</code> fragment was not being invoked before executing them. To discover the problem I had to <a href="http://rspec.rubyforge.org/rspec/1.3.0/">investigate a little bit about how the RSpec <acronym title="Domain Specific Language">DSL</acronym> works</a>. Basically:</p>

<ul>
<li>Each <code>context</code> (alias for <code>describe</code>) creates a new <code>ExampleGroup</code> subclass.</li>
<li>Each <code>it</code> (alias for <code>example</code>) creates a new instance of the current <code>ExampleGroup</code> subclass where it is invoked.</li>
</ul>

<p>So the problem was related to the very nature of closures. In Ruby, a block of code (<code>proc</code> or <code>lambda</code>) maintains the bindings in effect for that closure. The bindings contains not only variable references, but also the <code>self</code> reference itself.</p>

<p>In my case, what I was doing was to submit a closure with the <code>it</code> examples to the macro. The execution context of this closure was the one where it was defined: the <code>ExampleGroup</code> subclass created by <code>describe UserSessionsController...</code>. However, inside the macro, a new <code>ExampleGroup</code> subclass was created, and the <code>before</code> block was associated with that example group. That was the reason why the the <code>before</code> code was not getting executed before the submitted examples. Once I understood this, the solution was simple:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color:#9966CC; font-weight:bold;">def</span> context_authenticated<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&amp;</span>example_group_block<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; example_group_class = context <span style="color:#996600;">&quot;authenticated user&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; before<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:each</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span><br />
&nbsp; &nbsp; &nbsp; login_as_user<br />
&nbsp; &nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
&nbsp; example_group_class.<span style="color:#9900CC;">class_eval</span> <span style="color:#006600; font-weight:bold;">&amp;</span>example_group_block<br />
<span style="color:#9966CC; font-weight:bold;">end</span></div></div>

<p>What the previous code does is to change the evaluation context of the closure, so it get executed inside the <code>ExampleGroup</code> class created by the macro.</p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2010/01/16/using-macros-to-create-custom-example-groups-in-rspec/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Evaluating code dynamically in Groovy (differences with Ruby)</title>
		<link>http://jorgemanrubia.net/2009/10/10/evaluating-code-dynamically-in-groovy/</link>
		<comments>http://jorgemanrubia.net/2009/10/10/evaluating-code-dynamically-in-groovy/#comments</comments>
		<pubDate>Sat, 10 Oct 2009 16:38:44 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/2009/10/10/evaluating-code-dynamically-in-groovy/</guid>
		<description><![CDATA[This week I found out that there are important differences between Ruby and Groovy when it comes to evaluate code dynamically. In order to write the testing infrastructure of a DSL we were developing, we wanted to invoke the code contained in isolated files in the context of the caller code. We were using Groovy, [...]]]></description>
			<content:encoded><![CDATA[<p>This week I found out that there are important differences between Ruby and Groovy when it comes to evaluate code dynamically. In order to write the testing infrastructure of a <acronym title="Domain Specific Language">DSL</acronym> we were developing, we wanted to invoke the code contained in isolated files in the context of the caller code. We were using Groovy, and I wrongly assumed that it would be as easy as with Ruby.</p>

<p>Imagine you have a file named <code>say.script</code> with the next contents:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">say <span style="color:#996600;">&quot;Hello&quot;</span></div></div>

<p>In this <acronym title="Domain Specific Language">DSL</acronym>, you can say things that are visualized in the <code>STDOUT</code>. Executing this script with Ruby is very simple: just invoke <code>eval()</code> with the code to evaluate it in a context where the <code>say()</code> method exists.</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color:#9966CC; font-weight:bold;">def</span> say<span style="color:#006600; font-weight:bold;">&#40;</span>message<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; <span style="color:#CC0066; font-weight:bold;">puts</span> message<br />
<span style="color:#9966CC; font-weight:bold;">end</span><br />
<br />
<span style="color:#CC0066; font-weight:bold;">eval</span> <span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">read</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'say.script'</span><span style="color:#006600; font-weight:bold;">&#41;</span></div></div>

<p>If you want to evaluate the code in the context of some object (for example, an  <a href="http://martinfowler.com/bliki/ExpressionBuilder.html">expression builder</a>), you can write something like:</p>

<div class="codecolorer-container ruby blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="ruby codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color:#9966CC; font-weight:bold;">class</span> Context<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">def</span> say<span style="color:#006600; font-weight:bold;">&#40;</span>message<span style="color:#006600; font-weight:bold;">&#41;</span><br />
&nbsp; &nbsp; <span style="color:#CC0066; font-weight:bold;">puts</span> message<br />
&nbsp; <span style="color:#9966CC; font-weight:bold;">end</span><br />
<span style="color:#9966CC; font-weight:bold;">end</span><br />
<br />
context = Context.<span style="color:#9900CC;">new</span><br />
code = <span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">read</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'say.script'</span><span style="color:#006600; font-weight:bold;">&#41;</span><br />
context.<span style="color:#9900CC;">instance_eval</span> code</div></div>

<p>However, in Groovy, the <a href="http://groovy.codehaus.org/Embedding+Groovy"><code>GroovyShell.evaluate()</code> method</a> is not equivalent to Ruby&#8217;s <code>eval()</code> method. While both mechanisms can share state between the caller and the invoked code through the concept of bindings, in Groovy the <code>evaluate()</code> method is always resolved in the context of a <code>Script</code> object. This means that <strong>the implicit invocation context is not shared</strong>. If you try to execute this code:</p>

<div class="codecolorer-container groovy blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="groovy codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">def</span> say<span style="color: #66cc66;">&#40;</span>message<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><br />
&nbsp; <span style="color: #993399;">println</span> message<br />
<span style="color: #66cc66;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">def</span> shell <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> GroovyShell<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
<span style="color: #000000; font-weight: bold;">def</span> code <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;say.script&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">text</span><br />
<br />
shell.<span style="color: #006600;">evaluate</span><span style="color: #66cc66;">&#40;</span>code<span style="color: #66cc66;">&#41;</span> <span style="color: #808080; font-style: italic;">//WRONG: in the script object the say() method is not defined</span></div></div>

<p>You will obtain something like:</p>

<div class="codecolorer-container text blackboard" style="border:1px solid #9F9F9F;width:435px;"><div class="text codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">Exception in thread &quot;main&quot; groovy.lang.MissingMethodException: No signature of method: Script1.say() is applicable for argument types: (java.lang.String) values: {&quot;Hello&quot;}</div></div>

<p>A workaround for this situation is to convert the script code into a closure. This way, the <acronym title="Domain Specific Language">DSL</acronym> code is evaluated but not executed. With the closure object you can make the invocation in the context you prefer. In the last example, code bellow will make it:</p>

<div class="codecolorer-container groovy blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="groovy codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">def</span> say<span style="color: #66cc66;">&#40;</span>message<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><br />
&nbsp; <span style="color: #993399;">println</span> message<br />
<span style="color: #66cc66;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">def</span> shell <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> GroovyShell<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
<span style="color: #000000; font-weight: bold;">def</span> code <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;say.script&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">text</span><br />
<br />
code <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;{-&gt;${code}}&quot;</span><br />
<span style="color: #000000; font-weight: bold;">def</span> closure <span style="color: #66cc66;">=</span> shell.<span style="color: #006600;">evaluate</span><span style="color: #66cc66;">&#40;</span>code<span style="color: #66cc66;">&#41;</span><br />
closure.<span style="color: #006600;">delegate</span><span style="color: #66cc66;">=</span><span style="color: #000000; font-weight: bold;">this</span><br />
closure<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></div></div>

<p>In the example, we wrap the code to execute with a closure syntax. In this way, when we call <code>evaluate</code> we obtain a closure object. With this closure object we can modify its delegate (invocation context) and then call it.</p>

<p>Finally, if we wanted to execute the code using a specific invocation context (something like Ruby&#8217;s <code>instance_eval</code>), we just have to modify the delegate object:</p>

<div class="codecolorer-container groovy blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="groovy codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">class</span> <span style="color: #aaaadd; font-weight: bold;">Context</span><span style="color: #66cc66;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">def</span> say<span style="color: #66cc66;">&#40;</span>message<span style="color: #66cc66;">&#41;</span><span style="color: #66cc66;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #993399;">println</span> message<br />
&nbsp; <span style="color: #66cc66;">&#125;</span><br />
<span style="color: #66cc66;">&#125;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">def</span> shell <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> GroovyShell<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
<span style="color: #000000; font-weight: bold;">def</span> code <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">File</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">&quot;say.script&quot;</span><span style="color: #66cc66;">&#41;</span>.<span style="color: #006600;">text</span><br />
code <span style="color: #66cc66;">=</span> <span style="color: #ff0000;">&quot;{-&gt;${code}}&quot;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">def</span> context <span style="color: #66cc66;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Context</span><span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span><br />
<br />
<span style="color: #000000; font-weight: bold;">def</span> closure <span style="color: #66cc66;">=</span> shell.<span style="color: #006600;">evaluate</span><span style="color: #66cc66;">&#40;</span>code<span style="color: #66cc66;">&#41;</span><br />
closure.<span style="color: #006600;">delegate</span> <span style="color: #66cc66;">=</span> context<br />
closure<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span></div></div>

<p>I don&#8217;t know of a better approach for solving this problem with Groovy. Initially I thought there will be a direct way, like in Ruby. But after hours of searching for it we didn&#8217;t find anything (which doesn&#8217;t mean it doesn&#8217;t exist, of course).</p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2009/10/10/evaluating-code-dynamically-in-groovy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Composed Method implementation pattern</title>
		<link>http://jorgemanrubia.net/2009/06/28/the-composed-method-implementation-pattern/</link>
		<comments>http://jorgemanrubia.net/2009/06/28/the-composed-method-implementation-pattern/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 17:17:06 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/2009/06/28/the-composed-method-implementation-pattern/</guid>
		<description><![CDATA[Infoq is one of my favorite sources for reading general-purpose stuff on software development. Some time ago they published an excellent presentation: 10 Ways to Improve Your Code by Neal Ford. I just loved it. The first practice it focused on is the composed method implementation pattern, one of the most fundamental development practices I [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.infoq.com/">Infoq</a> is one of my favorite sources for reading general-purpose stuff on software development. Some time ago they published an excellent presentation: <a href="http://www.infoq.com/presentations/10-Ways-to-Better-Code-Neal-Ford">10 Ways to Improve Your Code</a> by <a href="http://www.nealford.com/">Neal Ford</a>. I just loved it. The first practice it focused on is the <strong>composed method</strong> implementation pattern, one of the most fundamental development practices I can think of.</p>

<p>It was formally described a lot of years ago, as a pattern, in Kent Beck&#8217;s book <a href="http://www.amazon.com/Smalltalk-Best-Practice-Patterns-Kent/dp/013476904X">Smalltalk Best Practice Patterns</a>. I havent&#8217;t read this book yet (it is arriving in my next Amazon&#8217;s order). Sincerely I don&#8217;t know anything about Smalltalk but people usually say that this book is recommendable for anyone interested in good programming practices. I&#8217;m sure I will enjoy it. I expect it to be better than <a href="http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091">Implementation Patterns</a>, also by Kent Beck. While not a bad book, I thought it was going to be much better. In this book, it is said that you should:</p>

<blockquote>
  <p>Compose methods out of calls to other methods, each of which is at roughly the same level of abstraction</p>
</blockquote>

<p>I don&#8217;t know why but I tended to call this implementation pattern as <em>factorized code</em>. I think it has to do with the fact that the first time I realized about its importance was reading <a href="http://www.amazon.com/Refactoring-Improving-Existing-Addison-Wesley-Technology/dp/0201485672">Martin Fowler&#8217;s Refactoring book</a>. It was a lot of years ago but I remember that in some section (I guess it was in the <em>extract method</em> refactoring pattern) the book said that when you have in your code something like this:</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000066; font-weight: bold;">void</span> someMethod<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #666666; font-style: italic;">//do some stuff</span><br />
&nbsp; line <span style="color: #cc66cc;">1</span><br />
&nbsp; line <span style="color: #cc66cc;">2</span><br />
&nbsp; line <span style="color: #cc66cc;">3</span><br />
<br />
&nbsp; <span style="color: #666666; font-style: italic;">//calculate some other stuff</span><br />
&nbsp; line <span style="color: #cc66cc;">4</span><br />
&nbsp; line <span style="color: #cc66cc;">5</span><br />
&nbsp; line <span style="color: #cc66cc;">6</span><br />
<br />
&nbsp; <span style="color: #666666; font-style: italic;">//do final stuff</span><br />
&nbsp; line <span style="color: #cc66cc;">7</span><br />
&nbsp; line <span style="color: #cc66cc;">8</span><br />
&nbsp; line <span style="color: #cc66cc;">9</span><br />
<span style="color: #009900;">&#125;</span></div></div>

<p>You should refactor to something like this:</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;height:300px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000066; font-weight: bold;">void</span> someMethod<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br />
&nbsp; doSomeStuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; calculateSomeOtherStuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; doFinalStuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000066; font-weight: bold;">void</span> doSomeStuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br />
&nbsp; line <span style="color: #cc66cc;">1</span><br />
&nbsp; line <span style="color: #cc66cc;">2</span><br />
&nbsp; line <span style="color: #cc66cc;">3</span><br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000066; font-weight: bold;">void</span> calculateSomeOtherStuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br />
&nbsp; line <span style="color: #cc66cc;">4</span><br />
&nbsp; line <span style="color: #cc66cc;">5</span><br />
&nbsp; line <span style="color: #cc66cc;">6</span>&nbsp; <br />
<span style="color: #009900;">&#125;</span><br />
<br />
<span style="color: #000066; font-weight: bold;">void</span> doFinalStuff<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span><br />
&nbsp; line <span style="color: #cc66cc;">7</span><br />
&nbsp; line <span style="color: #cc66cc;">8</span><br />
&nbsp; line <span style="color: #cc66cc;">9</span>&nbsp; <br />
<span style="color: #009900;">&#125;</span></div></div>

<p>It said that, instead of having a sequence of comments and lines of code, you should extract lines of code to methods with proper names. This way you could also remove comments, as they were redundant. If I remember something of the Refactoring book, is how impressed I was about Fowler&#8217;s coding style (the catalog is full of Java code samples).</p>

<p>In my first year at the University, we were taught about procedural programming. I remember being told that when you designed a program, you had to divide high-level routines into calls to lower-level ones. By doing this recursively, you obtained a tree, where leafs represented primitive routines.</p>

<p>Watching the way many people code it seems that this fundamental principle has simply being lost. It seems like if with objects, you only have to take care of carefully design the public contract of objects and their relations. While this aspect is very important, you have to pay a lot of attention to the design of internal code.</p>

<p>Although this pattern may seem very simple, applying it correctly is not as simple as saying <q>you should divide methods into small steps</q>. I think there are three fundamental properties that should rule methods design:</p>

<ul>
<li>Cohesion</li>
<li>Clear interfaces</li>
<li>Symmetry</li>
</ul>

<p>Methods should be <strong>highly cohesive</strong>. This means that methods should focus in a single responsibility or functionality. This property comes from the software quality field, usually applied to modules or classes. Applying it when designing methods implies that you shouldn&#8217;t have methods that do many things from the point of view of the client that is using it. Who is the client depends on the abstraction level where the code is being invoked. Could be another class o just a private method inside in the same one. A method that receives five parameters is usually a bad smell.</p>

<p>Methods should have <strong>clear interfaces</strong>. In <a href="http://www.amazon.com/Writing-Solid-Code-Microsofts-Programming/dp/1556155514">Writing Solid Code</a> Steve Maguire says that the signature of all methods (functions in those days) should be clear enough in order to understand what the method is supposed to do, without any other kind of documentation. Signature means the name of the method as well as of the parameters it receives and returns (and their types). Achieving this involves many things but without cohesion is just impossible.</p>

<p>The book shows a good example of how a method should not being designed: the <a href="http://c.conclase.net/librerias/funcion.php?fun=realloc">C <code>realloc()</code> function</a>. It just does many things with a very obscure interface, which you won&#8217;t understand without the documentation. The book also contains a very representative example from the physical word, the <em>candy machine interface</em> problem: when the candy machine offers numbers for both selecting products and displaying their prices. Methods should not offer a candy machine interface.</p>

<p>The composition of methods should also be <strong>symmetric</strong>. The steps a method is divided in should be at the same level of abstraction. Abstraction is a construction that a person does in order to understand something. Jumping from one level of abstraction to another requires mental effort. If you have to keep jumping between different levels of abstraction in order to understand some code, it will be far more difficult to understand.</p>

<p>In conclusion, while this pattern will improve the quality of your software, I use it because for me it is easier to program this way. It is just the principle of <em>divide and conquer</em> working. I usually code methods following a top-down approach. Writing the top level methods calling lower-level methods before they exist. This way I can directly project the structure of steps that I, like a human, have in my head. Other people prefer to write the code without decomposing it first, and then refactorize to extract methods (I think this approach is far less effective).</p>

<p>Anyway I think that if you apply this practice exhaustively, along with using proper names for naming identifiers, your code will be like a 400% better.</p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2009/06/28/the-composed-method-implementation-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Generating JUnit Test Cases Dynamically</title>
		<link>http://jorgemanrubia.net/2008/09/18/generating-junit-test-cases-dynamically/</link>
		<comments>http://jorgemanrubia.net/2008/09/18/generating-junit-test-cases-dynamically/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 00:53:30 +0000</pubDate>
		<dc:creator>Jorge Manrubia</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Development]]></category>

		<guid isPermaLink="false">http://jorgemanrubia.net/blog/?p=48</guid>
		<description><![CDATA[In this post I&#8217;m going to talk about generating JUnit Test Cases Dynamically. In order to define tests, most JUnit&#8217;s users place their testing code inside test methods that Start with test Don&#8217;t have arguments Given a TestCase object, JUnit TestSuites can dynamically extract test methods that follow these conventions and run them on the [...]]]></description>
			<content:encoded><![CDATA[<p>In this post I&#8217;m going to talk about generating <a href="http://www.junit.org">JUnit</a> Test Cases Dynamically. In order to define tests, most JUnit&#8217;s users place their testing code inside <q>test methods</q> that</p>

<ul>
<li>Start with <code>test</code></li>
<li>Don&#8217;t have arguments</li>
</ul>

<p>Given a <code>TestCase</code> object, JUnit <code>TestSuites</code> can dynamically extract test methods that follow these conventions and run them on the fly. However, this behavior isn&#8217;t enough in some cases. The problem of this approach is that, from the developer&#8217;s point of view, tests must be written statically.</p>

<p>Imagine you have a directory with many text files. For each file, you want to do the same kind of testing. Since the test result depends on each file, what you really want is to generate dynamically test cases. Of course you can have a single test method, and do all the testing there. The main problem of this approach is that Test Runners won&#8217;t be able to collect results properly: a single fail with one file would result as a failure. You won&#8217;t notice which tests are valid and which aren&#8217;t.</p>

<p>Generating tests cases dynamically is very simple. <a href="http://www.riehle.org/2008/04/03/junit-38-documented-using-collaborations/">JUnit&#8217;s design</a> itself is simple. This is one of the main reasons of why this framework is so successful. <a href="http://en.wikipedia.org/wiki/Junit">JUnit was created by Kent Beck and Erich Gamma</a>. It represents an excellent oportunity to see <acronym title="Gang of Four">GOF</acronym> design patterns in action (in the same way that <a href="http://www.jhotdraw.org/">JHotDraw</a>, another framework created by Erich Gamma as a design patterns exercise). In JUnit, a Test Case is, surprisingly, a Test Case. A Test Suite is a <a href="http://en.wikipedia.org/wiki/Composite_pattern">composite</a> of Test Case. You can create a Test Suite as a normal object and, programmatically, populate it with as many instances of a test case as you want.</p>

<p>Let&#8217;s see a very simple example. Imagine you have the following structure of folders:</p>

<p><img src="/blog/wp-content/uploads/2009/02/2008-09-18-junit-sample-folder-structure.png" alt="Folder Structure for the sample" /></p>

<p>For each folder, you want to create a Test Suite. For each file, you want to test that its extension must be <code>.txt</code>. In this way, you are going to create a parallel structure using test suites and test cases.</p>

<p>Below, the test suite is shown. It receives a directory in the constructor. It goes through all the contained files and subdirectories. For each subdirectory, a new <code>TestSuite</code> is created and added to the composite (recursively). For each file, a new <code>TestCase</code> is created and added in the same way. The actual testing is going to be done in these test case instances.</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TextFileTestSuite <span style="color: #000000; font-weight: bold;">extends</span> TestSuite <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> TextFileTestSuite<span style="color: #009900;">&#40;</span><span style="color: #003399;">File</span> directory<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span>directory.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">File</span> file <span style="color: #339933;">:</span> directory.<span style="color: #006633;">listFiles</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>file.<span style="color: #006633;">isDirectory</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; addTest<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> TextFileTestSuite<span style="color: #009900;">&#40;</span>file<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">else</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; addTest<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> TextFileTestCase<span style="color: #009900;">&#40;</span>file<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
<span style="color: #009900;">&#125;</span></div></div>

<p>The test case&#8217;s implementation is very straighforward. It receives the concrete file to test in the constructor. It also overrides the <code>runTest()</code> method, where the real testing code is placed.</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp;<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TextFileTestCase <span style="color: #000000; font-weight: bold;">extends</span> TestCase <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">File</span> file<span style="color: #339933;">;</span><br />
&nbsp; <br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> TextFileTestCase<span style="color: #009900;">&#40;</span><span style="color: #003399;">File</span> file<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">super</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">file</span> <span style="color: #339933;">=</span> file<span style="color: #339933;">;</span><br />
&nbsp; &nbsp; setName<span style="color: #009900;">&#40;</span>file.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp; <br />
&nbsp; <span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000066; font-weight: bold;">void</span> runTest<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">throws</span> <span style="color: #003399;">Throwable</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; assertTrue<span style="color: #009900;">&#40;</span>file.<span style="color: #006633;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #006633;">endsWith</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;.txt&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp;<span style="color: #009900;">&#125;</span></div></div>

<p>And that&#8217;s all. You can now check the results on a Test Runner:</p>

<div class="codecolorer-container java blackboard" style="overflow:auto;white-space:nowrap;border:1px solid #9F9F9F;width:435px;"><div class="java codecolorer" style="padding:5px;font:normal 12px/1.4em Monaco, Lucida Console, monospace;white-space:nowrap">&nbsp;<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> AllTests <span style="color: #009900;">&#123;</span><br />
&nbsp; <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> TEST_FOLDER <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;testdata&quot;</span><span style="color: #339933;">;</span><br />
&nbsp;<br />
&nbsp; <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">static</span> Test suite<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span><br />
&nbsp; &nbsp; TestSuite suite <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> TestSuite<span style="color: #009900;">&#40;</span><br />
&nbsp; &nbsp; &nbsp; &nbsp; <span style="color: #0000ff;">&quot;Test for net.jorgemanrubia.junitdinamically.sample&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//$JUnit-BEGIN$</span><br />
&nbsp; &nbsp; suite.<span style="color: #006633;">addTest</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> TextFileTestSuite<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">File</span><span style="color: #009900;">&#40;</span>TEST_FOLDER<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><br />
&nbsp; &nbsp; <span style="color: #666666; font-style: italic;">//$JUnit-END$</span><br />
&nbsp; &nbsp; <span style="color: #000000; font-weight: bold;">return</span> suite<span style="color: #339933;">;</span><br />
&nbsp; <span style="color: #009900;">&#125;</span><br />
&nbsp;<span style="color: #009900;">&#125;</span></div></div>

<p>With the exposed structure of folders, you will obtain something like this:</p>

<p><img src="/blog/wp-content/uploads/2009/02/2008-09-18-junit-sample-test-result.png" alt="Test Results using Eclipse's JUnit Test Runner" /></p>]]></content:encoded>
			<wfw:commentRss>http://jorgemanrubia.net/2008/09/18/generating-junit-test-cases-dynamically/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
