<?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"
	>

<channel>
	<title>Century Minds</title>
	<atom:link href="http://blog.centuryminds.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.centuryminds.com</link>
	<description></description>
	<pubDate>Sun, 05 Oct 2008 15:14:07 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.6.2</generator>
	<language>en</language>
			<item>
		<title>Playing with Ubiquity</title>
		<link>http://blog.centuryminds.com/2008/10/playing-with-ubiquity/</link>
		<comments>http://blog.centuryminds.com/2008/10/playing-with-ubiquity/#comments</comments>
		<pubDate>Sun, 05 Oct 2008 15:14:07 +0000</pubDate>
		<dc:creator>Mikel Alcón</dc:creator>
		
		<category><![CDATA[AJAX]]></category>

		<category><![CDATA[firefox]]></category>

		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/?p=106</guid>
		<description><![CDATA[I have been playing with Firefox Ubiquity this afternoon, and here is the result: A translation command for Word Reference. If you have Ubiquity installed, you should be able to install directly from this page.
Get the source code here

]]></description>
			<content:encoded><![CDATA[<p>I have been playing with Firefox <a href="https://wiki.mozilla.org/Labs/Ubiquity">Ubiquity</a> this afternoon, and here is the result: A translation command for <a href="http://www.wordreference.com/">Word Reference</a>. If you have Ubiquity installed, you should be able to install directly from this page.</p>
<p>Get the source code <a href="http://blog.centuryminds.com/wp-content/uploads/2008/10/wordreference.js">here</a></p>
<link rel="commands" href="http://blog.centuryminds.com/wp-content/uploads/2008/10/wordreference.js" name="Title Goes Here" />
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2008/10/playing-with-ubiquity/feed/</wfw:commentRss>
		</item>
		<item>
		<title>ANTLR Tutorial - Dependency injection language</title>
		<link>http://blog.centuryminds.com/2008/09/antlr-tutorial-dependency-injection-language/</link>
		<comments>http://blog.centuryminds.com/2008/09/antlr-tutorial-dependency-injection-language/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 21:56:35 +0000</pubDate>
		<dc:creator>Mikel Alcón</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/?p=60</guid>
		<description><![CDATA[It&#8217;s been a while since the last time I wrote something here. It turns out that I have been tinkering with ANTLR for the last nine months as part of my new job. So my idea is to write a series of posts to teach you how to create your own languages with ANTLR.
ANTLR is [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been a while since the last time I wrote something here. It turns out that I have been tinkering with ANTLR for the last nine months as part of my new job. So my idea is to write a series of posts to teach you how to create your own languages with ANTLR.</p>
<p>ANTLR is a pretty good top-down LL(*) lexer and parser that allows us to define languages/DSLs without the restrictions of developing it inside a host language, as <a href="http://blog.centuryminds.com/2007/10/21/java-static-imports-fluent-interfaces-builder-pattern-dsl/">Java</a>. As a drawback, writting a language with a parser is much more complicated that hosted DSLs.</p>
<p>I really think that the best way of learning any technology is to practice. That is why I am going to do it in a practical way, building a small language: a dependency injection language.</p>
<p>We are going to implement a language to define beans and give values to its attributes via setters or contructors. The value types allowed for attributes will be:</p>
<ul>
<li>References to other beans</li>
<li>Basic types: String, Integer, Long, boolean.</li>
<li>Lists</li>
<li>Maps</li>
</ul>
<p>In addition, it will allow us to define a default prefix package for beans that will ease the declaration of the bean type. So for example, we might define a bean type as &#8220;dao.UserDAO&#8221; instead of the more verbose &#8220;com.centuryminds.tutorial.dao.UserDAO&#8221;.</p>
<pre># This is a comment
default package prefix com.centuryminds.tutorial

def bean userDAO1 of type dao.UserDAO as
   tableName: "test"
   cacheSize: 200
end

def bean userDAO2 of type dao.UserDAO as
   init "test", 200 # constructor params
   otherAttribute: "other"
end

def bean userManager of type manager.UserManager as
   userDAO: userDAO1
end

def bean myBean of type com.nodefaultpackage.bean.Mybean as
   listVar: ["test", "othertest"]
   mapVar: {"test": 3, "another": 4}
end</pre>
<h2>ANTLR basics</h2>
<p>A parser constructed with a tool like ANTLR needs to be splitted into several phases. In this way each part keeps simpler. These phases generally are the following:</p>
<ul>
<li><strong>Lexer:</strong> It reads a character stream and generates a sequential list of recognized tokens.</li>
<li><strong>Parser:</strong> It receives a list of tokens and identifies the structure of the sentences according to the grammar. Once we have identified the structure we can generate two kinds of outputs: 1) Simply generate the final compiler output or 2) Go further and generate an Abstract Syntax Tree (AST henceforth) for later validations/manipulations.</li>
<li><strong>AST Semantic Validation Phase:</strong> Once we&#8217;ve finished validating the source structure, we have to validate it semantically. A semantic error means something  is grammatically correct but completly meaningless. This phase can be invoked plenty of times and/or work in association with a pre-semantic phase, depending on the grammar complexity.</li>
<li><strong>AST Manipulation Phases</strong>: Once we know that what the source code &#8220;says&#8221; is correct and meaningful, we can pass it through a set of AST manipulation phases that transform the tree representing the code into something more specialized, optimized, etc. For example, removing unused variables, adding extra functionality, static check for nulls, and so forth.</li>
<li><strong>Output Generation Phase</strong>: This is the last phase of a compiler, in which we generate the output: x86 code, Java code, bytecode, xml, whatever you want.</li>
</ul>
<p>Do we need all the phases? Of course not, it depends totally on the complexity of the grammar. The mandatory ones are lexer and parser.</p>
<p>As for our small language, we&#8217;ll implement the following phases:</p>
<ul>
<li><strong>Lexer/Parser:</strong> With ANTLR you can define both in the same grammar file.</li>
<li><strong>Pre-semantic phase:</strong> We are going to identify all the beans present in a file and its associated class types. This will permit us to not depend on the order the beans are defined (without this phase we wouldn&#8217;t be able to reference another bean that is defined below in the file, since we haven&#8217;t parsed that bean yet).</li>
<li><strong>Semantic validation:</strong> Validation of all the types of the code.<em> Has UserManager a field &#8220;dao&#8221; that is of type UserDAO? Does UserDAO has a field named &#8220;table&#8221; of type string that we can assign the literal &#8220;myTable&#8221;?</em></li>
<li><strong>Output generation phase:</strong> In our case it is going to be a Java object structure ready to be accessed by our DI framework. Other options comprise the generation of a Spring XML file, Guice code, etc.</li>
</ul>
<h3>Basic ANTLR Examples</h3>
<p>To develop with ANTLR I recommend ANTLRWorks. This tool is a specialized IDE that supports the definition of ANTLR based languages. Furthermore, with it (and with its built-in debugger!) we&#8217;ll be able to test our lexer/parsers.</p>
<p>Let&#8217;s start off with a basic example:</p>
<pre class="js">grammar Injector;
options {
 output=AST;
}
tokens{
 BEANS;
 BEAN;
 PACKAGE_LIST;
}
@header {
package com.centuryminds.injector;
}
@lexer::header
{
package com.centuryminds.injector;
}

beans	:	beanDef+ -&gt; ^(BEANS beanDef+)
;

beanDef: 'def' Identifier 'of' 'type' packageName -&gt; ^(BEAN Identifier packageName)
;

packageName
	: Identifier ('.' Identifier)*	-&gt; ^(PACKAGE_LIST Identifier+)
;

Identifier    : LETTER ( LETTER | '0'..'9' | '_' )*
;

fragment
LETTER: ('a'..'z' | 'A'..'Z')
;

WS  :  (' '|'\t') {$channel=HIDDEN;}
    ;
NEWLINE : ('\n'|'\r' ) {$channel=HIDDEN;}
    ;

LINE_COMMENT
    : '#' ~('\n'|'\r')* '\r'? NEWLINE {$channel=HIDDEN;}
    ;</pre>
<p>This grammar recognizes this kind of source code:</p>
<pre class="java">def bean1 of type one.example.Example
def bean2 of type another.example
def bean3 of type NoPackage</pre>
<p>This is the AST generated one the code above has been parsed using our grammar:<br />
<a title="simplebeans.png" href="http://blog.centuryminds.com//uploads/2008/08/simplebeans.png"><img src="http://blog.centuryminds.com//uploads/2008/08/simplebeans.png" alt="simplebeans.png" /></a></p>
<p>But, let&#8217;s take a look at each statement in the grammar file:</p>
<p>First of all, we define the grammar name:</p>
<pre>grammar Injector;</pre>
<p>It&#8217;s vital that the grammar file is named accordingly to the grammar name. In this case the file would be named &#8220;Injector.g&#8221;</p>
<p>In the next line we define that the output of the parser will be an AST:</p>
<pre>options {
 output=AST;
}</pre>
<p>These lines:</p>
<pre>tokens{
 BEANS;
 BEAN;
 PACKAGE_LIST;
}</pre>
<p>describe tokens that have not been read from the input -aka <em><strong>virtual tokens</strong></em>, but generated by the parser. In the example, we create three virtual tokens, one for the Beans list, one for each bean definition and one for a Java package definition.</p>
<p>The following lines set the Java package for the generated Lexer and Parser:</p>
<pre>@header {
package com.centuryminds.injector;
}
@lexer::header
{
package com.centuryminds.injector;
}</pre>
<p>After this header code, we have two kinds of statements: <em><strong>token definitions</strong></em> and <em><strong>rules definitions.</strong></em> Tokens are recognized by  the lexer. Rules are applied by the parser to identify the structure of the source code.</p>
<p>Tokens can be defined in two ways:</p>
<ul>
<li>As a <em><strong>named token</strong></em>:
<pre>WORD: ('a'..'z' | 'A'..'Z')+</pre>
<p>It might be referenced by other Tokens/Rules as to avoid repeated code. The name of the tokens must start with an upper case letter. E.g. &#8220;Word&#8221; is a valid token identifier, &#8220;word&#8221; is not ( It will be identified as an action).</li>
<li>As an <em><strong>anonymous token</strong></em> inside a rule:
<pre>rule: 'define' 'alias' WORD 'as' WORD</pre>
<p>where &#8216;define&#8217;, &#8216;alias&#8217; and &#8216;as&#8217; are anonymous tokens.</li>
</ul>
<p>We can also define <em><strong>fragment tokens</strong></em>. These are not really tokens by themselves, but fragments to avoid repetition. For example, LETTER fragment in the following code:</p>
<pre>Identifier    : LETTER ( LETTER | '0'..'9' | '_' )*
;

fragment
LETTER: ('a'..'z' | 'A'..'Z')
;</pre>
<p>Oftentimes, we don&#8217;t want some tokens to be visible for the parser, so that it doesn&#8217;t have to deal with them. In this case, we can ignore them or locate them inside a different <em><strong>token channel</strong></em>. There is a special channel named HIDDEN that maintains the information but hides it to the parser. In our example we hide the whitespaces, new lines and comments.</p>
<pre>WS  :  (' '|'\t') {$channel=HIDDEN;}
    ;
NEWLINE : ('\n'|'\r' ) {$channel=HIDDEN;}
    ;

LINE_COMMENT
    : '#' ~('\n'|'\r')* '\r'? NEWLINE {$channel=HIDDEN;}
    ;</pre>
<p>Finally, we define the rules:</p>
<pre>beans	:	beanDef+ -&gt; ^(BEANS beanDef+)
;

beanDef: 'def' Identifier 'of' 'type' packageName -&gt; ^(BEAN Identifier packageName)
;

packageName
	: Identifier ('.' Identifier)*	-&gt; ^(PACKAGE_LIST Identifier+)
;</pre>
<p>A rule has the following syntax for AST generation:</p>
<pre>ruleName : ruleAction  -&gt; ^(ROOT_ELEMENT child1 child2 ...);</pre>
<p>For example:</p>
<pre>beanDef: 'def' Identifier 'of' 'type' packageName -&gt; ^(BEAN Identifier packageName);</pre>
<p>Here you are a rule named beanDef that recognizes &#8220;def myBean of type a.b.c&#8221;-like strings. In order to recognize the package name it invokes a sub-rule called packageName that in turn returns a sub-AST. Once we parse the structure, we build its corresponding AST with the virtual token BEAN as root, Identifier as the first child and packageName sub tree as the second one.</p>
<p>Of course a rule can have more options: rule parameters, return types, init blocks, etc. I recommend to take a look at the documentation, or await the next tutorial :).</p>
<p>Arbitrary Java code can be attached at any moment of the parsing:</p>
<pre>beanDef: 'def' {System.out.println("after def");}
              Identifier  {System.out.println("Identifier: "+ $Identifier.text);}
              'of' 'type' packageName  {System.out.println("end of the rule");}
               -&gt; ^(BEAN Identifier packageName);</pre>
<p>The ANTLR tokens and rules can be accessed from this Java code: 1) The token text can be retrieved in the form $Identifier.text. 2) The AST corresponding to the sub-rule using $packageName.start</p>
<p>I&#8217;m wrapping it up. In the second part of this tutorial we will see the complete grammar file and the pre-semantic phase. Meanwhile, you can try to complete the grammar as an exercise.</p>
<p>Links:</p>
<ul>
<li><a href="http://www.antlr.org/">ANTLR official site</a></li>
<li><em><a href="http://www.amazon.com/Definitive-ANTLR-Reference-Domain-Specific-Programmers/dp/0978739256%3FSubscriptionId%3D08WX39XKK81ZEWHZ52R2%26tag%3Dws%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3D0978739256">&#8220;The Definitive ANTLR Reference&#8221;</a></em> book written by Terence Parr, the creator of ANTLR</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2008/09/antlr-tutorial-dependency-injection-language/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Weak and Soft References in Java</title>
		<link>http://blog.centuryminds.com/2007/11/weak-and-soft-references-in-java/</link>
		<comments>http://blog.centuryminds.com/2007/11/weak-and-soft-references-in-java/#comments</comments>
		<pubDate>Sat, 10 Nov 2007 00:07:44 +0000</pubDate>
		<dc:creator>rbarroso</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2007/11/10/weak-and-soft-references-in-java/</guid>
		<description><![CDATA[Types of References in Java
Before I get to the point, let me introduce you a couple of classes we&#8217;ll count on when going through examples later.
The first one is Item:

package com.centuryminds.softreferences;

/**
 * An item
 */
class Item
{
  //class members
}

And here comes Group:

package com.centuryminds.softreferences;

import java.util.ArrayList;
import java.util.List;

/**
 * A group of {@link Item}
 */
public class Group&#60;T extends [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Types of References in Java</strong></p>
<p>Before I get to the point, let me introduce you a couple of classes we&#8217;ll count on when going through examples later.</p>
<p>The first one is <code>Item</code>:</p>
<pre style="background-color: #FFFFCC; font-family: courier; font-size: small;">
package com.centuryminds.softreferences;

/**
 * An item
 */
class Item
{
  //class members
}
</pre>
<p>And here comes <code>Group</code>:</p>
<pre style="background-color: #FFFFCC; font-family: courier; font-size: small;">
package com.centuryminds.softreferences;

import java.util.ArrayList;
import java.util.List;

/**
 * A group of {@link Item}
 */
public class Group&lt;T extends Item&gt;
{
  private final List&lt;T&gt; items = new ArrayList&lt;T&gt;();

  public void add(T item)
  {
    items.add(item);
  }

  // other methods
  // ...
}
</pre>
<p>Let&#8217;s start the ball rolling. This is the most common way to create a reference to an object from another one (okay, forget about the factories, IoC and such for a while):</p>
<pre style="background-color: #FFFFCC; font-family: courier; font-size: small;">
Item item = new Item();
</pre>
<p>The <code>item</code> element is called a <em>strong reference</em>. Why is regarded as strong? A new well-kown player named Garbage Collector -GC from now on- comes up , which is responsible of taking care (i.e. freeing) of the memory resources. When an object <code>Client</code>, holding a reference to <code>item</code>:</p>
<p style="text-align:center;"><img align="center" src='http://blog.centuryminds.com/wp-content/uploads/2007/11/im1.png' alt='A strong reference' /></p>
<p>decides to not use <code>item</code> anymore:</p>
<p style="text-align:center;"><img src='http://blog.centuryminds.com/wp-content/uploads/2007/11/im21.png' alt='Not needed anymore' /></p>
<p>after an undetermined time, the GC might decide to dispose of the instance formerly referenced by <code>item</code>.</p>
<p>To illustrate a dime a dozen problem associated to strong references, let&#8217;s suppose we have an object <code>Group</code>, referencing a bunch of <code>Item</code> elements through its internal <code>items</code> list member.</p>
<p style="text-align:center;"><img src='http://blog.centuryminds.com/wp-content/uploads/2007/11/im3.png' alt='Items in a Group' /></p>
<p>As we can see in the figure, there are a couple of external references to the <code>Item</code>s. What happens when these references are not needed anymore and stop pointing at those <code>Item</code>s?</p>
<p style="text-align:center;"><img src='http://blog.centuryminds.com/wp-content/uploads/2007/11/im4.png' alt='No more external references' /></p>
<p>At this point in time, the logic of our application might require us to remove the references to the <code>Item</code>s in our <code>Group</code> instance, since they are not used anymore. That&#8217;s a burden every now and then. Actually, what we are doing is duplicating efforts, since this should be the main responsibility of the GC.</p>
<p><strong>WeakReferences</strong></p>
<p>A <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/WeakReference.html">WeakReference</a> is a reference which does not prevent an object to be reclaimed by the Garbage Collector. A <code>WeakReference</code> allows you to pass  the GC the buck when determining the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ref/package-summary.html#reachability">reachability</a> of an object for you.</p>
<p style="text-align:center;"><img src='http://blog.centuryminds.com/wp-content/uploads/2007/11/im5.png' alt='A weak reference' /></p>
<p>Here is how a <code>WeakReference</code> is created:</p>
<pre style="background-color: #FFFFCC; font-family: courier; font-size: small;">
package com.centuryminds.softreferences;

/**
 * Creating a WeakReference
 */
class A
{
  private final WeakReference&lt;B&gt; b = new WeakReference&lt;B&gt;(new B());

  public B getB()
  {
    return b.<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/Reference.html#get()">get()</a>;
  }
}
</pre>
<p>A small hint here: the method <code>getB()</code> might return <code>null</code> if there are no strong references to the internal reference <code>b</code>. As a matter of fact, the previous is an awful example, since the first call to <code>getB()</code> could return <code>null</code> in case the GC decided to reclaim <code>b</code> and release the memory assigned to it before that method call. Not good.</p>
<p><strong>SoftReferences</strong></p>
<p>Another far more interesting type of reference we may take advantage of is the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/SoftReference.html">SoftReference</a>. In short, this type of reference is like a <code>WeakReference</code>, but tells the GC to not reclaim the wrapped object if there is enough free memory. In other words, if the the GC needs more free memory after reclaiming the objects reachable through strong and weak references, then it will reclaim the instances only reachable through soft references. This, as we will see, makes an excellent candidate for becoming a <em>smart</em> invalidation policy within a cache.</p>
<p><strong>An all-dancing cache</strong></p>
<p>We are going to build up a cache of objects using soft references. Motivation for a cache:</p>
<ol>
<li>There are some elements which are very expensive to retrieve</li>
<li>Those elements are used frequently</li>
<li>The number of such elements (or the number of the most frequently used) is limited</li>
</ol>
<p>In our particular case, the expected behavior of our cache will be:</p>
<blockquote><p>
<em>The objects stored in the cache will be discarded if they are referenced by the cache only AND more free memory is required.</em></p></blockquote>
<p>The Garbage Collector will be in charge of that. The ball is in its court now.</p>
<p>A code snippet is worth a thousand words:</p>
<pre style="background-color: #FFFFCC; font-family: courier; font-size: small;">
package com.centuryminds.softreferences;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

/**
 * Generic cache based on SoftReference's
 */
public class Cache&lt;T&gt;
{
  private final Map&lt;String, SoftReference&lt;T&gt;&gt; cache = new HashMap&lt;String, SoftReference&lt;T&gt;&gt;();

  /**
   * Look an element up by its id
   */
  public T get(final String id)
  {
    T elem = null;

    if (cache.containsKey(id))
    {
      SoftReference&lt;T&gt; ref = cache.get(id);
      elem = ref.get();
    }

    // elem could value null here in two cases:
    // (1) it was not stored in the cache
    // (2) it was garbage collected
    if (elem == null)
    {
      elem = getElemFromExternalService(id);
      cache.put(id, new SoftReference&lt;T&gt;(elem));
    }

    return elem;
  }
}
</pre>
<p>This cache manages elements of unknown types at compile-time, which are retrieved by their ids through calls to <code>getElemFromExternalService(id)</code>. This method may be a private member of the cache, a callback or whatever. The key point here is that the elements are stored as soft references. When an external entity asks the cache for an element, it is linked to it through a strong reference:</p>
<pre style="background-color: #FFFFCC; font-family: courier; font-size: small;">
// returns the wrapped object
elem = ref.get();
...
// a strong reference for the callee
return elem;
</pre>
<p>Bear in mind this is vital to our purposes, since the existence of a strong reference whilst the object is being used will prevent it from being garbage-collected.</p>
<p><strong>Extra goodies</strong></p>
<ul>
<li><a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/WeakHashMap.html">WeakHashMap</a> is a <code>Map</code> whose keys are stored using weak references. Refer to the Javadocs for further information.</li>
<li>A wrapped object by a <code>WeakReference</code> becoming rubbish does not imply that the <code>WeakReference</code> itself defuncts. We thus have to perform some kind of cleanup of those references. <code>WeakReference</code> has got a contructor which accepts a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ref/ReferenceQueue.html">ReferenceQueue</a>, which is used to track stale references to <code>WeakReference</code>s objects. Take a look at the Javadocs to get more information on how to use it.</li>
<li>There is another type reference named <em><a href="http://mindprod.com/jgloss/phantom.html">phantom reference</a></em>, but it is not worth the hassle explaining it for the purposes of this post.</li>
<li>An open question: if <code>WeakHashMap</code> exists, what happened to <code>SoftHashMap</code>? I don&#8217;t want to make a mountain out of a molehill, but this class would be at least as useful as <code>WeakHashMap</code>, <a href="http://archive.devx.com/java/free/articles/Kabutz01/Kabutz01-2.asp">if not more</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2007/11/weak-and-soft-references-in-java/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Java static imports + Fluent interfaces + Builder pattern= DSL</title>
		<link>http://blog.centuryminds.com/2007/10/java-static-imports-fluent-interfaces-builder-pattern-dsl/</link>
		<comments>http://blog.centuryminds.com/2007/10/java-static-imports-fluent-interfaces-builder-pattern-dsl/#comments</comments>
		<pubDate>Sun, 21 Oct 2007 14:13:55 +0000</pubDate>
		<dc:creator>Mikel Alcón</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2007/10/21/java-static-imports-fluent-interfaces-builder-pattern-dsl/</guid>
		<description><![CDATA[After having written nothing for a long time I am back to talk about an interesting bunch of java features. I am talking about DSL in Java, not as clean and powerful as in Ruby but, I think, very interesting for Java developers.
Static import
So, let&#8217;s start with static import, a nice Java feature introduced in [...]]]></description>
			<content:encoded><![CDATA[<p>After having written nothing for a long time I am back to talk about an interesting bunch of java features. I am talking about DSL in Java, not as clean and powerful as in Ruby but, I think, very interesting for Java developers.</p>
<p><strong>Static import</strong></p>
<p>So, let&#8217;s start with <em>static import</em>, a nice Java feature introduced in its 5th version. Until Java 5, we could only import classes for using in our code, so that, instead of using something as ugly as <em>java.util.List list= new java.util.ArrayList()</em> we could simplify by importing the List and ArrayList classes and omit the package class in the creation and usage of the objects.</p>
<p>But, what happens when we want to use static methods or properties of other classes?</p>
<pre name="code" class="java">MyFunnyClass.myMoreFunnierMethod(param)
MyFunnyClass.NotSoFunnyMethod(param)</pre>
<p>Our code gets cluttered by retyping the class part, when this shouldn&#8217;t be necessary. Wouldn&#8217;t it be nice if we were able to express &#8216;I want to use the following static methods in my class, and then use  them as methods defined in our class&#8217; ?</p>
<p>We are lucky, Sun engineers introduced the <em>static import</em> feature in Java5. So how do we use it? This is a piece of cake:</p>
<pre name="code" class="java">import static mypackage.MyClass.interestingMethod
...
interestingMethod("Look ma, I don't need referencing to MyClass!")
</pre>
<p>or we can use wildcards instead:</p>
<pre name="code" class="java">import static mypackage.MyClass.*
...
interestingMethod("Look ma, I don't need referencing to MyClass!")
otherInterestingMethod("Look ma, I don't need referencing to MyClass!")</pre>
<p>It doesn&#8217;t look very useful for what we usually code, and used incorrectly, can derive in a fist of method calls that we don&#8217;t know where they come from. But this feature is going to be crucial for DSLs design in Java&#8230;</p>
<p><strong>Fluent interfaces</strong></p>
<p>Fluent interfaces are a way of designing interfaces that allows us to chain method calls, making our code more readable. So, what does it looks like?</p>
<p>Without fluent interfaces:</p>
<pre name="code" class="java">
Person person= new Person();
person.setName("John");
person.setSurname ("Smith");
person.setPet(new Dog("Charly"));
person.setClothingStyle(ClothingStyle.CASUAL);
</pre>
<p>With a fluent interface API:</p>
<pre name="code" class="java" >Person person = new Person().name("John").surname("Smith").pet(new Dog("Charly")).clothingStyle(ClothingStyle.CASUAL)</pre>
<p>Fluent interfaces make our code look much better.</p>
<p>Using chained methods is as easy as returning the object instance (<em>this</em>) at the end of each fluent method:</p>
<pre name="code" class="java">public class Person{
...
  public Person name(String name){
     this._name=name;
     return this;
  }
...
}</pre>
<p>Fluent interfaces are compatible with having accessor methods (set* and get*) in our classes. Basically, the goal is to ease the API usage and uplift the readability/expressivity of our code.<br />
You can get more information about fluent interfaces in <a href="http://martinfowler.com/bliki/FluentInterface.html">Martin Fowler Blog</a>.</p>
<p><strong>Builder Pattern</strong></p>
<p>The previous two features look very interesting, don&#8217;t they? And it seems that both of them can be used to improve our code readability, and actually they do. But there is a last feature that takes advantage of them , we are talking about the <a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder Pattern</a>.</p>
<p>Quoted from the Wikipedia:</p>
<p><em>The Builder Pattern is a software design pattern. The intention is to separate the construction of a complex object from its representation so that the same construction process can create different representations.</em></p>
<p>In short, we are going to have an object that facilitates the construction of &#8230;other objects! This implies that such a pattern is only useful when we design interfaces for objects that we are going to build up many times with different parameterization or to designing interfaces.</p>
<p>I am the sort of person that prefers an example over loads of paragraphs explaining it , hence go carefully through the following code:</p>
<pre name="code" class="java">
package test;

import java.util.Calendar;
import static java.util.Calendar.* ;
import java.util.Date;

public final class TimeUtil {

    public static DateEx now() {
        return new DateEx(new Date());

    }

    public static DateEx tomorrow() {
        DateEx date = new DateEx(new Date());
        return date.add(days(1));
    }

    public static DateEx yesterday() {
        DateEx date = new DateEx(new Date());
        return date.subtract(days(1));
    }

    public static TimeUnit months(int n) {
        return new TimeUnit(MONTH, n);
    }

    public static TimeUnit years(int n) {
        return new TimeUnit(YEAR, n);
    }

    public static TimeUnit days(int n) {
        return new TimeUnit(DAY_OF_MONTH, n);
    }

    public static DateEx date(Date date) {
        return new DateEx(date);

    }

    private static final class TimeUnit {
        private final int type;
        private final int size;

        public TimeUnit(int type, int size) {
            this.type = type;
            this.size = size;
        }
    }

    public static final class DateEx {

        private final Calendar date;

        public DateEx(Date date) {

            this.date = Calendar.getInstance();
            this.date.setTime(date);
        }

        public Date toDate() {
            return date.getTime ();
        }

        public DateEx add(TimeUnit unit) {
            date.add(unit.type, unit.size);
            return this;

        }

        public DateEx subtract(TimeUnit unit) {
            date.add(unit.type, -unit.size);
            return this;

        }

        public DateEx clearTime() {
            date.set(HOUR_OF_DAY, 0);
            date.clear(MINUTE);
            date.clear (SECOND);
            date.clear(MILLISECOND);
            return this;

        }

        public DateEx firstDayOfMoth() {
            date.set(DAY_OF_MONTH, 1);
            return this;
        }

        public String toString() {
            return date.getTime().toString();

        }
    }
}</pre>
<p>No worries, I am going to explain each line of code, or at least the more interesting ones:</p>
<pre name="code" class="java">
import static java.util.Calendar.* ;
</pre>
<p>This rings a bell, I hope. In this case, importing <em>Calendar</em> static fields allows us to use them as:</p>
<pre name="code" class="java">
            date.set(HOUR_OF_DAY, 0);
            date.clear(MINUTE);
            date.clear (SECOND);
            date.clear(MILLISECOND);
</pre>
<p>We are building a date builder, so we need another class especialized in the construction of <em>java.util.Date</em> objects. This DateEx inner class for:</p>
<pre name="code" class="java">
    public static final class DateEx {
    ...
   }</pre>
<p>The key point here is that DateEx is a construction utility that uses fluent interfaces, so that we can chain methods calls to DateEx objects like:</p>
<pre name="code" class="java">DateEx dateBuilder= new DateEx(new Date()).firstDayOfMonth().clearTime()</pre>
<p>and finally get the date object:</p>
<pre name="code" class="java">Date date= dateBuilder.toDate()</pre>
<p>This code seems alright, yet did you notice what an ugly code we are using to note &#8220;now&#8221; ?<em> new DateEx(new Date())</em> ??? What the hell is this? If I want to express &#8220;now&#8221; I want something that actually does it, and <em>&#8220;new DateEx(new Date..&#8221;</em> doesn&#8217;t at all. Luckily, we might define convenient methods for that sort of things:</p>
<pre name="code" class="java">
    public static DateEx now() {
        return new DateEx(new Date());

    }</pre>
<p>Now, if we import the <em>now</em> static method in our class we can rewrite the previous code as:</p>
<pre name="code" class="java">DateEx dateBuilder= now().firstDayOfMonth().clearTime()</pre>
<p>This is the kind of code that makes me happy (Yes, I know&#8230;). Look at it, and at first glance, you realize &#8220;hey, he is clearing the time part of the first day of the current month&#8221;.</p>
<p>Furthermore, we can add a couple of convenient methods to our new little API:</p>
<pre name="code" class="java">
    public static DateEx tomorrow();
    public static DateEx yesterday();
</pre>
<p>There is also a TimeUnit inner class that allows us to express time units in order to perform time operations to our DateEx objects. For example, what if we wanted to get 1 month and 10 days before the current date? We can do it with our TimeUnit classes and static util methods as:</p>
<pre name="code" class="java">
dateBuilder.subtract(months(1)).subtract(days(10));
</pre>
<p>Cooler than using our good ol&#8217; Calendar friend.</p>
<p>What kind of things can we do with this example API?</p>
<pre name="code" class="java">
package test;

import static test.TimeUtil.*;
import java.util.Date;

public class Example {
    public static void main(String [] params){

        Date date= new Date();
        System.out.println (date(date).add(years(1)));

        System.out.println(now().toDate());
        System.out.println(now().add(days(2)).add(months(1)).subtract(years(1)).clearTime().toDate());
        System.out.println(yesterday()+" - "+now()+" - "+tomorrow());
        System.out.println(now().clearTime().firstDayOfMoth());
    }
}</pre>
<p>Neat, it is not perfect, a lot of brackets are needed which only mess the code up, but as I see it, we have improved the expressivity of our code. In any case, my advice is to learn a new language like Ruby or Groovy, it opens your mind and teaches you different ways of doing things.</p>
<p>On the other hand, Java 7 specification is going to define closures for the Java language, so in the future we are going to be able to do more interesting things!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2007/10/java-static-imports-fluent-interfaces-builder-pattern-dsl/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Paths absolutos</title>
		<link>http://blog.centuryminds.com/2007/08/paths-absolutos/</link>
		<comments>http://blog.centuryminds.com/2007/08/paths-absolutos/#comments</comments>
		<pubDate>Tue, 28 Aug 2007 10:14:45 +0000</pubDate>
		<dc:creator>Mikel Alcón</dc:creator>
		
		<category><![CDATA[Programming]]></category>

		<category><![CDATA[Software Engineering]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2007/08/28/paths-absolutos/</guid>
		<description><![CDATA[Voy a ser corto. Tatuaros en la frente: ¡NO UTILIZARÉ PATHS ABSOLUTOS EN MI APLICACIÓN!
Al resto del equipo no le gusta descargase una clase en la que lo primero que te encuentras es:
"D:\workspace\proyectox\drl\fichero.drl"
¡Usa el classpath y rutas relativas!
Sí, hay excepciones a la regla, pero generalmente aplican a sistemas de producción, no de desarrollo. Por ejemplo, [...]]]></description>
			<content:encoded><![CDATA[<p>Voy a ser corto. Tatuaros en la frente: ¡NO UTILIZARÉ PATHS ABSOLUTOS EN MI APLICACIÓN!</p>
<p>Al resto del equipo no le gusta descargase una clase en la que lo primero que te encuentras es:<br />
<code>"D:\workspace\proyectox\drl\fichero.drl"</code></p>
<p><strong>¡Usa el classpath y rutas relativas!</strong></p>
<p>Sí, hay excepciones a la regla, pero generalmente aplican a sistemas de producción, no de desarrollo. Por ejemplo, el administrador puede querer que los logs vayan a /var/logs/aplicación, pero tu no quieres poner los logs en tu equipo en C:\Documents and Settings\bob\Mis Documentos\logs.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2007/08/paths-absolutos/feed/</wfw:commentRss>
		</item>
		<item>
		<title>You can only have two</title>
		<link>http://blog.centuryminds.com/2007/06/you-can-only-have-two/</link>
		<comments>http://blog.centuryminds.com/2007/06/you-can-only-have-two/#comments</comments>
		<pubDate>Sat, 09 Jun 2007 11:10:18 +0000</pubDate>
		<dc:creator>rbarroso</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2007/06/09/you-can-only-have-two/</guid>
		<description><![CDATA[We are going to learn a bit about a useful tool to help us make decisions prioritizing some traits of our work over the remainder ones. Let me introduce you to the cost-time-quality triangle:

The triangle itself is nothing new or recently discovered, I am sure every manager worldwide is aware of it, or at least [...]]]></description>
			<content:encoded><![CDATA[<p>We are going to learn a bit about a useful tool to help us make decisions prioritizing some traits of our work over the remainder ones. Let me introduce you to the <em>cost-time-quality</em> triangle:</p>
<p align="center"><a href="http://blog.centuryminds.com/wp-content/uploads/2007/06/onlytwo.jpg" title="Cost-Time-Quality Triangle"><img src="http://blog.centuryminds.com/wp-content/uploads/2007/06/onlytwo.jpg" alt="Cost-Time-Quality Triangle" /></a></p>
<p>The triangle itself is nothing new or recently discovered, I am sure every manager worldwide is aware of it, or at least should be! Basically, what we have is a set of three properties (quality, cost and time), and the point here is that, at a given point in time, you can only count on two of them. In other words, if we applied this to a wide range of ways to accomplish with a task, it tells us that we can´t wind up with a cheap and high-quality result in a short time. I will refer to the title of this post: <strong><em>you can only have two</em></strong>. With three elements at play, picking them two by two, we get three possibilities:</p>
<blockquote><p><span style="font-weight: bold">A)</span> <strong>Quality &amp; Time</strong></p></blockquote>
<blockquote><p>High-quality solutions in short times. A steal? Uhmm, beware the available budget!</p></blockquote>
<blockquote><p><span style="font-weight: bold">B)</span> <strong>Cost &amp; Time</strong></p>
<p>Cheap and swift, then? The quality will suffer!</p></blockquote>
<blockquote><p><span style="font-weight: bold">C)</span> <strong>Quality &amp; Cost</strong></p></blockquote>
<blockquote><p>Cheap and good? Be sure you finish it in a realistic span of time! Crackin&#8217; the whip would help &#8230;</p></blockquote>
<p>No combination is better than the others, it depends on your situation. Personally, I find the hardest part to find a balance between the three of them so that you feel sort of successful when you finish the task.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2007/06/you-can-only-have-two/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Anemic Domain Model Antipattern</title>
		<link>http://blog.centuryminds.com/2007/03/anemic-domain-model-antipattern/</link>
		<comments>http://blog.centuryminds.com/2007/03/anemic-domain-model-antipattern/#comments</comments>
		<pubDate>Thu, 08 Mar 2007 22:47:15 +0000</pubDate>
		<dc:creator>Mikel Alcón</dc:creator>
		
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2007/03/08/anemic-domain-model-antipattern/</guid>
		<description><![CDATA[Anemic ¿Qué!??
Hoy toca hablar de patrones, o mejor dicho, de anti patrones. Esas cosas que se deben evitar por norma general.
Mucha de la gente que venimos de lenguajes procedurales (vaya palabro&#8230;) tipo C, tendemos a pensar de esta forma a la hora de programar en Java. ¿Por qué? Por que C no es un lenguaje [...]]]></description>
			<content:encoded><![CDATA[<p>Anemic ¿Qué!??</p>
<p>Hoy toca hablar de patrones, o mejor dicho, de anti patrones. Esas cosas que se deben evitar por norma general.</p>
<p>Mucha de la gente que venimos de lenguajes procedurales (vaya palabro&#8230;) tipo C, tendemos a pensar de esta forma a la hora de programar en Java. ¿Por qué? Por que C no es un lenguaje orientado a objetos. Para representar en C un dato usamos lo siguiente:<br />
<code></code></p>
<p><code>typedef struct point { int x,y; } point;<br />
....<br />
y usamos punto.x </code><br />
Así que cuando vamos a un lenguaje orientado a objetos tendemos a hacer cosas de este tipo:<br />
<code><br />
public class Casa{<br />
private String nombre;<br />
private boolean alquilada;<br />
private boolean habitable;<br />
public void setNombre()...<br />
public String getNombre()...<br />
public void setAlquilada()...<br />
public boolean isAlquilada()...<br />
....<br />
}</code></p>
<p><code>public class Persona{<br />
private String nombre;<br />
private List casas;<br />
public void setNombre()...<br />
public String getNombre()...<br />
public void setCasas()...<br />
public List getCasas()...<br />
}<br />
..</code><br />
<code> List casasNoAlquiladas= new ArrayList();<br />
for(Persona persona: personas){<br />
for (Casa casa : persona.getCasas()){<br />
if (! casa.isAlquilada() &amp;&amp; casa.isHabitable()){<br />
casasNoAlquiladas.add(casa);<br />
}<br />
}<br />
}<br />
</code></p>
<p>&#8230;.</p>
<p>¿Cuál es el problema con esto? Pues que estamos utilizando las clases de negocio como simples estructuras de datos. Hemos avanzado en la tecnología, ¡ Avancemos  en su uso también! Vale, siempre lo has hecho así, te sientes cómodo con esta solución ¿Con qué problemas te vas a encontrar?</p>
<ul>
<li>Lógica de negocio dispersa por toda la aplicación, seguramente incluso repetida.</li>
<li>Complejidad a la hora de hacer las clases controladoras</li>
<li>Estamos exponiendo la forma en que mantenemos las casas al exterior. Solo debemos exponer las entities, no los value objects! (esto daría para otro post)</li>
<li>¿La lista de casas que devolvemos es inmutable? ¡Cuidado!</li>
<li>Sumando todo lo anterior: Más complejidad = más bugs, además de menos extensible</li>
</ul>
<p>Bueno y ¿Cómo lo solucionaríamos? Muy fácil, introduciendo la lógica de negocio en las clases de negocio:<br />
<code><br />
public class Casa{</code></p>
<p>&#8230;.</p>
<p><code> private final String nombre;<br />
private boolean alquilada;<br />
private boolean habitable;<br />
public String getNombre()...<br />
public void setAlquilada()...<br />
public boolean isAlquilada()...<br />
public boolean isAlquilable(){<br />
return (! casa.isAlquilada() &amp;&amp; casa.isHabitable());<br />
}</code></p>
<p>&#8230;.<br />
}</p>
<p><code>public class Persona{<br />
private String nombre;<br />
private List casas;<br />
public void setNombre()...<br />
public String getNombre()...<br />
public void setCasas()...<br />
public List getCasasAlquilables(){<br />
List list= new ArrayList();<br />
for (Casa casa: casas){<br />
if (casa.isAlquilable()) list.add(casa);<br />
}<br />
return list;<br />
}<br />
}<br />
..</code><br />
<code> List casasNoAlquiladas= new ArrayList();<br />
for(Persona persona: personas){<br />
casasNoAlquiladas.addAll(persona.getCasasAlquilables());<br />
}<br />
</code><br />
Más fácil ¿Verdad? Si no conocías este error común, seguro que ahora te vienen a la memoria un montón de casos en los que podrías ahorrar mucho en código y hacerlo mucho más extensible.</p>
<p>Otro ejemplo: En cierto cliente, hace un cierto tiempo y haciendo cierta aplicación <img src='http://blog.centuryminds.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> De una clase muy importante en el modelo (Entity) sacabamos unos cuantos informes. En un momento dado, me pidieron que si se podía cambiar cierta lógica a la hora de generar los informes.  Mi respuesta fue: tardo 2 segundos (y uno para pulsar ctrl+shif+T  en Eclipse!! ). ¿Por qué? Porque mi clase de ese entity tan importante tenía lo siguiente:<br />
<code><br />
List&lt;Dato&gt; getSubObjetosQueCumplenCiertaCondiciónDeNegocio(){<br />
for....{<br />
if (obj.condicion1() &amp;&amp; obj.condicion2() &amp;&amp; entity.....)</code></p>
<p><code>        lista.add(...)</code><br />
&#8230;</p>
<p><code>}<br />
}<br />
</code></p>
<p>Lo que me pedían era un cambio de negocio. Yo había entendido mál, un objeto de tipo Dato debía de cumplir obj.condicion() &amp;&amp; obj.condicion3(), pero el cambio no suponía el menor esfuerzo. ¿Cuánto hubiese costado si hubiesemos tenido este código disperso por toda la aplicación?</p>
<p>Se puede discutir si incluir los DAO dentro del objeto de negocio es bueno o malo (Rails y Grails lo hacen),  si algúna lógica concreta debería ir en los controladores, pero al menos este tipo de cosas creo que pueden ayudarte bastante.</p>
<p>Bueno, no se si ha quedado claro, hoy no he dormido mucho y estoy muuuuuy cansado <img src='http://blog.centuryminds.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2007/03/anemic-domain-model-antipattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>You Need Code Reviews</title>
		<link>http://blog.centuryminds.com/2007/02/you-need-code-reviews/</link>
		<comments>http://blog.centuryminds.com/2007/02/you-need-code-reviews/#comments</comments>
		<pubDate>Mon, 05 Feb 2007 23:08:59 +0000</pubDate>
		<dc:creator>rbarroso</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2007/02/05/you-need-code-reviews/</guid>
		<description><![CDATA[Look at this code:
(within a while body)

...
if (log.isDebugEnabled()) log.debug("Parsing line " + (lineNumber++));
...
lineNumber used here
...
You might be wondering: what´s wrong with it? Well, it turns out that this sort of construction it could become extremely difficult to spot in certain conditions. Imagine a hypothetical  situation where this code is not working properly in the [...]]]></description>
			<content:encoded><![CDATA[<p>Look at this code:</p>
<p><em>(within a while body)</em><br />
<code><br />
...<br />
if (log.isDebugEnabled()) log.debug("Parsing line " + (lineNumber++));<br />
...<br />
lineNumber used here<br />
...</code></p>
<p>You might be wondering: what´s wrong with it? Well, it turns out that this sort of construction it could become extremely difficult to spot in certain conditions. Imagine a hypothetical  situation where this code is not working properly in the production environment, and meanwhile the developer in charge of this block of code -the guy as cool as a cucumber- is totally sure about the correctness of it. Okay, you got it, you may be thinking of me: &#8220;How noob this guy is!&#8221;; but Hey!, sometimes you are toiling late in the night and this kind of bugs pass unnoticed until you receive an email from your Development Manager muttering:</p>
<blockquote><p><em>Subject: Potential bug</em></p>
<p><em>I have come across with this statement -</em><em>incidentally- while surfing the code. Beware that the log will be printed out only if the log level is set to DEBUG, so the lineNumber variable won´t be incremented.</em></p>
<p><em>All the best,</em></p>
<p><em>Your Development Manager</em></p></blockquote>
<p>Guess which level the Production Support had established in their environment? Fortunately, I started off saying &#8220;<em>Imagine a hypothetical  situation &#8230;</em>&#8220;.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2007/02/you-need-code-reviews/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Share your knowledge</title>
		<link>http://blog.centuryminds.com/2006/12/share-your-knowledge/</link>
		<comments>http://blog.centuryminds.com/2006/12/share-your-knowledge/#comments</comments>
		<pubDate>Fri, 15 Dec 2006 22:32:44 +0000</pubDate>
		<dc:creator>rbarroso</dc:creator>
		
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2006/12/15/share-your-knowledge/</guid>
		<description><![CDATA[Thomas Jefferson said:
And no matter how many people share it, the idea is not diminished. When I hear your idea, I gain knowledge without diminishing anything of yours. In the same way, if you use your candle to light mine, I get light without darkening your. Like fire, ideas encompass the globe without lessening their [...]]]></description>
			<content:encoded><![CDATA[<p>Thomas Jefferson <a href="http://www.aaronsw.com/weblog/001115" title="And no matter ..." target="_blank">said</a>:</p>
<blockquote><p><em>And no matter how many people share it, the idea is not diminished. When I hear your idea, I gain knowledge without diminishing anything of yours. In the same way, if you use your candle to light mine, I get light without darkening your. Like fire, ideas encompass the globe without lessening their density.</em></p></blockquote>
<p>Sometimes, in this hectic world, you realise that your knowledge about a subject has increased considerably, and probably at that moment you are an expert on it. The &#8220;problem&#8221; now is how you ought to handle that situation in regards to your team mates. You can keep such expertise for your own benefit, considering them a sort of nuissance, if not worse. But that is not supportive. As I see it, helping your co-workers is a professional duty, no matter the reason. No matter the guy. <strong>You must do it because you must do it</strong>. And that´s all. There shouldn´t have to exist more reasons besides that one. Yeah, I know, there are lotsa situations where excuses arise in order not to help someone, but anyway I think it is a good principle to start with. Write it down in your tickler file.</p>
<p>Nonetheless,  there are some important benefits of  being supportive and willing to give others a hand:</p>
<ol>
<li>You can cause a great impact in the morale of your huddle, because your positive attitude might make them want to better themselves in turn. The overall competence of your team spikes. Betcha! That´s good for you as well. If this doesn´t work, pull out.</li>
<li>You may <em>think</em> you are an expert. Believe me: even experts are requested to answer questions they don´t know about! IMHO, I consider this awesome. The search for those answers permits you to assimilate unexplored areas of the topic on discussion.  Therefore, you are gaining more insight, which is always neat. For example, the other day someone asked me about subversion, and how this system performs the merging. I <em>thought</em> I had that under control. I explained to him the basics of the merging in subversion, the reason it should be called <em>diff-and-apply</em> instead of merging, how two revisions from the origin and destination trees are applied to the working copy, and so on. So far, so good. All the same, point in time, he asked me how a merge was actually applied to a specific file in the working copy. That was kinda going thorugh bad times, <em><strong>because I didn´t understand it seamlessly</strong>,</em> hence I wasn´t able to provide him with an answer. Well, in fact, I had to look up that section in a subversion book, read it thoroughly, sink in all that stuff, and lastly give to him the right answer. I could have told him to grab a book and look it up. That would have been a lazy behaviour and, what it´s much worse, I would still be thinking I have that part under control now. It´s wonderful not to be an expert in nearly anything, isn´t it?</li>
<li><strong>Corollary:</strong> the rest of the team come to trust they can rely on you when they feel they´re dead in the water.</li>
</ol>
<p><strong>Corollary to the last Corollary:</strong> Be nice <img src='http://blog.centuryminds.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2006/12/share-your-knowledge/feed/</wfw:commentRss>
		</item>
		<item>
		<title>AbstractTransactionalSpringContextTests meets TestNG</title>
		<link>http://blog.centuryminds.com/2006/12/abstracttransactionalspringcontexttests-meets-testng/</link>
		<comments>http://blog.centuryminds.com/2006/12/abstracttransactionalspringcontexttests-meets-testng/#comments</comments>
		<pubDate>Tue, 12 Dec 2006 20:53:57 +0000</pubDate>
		<dc:creator>rbarroso</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://blog.centuryminds.com/2006/12/12/abstracttransactionalspringcontexttests-meets-testng/</guid>
		<description><![CDATA[Introduction 
In the search of an alternative to JUnit, in relation to the testing of our classes, we -Mikel and I- decided to give TestNG a try. This testing framework takes advantage of a useful feature introduced in the release 5.0 of the Java Language: the annotations. In addition, it provides a rich set of [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Introduction </strong></p>
<p>In the search of an alternative to <a href="http://www.junit.org/" title="JUnit" target="_blank">JUnit</a>, in relation to the testing of our classes, we -Mikel and I- decided to give <a href="http://testng.org/" title="TestNG" target="_blank">TestNG</a> a try. This testing framework takes advantage of a useful feature introduced in the release 5.0 of the Java Language: the <a href="http://jcp.org/en/jsr/detail?id=175" title="Annotations (JSR)" target="_blank">annotations</a>. In addition, it provides a rich set of facilities to ease the unit and integration testing of Java classes, like groups and data providers. Unfortunately, these are very well explained in the home page of the project, so let´s consider them as being out of the scope in regards to the main thread of this post.</p>
<p><strong>The Problem</strong></p>
<p>What we want to have: test cases running within a transactional context AND take advantage of the TestNG facilities. The former is neatly addressed by a class named <a href="http://www.springframework.org/docs/api/org/springframework/test/AbstractTransactionalSpringContextTests.html" title="AbstractTransactionalSpringContextTests" target="_blank">AbstractTransactionalSpringContextTests</a>, present in the Spring´s mock package. The latter, well, pretty obvious. What it isn´t so obvious is the way to combine both. Why? TestNG does not provide a direct way to surround the test cases with a transaction, so a rollback action is performed at the end of every test. This way, we are able to avoid side effects between test executions, because one test inserts a row and the next one didn´t expect it, or because a database row is updated between executions breaking some assertions, or because &#8230; you get the idea. When we decided to start using TestNG as our main framework for testing, this absence lead us to ask Cedric Beust, the TestNG project leader, about some way to accomplish with the transaction stuff. He responded us very kind and rapidly, recommending to implement the rollbacking in an <code>@AfterMethod</code> method.</p>
<p><strong>TransactionRollbackTearDownTestCase </strong></p>
<p><em>Note: for this class&#8217;s name origin, take a look at <a href="http://xunitpatterns.com/Transaction%20Rollback%20Teardown.html" title="Transaction Rollback Tear Down" target="_blank">this site </a></em></p>
<p>Probably Cedric is completely right, but we like how <code>AbstractTransactionalSpringContextTests</code> does its business, and of course, the integration with the Spring´s IoC in order to inject the dependencies to the test classes. For that reason, we have come up with an adapter class, which permits us to run TestNG test cases within the transactional context provided by the Spring class. It is kinda adapter because we change the way the class <code>AbstractTransactionalSpringContextTests</code> is used (i.e. inheriting from it), right now we can extend from the new base class and define our test cases as the usual TestNG manner (i.e. through the use of annotations). It is not an adapter as in the software design patterns.</p>
<p>The class is named <code>TransactionalRollbackTearDownTestCase</code>, and following there is a diagram of its relationships:</p>
<p style="text-align:center;"><img src="https://centuryminds.wordpress.com/files/2006/12/testng.png" alt="TransactionalRollbackTeardownTestCase" /></p>
<p>The code of this class could prove more descriptive than me trying to explain how it does its job:</p>
<pre>
package com.centuryminds.test;

import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springframework.test.AbstractTransactionalSpringContextTests;

import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;

/**
 * Base test class which permits: 1) Inject dependencies defined in a Spring
 * context. The aforementioned dependencies must be declared as protected
 * members 2) Perform a rollback action after every test. Basically, it
 * acts as an adapter between the TestNG test case structure and the facilities
 * provided by the class {@link AbstractDependencyInjectionSpringContextTests}
 * in the Spring package
 *
 * @see AbstractDependencyInjectionSpringContextTests
 * @see AfterMethod
 * @see BeforeMethod
 */
public abstract class TransactionRollbackTearDownTestCase extends
		AbstractTransactionalSpringContextTests
{

	/**
	 * Test Fixture
	 *
	 * @throws Exception if a error occurred during the fixture execution
	 * @see {@link AbstractDependencyInjectionSpringContextTests#setUp()}
	 * @see {@link AbstractDependencyInjectionSpringContextTests#setPopulateProtectedVariables(boolean)}
	 */
	@BeforeMethod
	protected final void before() throws Exception
	{
		setPopulateProtectedVariables(true);
		super.setUp();
	}

	/**
	 * Test Teardown
	 *
	 * @throws Exception if a error occurred during the teardown execution
	 * @see {@link AbstractDependencyInjectionSpringContextTests#tearDown()}
	 */
	@AfterMethod
	protected final void after() throws Exception
	{
		super.tearDown();
	}
}</pre>
<p>As it can be seen, this class is really simple. It defines two final methods, both TestNG-annotated which delegate the test fixture and teardown actions to the underlying parent implementation. Therefore, every time a test case method is going to be executed, <code>before() </code>will inject the dependencies defined in the Spring context and will create and start a new transaction context. The method <code>tearDown()</code> in turn will perform a rollback action just after the test ends.</p>
<p><strong>Extending the Hierarchy </strong></p>
<p>Obviously, the class above is not enough: where are the dependencies to be injected defined? We have to tell <code>AbstractTransactionalSpringContextTests</code> where to look for them. This can be achieved by a subclass of <code>TransactionalRollbackTearDownTestCase</code>, for example:</p>
<pre>
package com.centuryminds.test;

/**
 * Base test class that specifies the spring contexts containing the dao
 * definitions. The subclasses must provide an implementation of the method
 * {@link #getConfigLocations()}, specifying the files with the spring contexts
 * holding the definitions of the dao and its dependencies
 */
public class BaseDAOTestCase extends TransactionRollbackTearDownTestCase
{
	/**
	 * @see org.springframework.test.AbstractDependencyInjectionSpringContextTests#getConfigLocations()
	 */
	@Override
	protected String[] getConfigLocations()
	{
		return new String[] { "classpath:applicationContext-datasource.xml",
				"classpath:applicationContext-service.xml" };
	}
}</pre>
<p><strong>The Actual Test Class </strong></p>
<p>One important benefit of the separation above is that we could define several BaseDAO* classes, each one of them declaring its own context set. Let´s see an example DAO test class extending from BaseDAOTestCase:</p>
<pre>
package com.centuryminds.test;

import java.util.HashSet;

import org.testng.annotations.Test;

import com.threefish.aquarium.dao.hibernate.GenericHibernateDAO;
import com.threefish.aquarium.model.Role;
import com.threefish.aquarium.model.User;

/**
 * Tests for RoleDAO
 */
public class RoleDAOTest extends BaseDAOTestCase
{
	/** role dao */
	protected GenericHibernateDAO roleDAO;

	/** role */
	private Role role;

	@Test
	public void testCreate() throws Exception
	{
		int amount = roleDAO.findAll().size();

		// let's create a new role to persist
		role = new Role();
		role.setName("testrole");
		role.setDescription("Master of Universe");
		role.setUsers(new HashSet());

		roleDAO.makePersistent(role);

		assertNotNull(role.getId());
		assertEquals(amount + 1, roleDAO.findAll().size());
	}

	@Test
	public void testSuccessfulGet() throws Exception
	{
		role = roleDAO.findById(Long.valueOf(1));

		assertEquals("admin", role.getName());
	}

	@Test
	public void testUpdate() throws Exception
	{
		role = roleDAO.findById(Long.valueOf(1));
		role.setDescription("Super Administrator Role");
		roleDAO.makePersistent(role);

		assertEquals("Super Administrator Role", role.getDescription());
	}
}</pre>
<p>The <code>RoleDAO</code> test class makes use of a custom generic DAO framework, but despite that I think it is pretty self-explanatory. We shall try to explain the generic DAO related interfaces and classes in another post when we get a chance, but for now we have enough.</p>
<p>The test methods are executed within a transaction per test method, which is rollbacked at the very end of it. So, the role insert in the first test (<code>testCreate()</code>), would be rollbacked and future tests depending on the initial state (i.e. the state before <code>testCreate()</code> ran) wouldn´t be affected. We accomplished with the goal of executing the test cases in isolation. Thanks Spring! We accomplished with the goal of using some of the features offered by TestNG. Thanks to you as well!</p>
<p><strong>Future</strong></p>
<p>We are aware about the drawbacks of this solution, and we are pretty sure about the fact that there must exist a more sophisticated solution out there, hence we are very willing to listen to your suggestions to improve the general structure of our current one. We&#8217;ll stay tuned &#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.centuryminds.com/2006/12/abstracttransactionalspringcontexttests-meets-testng/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 1.088 seconds -->
<!-- Cached page served by WP-Cache -->
