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

<channel>
	<title>got object?</title>
	<atom:link href="http://www.gotobject.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gotobject.com</link>
	<description>a quickmix of random thoughts</description>
	<pubDate>Tue, 11 Aug 2009 22:48:14 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>FilterQ - A lightweight filtering API for Iterable Objects.</title>
		<link>http://www.gotobject.com/2009/07/filterq-a-lightweight-filtering-api-for-iterable-objects/</link>
		<comments>http://www.gotobject.com/2009/07/filterq-a-lightweight-filtering-api-for-iterable-objects/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 23:04:52 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[functional programming]]></category>

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

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

		<category><![CDATA[First-class functions]]></category>

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=56</guid>
		<description><![CDATA[Wow, version 0.3 of FilterQ has been released and is available at filterq.googlecode.com. Several cool features have been added, several bugs have been fixed. But the best of all things, at least for me, is that I am using it in my JUnit 4.5 extensions project. FilterQ is my lightweight filtering API for Iterable Objects [...]]]></description>
			<content:encoded><![CDATA[<p>Wow, version 0.3 of FilterQ has been released and is available at <a href="http://filterq.googlecode.com">filterq.googlecode.com</a>. Several cool features have been added, several bugs have been fixed. But the best of all things, at least for me, is that I am using it in my JUnit 4.5 extensions project. FilterQ is my lightweight filtering API for Iterable Objects (yeah, you got it right, it is an API for objects implementing the Java&#8217;s Iterable<T> interface). The concepts behind FilterQ&#8217;s API have been inspired by LinQ, and Quaere use cases. In order to illustrate its specific API methods, I have compiled some interesting usage scenarios, which will be distributed in 3 posts. The first post will illustrate the basic usage scenarios. While these are small scenarios they convey the power of this API.</p>
<p>Basic usage scenarios<br />
	1. basic filtering</p>
<pre name="code" class="java">

// select all the prime numbers found within (0...1000),
// while making sure that that 117 is not included in our result.
from(range(1,1000)).where(numIsPrime()).select(not(eq(117)));
// or simply
from(range(1,1000, numIsPrime().or(not(eq(117))))).select();

//  which one should I choose? well, it depends. If you prefer readability
//  over brevity, then choose the first one.
</pre>
<p>	2. dealing with results</p>
<pre name="code" class="java">

//  from the above results, count all of the prime numbers greater than 100 and less than 500.
//  Let&#039;s assume that the result is stored in a var of type &quot;Iterable&lt;Integer&gt;&quot; called foo.
count(foo, gt(100).and(lt(500));

// or simply count them all
count(foo);
</pre>
<p>	3. dealing with two Iterables in a single loop</p>
<pre name="code" class="java">

for(Integer each : intersect(range(1,100, mod(3)), range(60,250, mod(13)))){
       System.out.println(each)
}

// or
for(Integer each : union(range(1,100, mod(3)), range(60,250, mod(13))))){
	System.out.println(each)
}
</pre>
<p>	3. dealing with transformations</p>
<pre name="code" class="java">

final Integer[] numbers = {5, 4, 1, 3, 9, 8, 6, 7, 2, 0};
final String[]   strings   = {&quot;zero&quot;,&quot;one&quot;,&quot;two&quot;,&quot;three&quot;,&quot;four&quot;,&quot;five&quot;,&quot;six&quot;,&quot;seven&quot;,&quot;eight&quot;, &quot;nine&quot; };
final Iterable&lt;String&gt;  result  =  from(numbers).apply(indexed(strings));

System.out.println(asList(result));
// result: five, four, one, three, nine, eight, six, seven, two, zero	
</pre>
<p>	4. skipping elements</p>
<pre name="code" class="java">

from(Arrays.asList(1, 2, 3, 40, 20, 30, 100)}).where(gt(20).and(lt(100))).skip(1);
// and the result is?
</pre>
<p>	5. ordering elements</p>
<pre name="code" class="java">

from(Arrays.asList(&quot;John&quot;, &quot;Mary&quot;, &quot;Roberto&quot;, &quot;David&quot;, &quot;Fernando&quot;)).orderBy(length()).select();
// and the result is? [John, Mary, David, Roberto, Fernando]
</pre>
<p>	6. dealing with objects&#8217; private members</p>
<pre name="code" class="java">

final Person a = new Person(&quot;John&quot;, &quot;Peterson&quot;);
final Person b = new Person(&quot;Pete&quot;, &quot;Peterzon&quot;);

final List&lt;Person&gt; ppl = Arrays.asList(a, b);
final Iterable&lt;Person&gt; t = from(ppl).where(eq(&quot;lastName&quot;, &quot;Peterson&quot;)).select();

System.out.println(t);
// and the result is?	   	   
</pre>
<p>	7. concatenating elements</p>
<pre name="code" class="java">

final List&lt;Integer&gt; a = Arrays.asList(1, 2, 3, 3, 4);
final List&lt;Integer&gt; b = Arrays.asList(2, 3, 4);

final Iterable&lt;Integer&gt; result = concat(a, b);
System.out.println(result);

// and the result is?
</pre>
<p>This is all for today. I&#8217;ve just covered the first out of 3 posts covering FilterQ&#8217;s usage scenarios. Next post will illustrate other functionality, such as FilterQ&#8217;s XML support and Java Reflection API. Till next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2009/07/filterq-a-lightweight-filtering-api-for-iterable-objects/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Varargs Null Checking</title>
		<link>http://www.gotobject.com/2009/05/varargs-null-checking/</link>
		<comments>http://www.gotobject.com/2009/05/varargs-null-checking/#comments</comments>
		<pubDate>Fri, 08 May 2009 23:53:57 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[programming]]></category>

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

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=52</guid>
		<description><![CDATA[VarArgs Null checking? This should be easy, right? All we need to do is put a &#8220;VarArgs&#8221;.length == 0 check before the important method&#8217;s body and we are set (See Checker class), correct? 


class Checker {
	public void check(Arg... args){
		if(args.length == 0) return;
		final List&#60;Arg&#62; someArgs = Arrays.asList(args);
		for(Arg each: someArgs){
			System.out.println(&#34;checked:&#34; + each.toString());
		}
	}
}

class Arg{
  private final String [...]]]></description>
			<content:encoded><![CDATA[<p>VarArgs Null checking? This should be easy, right? All we need to do is put a &#8220;VarArgs&#8221;.length == 0 check before the important method&#8217;s body and we are set (See Checker class), correct? </p>
<pre name="code" class="java">

class Checker {
	public void check(Arg... args){
		if(args.length == 0) return;
		final List&lt;Arg&gt; someArgs = Arrays.asList(args);
		for(Arg each: someArgs){
			System.out.println(&quot;checked:&quot; + each.toString());
		}
	}
}

class Arg{
  private final String name;
  Arg(String name){this.name = name;}
  @Override public String toString(){return name;}
}
</pre>
<p>The above check should work nicely under the following circumstances </p>
<pre name="code" class="java">

new Checker().check(new Arg(&quot;one&quot;), new Arg(&quot;two&quot;));
new Checker()
</pre>
<p>Unfortunately, it won&#8217;t work under the following one, which will actually throw the exception that you were trying to avoid: NullPointerException.</p>
<pre name="code" class="java">

new Checker().check(null, null); // Ooh! a NullPointerException....
</pre>
<p>how to fix this? Easy&#8230;</p>
<pre name="code" class="java">

class Checker {
	public void check(Arg... args){
		if(args.length == 0 || Arrays.asList(args).contains(null)) return;
		final List&lt;Arg&gt; someArgs = Arrays.asList(args);
		for(Arg each: someArgs){
			System.out.println(each.toString());
		}
	}
}
</pre>
<p>This should definitely work nicely. This is all for today. Until next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2009/05/varargs-null-checking/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Reading files a la for-each loop.</title>
		<link>http://www.gotobject.com/2009/01/reading-files-a-la-foreach-loop/</link>
		<comments>http://www.gotobject.com/2009/01/reading-files-a-la-foreach-loop/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 20:26:58 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[programming]]></category>

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

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=25</guid>
		<description><![CDATA[This post will show you how to use the for-each loop for reading files.  This approach tried to replace the following approach


    try {
        BufferedReader in = new BufferedReader(new FileReader(&#34;infilename&#34;));
        String str;
       [...]]]></description>
			<content:encoded><![CDATA[<p>This post will show you how to use the for-each loop for reading files.  This approach tried to replace the following approach</p>
<pre name="code" class="java">

    try {
        BufferedReader in = new BufferedReader(new FileReader(&quot;infilename&quot;));
        String str;
        while ((str = in.readLine()) != null) {
            process(str);
        }
        in.close();
    } catch (IOException e) {
    }
</pre>
<p>with this one:</p>
<pre name="code" class="java">

    final IterableFileReader e = new IterableFileReader(new File(&quot;SomeFile.WithSomeExtension&quot;));
    for(String eachLine: e){
        process(eachLine);
    }
</pre>
<p>The source code of my solution is illustrated herein:</p>
<pre name="code" class="java">

public class IterableFileReader implements Iterable&lt;String&gt;{
    private final BufferedReader reader;
    public IterableFileReader(InputStream is, Charset encoding) throws IOException {
        reader = new BufferedReader(new InputStreamReader(is, encoding.toString()));
    }

    public IterableFileReader(File file) throws IOException {
        this(new FileInputStream(file), Charset.UTF_8);
    }

    public Iterator&lt;String&gt; iterator() {
        return new Iterator&lt;String&gt;(){
            private String line;
            public boolean hasNext() {
                try {
                    line = reader.readLine();
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
                return line != null;
            }

            public String next() {
                return line;
            }

            public void remove() {
                throw new UnsupportedOperationException(&quot;remove is not supported. sorry dude!&quot;);
            }
        };
    }
}
</pre>
<p>I hope you will find this approach useful. Ok, time is up. I gotta go, my daughter is crying. Till next time.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2009/01/reading-files-a-la-foreach-loop/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Still alive&#8230;.</title>
		<link>http://www.gotobject.com/2009/01/still-alive/</link>
		<comments>http://www.gotobject.com/2009/01/still-alive/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 00:32:38 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

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

		<guid isPermaLink="false">http://www.gotobject.com/2009/01/still-alive/</guid>
		<description><![CDATA[I am still here, with less time than ever, but still here. I will start blogging again very soon.
]]></description>
			<content:encoded><![CDATA[<p>I am still here, with less time than ever, but still here. I will start blogging again very soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2009/01/still-alive/feed/</wfw:commentRss>
		</item>
		<item>
		<title>More on Filters as First-class functions.</title>
		<link>http://www.gotobject.com/2008/10/more-on-filters-first-class-functions/</link>
		<comments>http://www.gotobject.com/2008/10/more-on-filters-first-class-functions/#comments</comments>
		<pubDate>Fri, 17 Oct 2008 01:49:15 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[functional programming]]></category>

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

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

		<category><![CDATA[First-class functions]]></category>

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=21</guid>
		<description><![CDATA[By expanding (more like enhancing  ) the filter pattern described here and borrowing some of the beauties of the matcher pattern in Guice, I coded a more concise version of this filter pattern. Now this pattern&#8217;s implementation has a fluent API for combining other filters together, a place where all filters can be defined, [...]]]></description>
			<content:encoded><![CDATA[<p>By expanding (more like enhancing <img src='http://www.gotobject.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ) the filter pattern described <a href="http://www.erik-rasmussen.com/blog/2008/01/18/the-filter-pattern-java-conditional-abstraction-with-iterables/">here</a> and borrowing some of the beauties of the <a href="http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/matcher/Matcher.html">matcher pattern</a> in Guice, I coded a more concise version of this filter pattern. Now this pattern&#8217;s implementation has a fluent API for combining other filters together, a place where all filters can be defined, a way of negating filters, etc. Further in this post I will provide a simple example that describes how the newer version of this pattern can be utilize. But before showing the example, I will provide the pattern&#8217;s newer definition and implementation herein.</p>
<p>Filter pattern&#8217;s main interface&#8230;</p>
<pre name="code" class="java">

public interface Filter &lt;T&gt; {
    Filter &lt;T&gt; and(Filter &lt;? super T&gt; thing);
    Iterable &lt;T&gt; filter(Iterable &lt;T&gt; thing);
    boolean evaluate(T thing);
    Filter &lt;T&gt; or(Filter &lt;? super T&gt; thing);
}
</pre>
<p>and its abstract implementation&#8230;</p>
<pre name="code" class="java">

public abstract class AbstractFilter &lt;T&gt; implements Filter &lt;T&gt; {
    public Filter&lt;T&gt; and(Filter&lt;? super T&gt; thing) {
        return new AndFilter&lt;T&gt;(this, thing);
    }

    public Iterable&lt;T&gt; filter(final Iterable&lt;T&gt; thing) {
        return new Iterable&lt;T&gt;(){
            public Iterator&lt;T&gt; iterator() {
                return new FilteringIterator&lt;T&gt;(
                	AbstractFilter.this,
                	thing.iterator()
                );
            }
        };
    }

    public Filter&lt;T&gt; or(Filter&lt;? super T&gt; thing) {
        return new OrFilter&lt;T&gt;(this, thing);
    }

    private static class AndFilter&lt;T&gt; extends AbstractFilter&lt;T&gt; {
        private final Filter&lt;? super T&gt; one;
        private final Filter&lt;? super T&gt; two;

        AndFilter(
        	Filter&lt;? super T&gt; one,
            Filter&lt;? super T&gt; two
        ) {
            this.one = one;
            this.two = two;
        }

        public boolean evaluate(T thing) {
            return one.evaluate(thing)
            	   &amp;&amp; two.evaluate(thing);
        }
    }

    private static class OrFilter&lt;T&gt; extends AbstractFilter&lt;T&gt; {
        private final Filter&lt;? super T&gt; one;
        private final Filter&lt;? super T&gt; two;

        OrFilter(
        	Filter&lt;? super T&gt; one,
            Filter&lt;? super T&gt; two
        ) {
            this.one = one;
            this.two = two;
        }

        public boolean evaluate(T thing) {
            return one.evaluate(thing)
            	   || two.evaluate(thing);
        }
    }

    private static class FilteringIterator&lt;T&gt; implements Iterator &lt;T&gt; {
        private final Filter &lt;T&gt;     filter;
        private final Iterator &lt;T&gt;   base;
        private       T              next;

        FilteringIterator(
        	Filter&lt;T&gt; filter,
        	Iterator&lt;T&gt; base
        ){
            this.filter = filter;
            this.base = base;
            tryNext();
        }

        private void tryNext() {
            next = null;
            while (base.hasNext()) {
                final T item = base.next();
                if (item != null &amp;&amp; filter.evaluate(item)) {
                    next = item;
                    break;
                }
            }
        }

        public boolean hasNext() {
            return next != null;
        }

        public T next() {
            if (next == null) throw new NoSuchElementException();
            final T returnValue = next;
            tryNext();
            return returnValue;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }
}
</pre>
<p>Now that I have provided this pattern&#8217;s definition and implementation, I will proceed with a simple example of its use. This example will deal with the Java Reflection API. Imagine that you are trying to query all the methods in a class which names start with &#8220;eq&#8221;, &#8220;has&#8221;, &#8220;toS&#8221; and have the Object class as a parameter. Most of the times you will have multiple IFs checking the methods of your interest. What if I don&#8217;t want to do that and instead, I want to use the Filter design pattern. Well, in order to do that all you need to code are two basic filters: one for looking at the methods&#8217; names and the other one for looking at the methods&#8217; parameters types.</p>
<pre name="code" class="java">

    public static Filter &lt;Method&gt; containedParameters(final Class&lt;?&gt;... params){
        return new AbstractFilter &lt;Method&gt;(){
            public boolean evaluate(Method thing) {
                final List&lt;Class&lt;?&gt;&gt; s = Arrays.asList(
                	thing.getParameterTypes()
                );

                for(Class&lt;?&gt; each : params){
                    if(s.contains(each)){
                        return true;
                    }
                }
                return false;
            }
        };
    }

    public static Filter &lt;Method&gt; startedWith(final String... prefixes) {
        return new AbstractFilter &lt;Method&gt;(){
            public boolean evaluate(Method thing) {
                for(String prefix : prefixes) {
                    if(thing.getName().startsWith(prefix)){
                        return true;
                    }
                }
                return false;
            }
        };
    }
</pre>
<p>Simple, huh? totally!<br />
Well, what if you want to negate one of those filters? Well, this is even simpler to implement:</p>
<pre name="code" class="java">

    public static &lt;T&gt; Filter &lt;T&gt; not(final Filter &lt;T&gt; filter) {
        return new AbstractFilter &lt;T&gt;(){
            public boolean evaluate(T thing) {
                return !filter.evaluate(thing);
            }
        };
    }
</pre>
<p>And to finalize this post, here is how to put these filters to work:</p>
<pre name="code" class="java">

public class RunPattern {
    private RunPattern(){}
    public static void main(String... args) {
        // calling filters one after another
        for(Method each : containedParameters(Object.class)
        	.filter(startedWith(&quot;eq&quot;, &quot;has&quot;, &quot;toS&quot;)
        	.filter(Arrays.asList(Object.class.getDeclaredMethods())))){
           System.out.println(each.getName());
        }

        // or maybe you can start using and &amp; or operators
        final Filter &lt;Method&gt; m1 = containedParameters(Object.class)
        						   .and(startedWith(&quot;eq&quot;, &quot;has&quot;, &quot;toS&quot;));

        for(Method each : m1.filter(Arrays.asList(Object.class.getDeclaredMethods()))){
            System.out.println(each.getName());
        }

        // which method do you you prefer?
        // it will be up to you...

        // hmmm....what if?
        final Filter &lt;Method&gt; m2 = not(containedParameters(Object.class))
        						   .and(startedWith(&quot;eq&quot;, &quot;has&quot;, &quot;toS&quot;));
        for(Method each : m2.filter(Arrays.asList(Object.class.getDeclaredMethods()))){
            System.out.println(each.getName());
        }

    }
}
</pre>
<p>Hopefully you will find this newer version of this pattern useful. Ciao!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2008/10/more-on-filters-first-class-functions/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Class.cast(..) and Generics - a powerful combination</title>
		<link>http://www.gotobject.com/2008/07/class-cast-and-generics-a-powerful-combination/</link>
		<comments>http://www.gotobject.com/2008/07/class-cast-and-generics-a-powerful-combination/#comments</comments>
		<pubDate>Sat, 12 Jul 2008 04:50:42 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[random ideas]]></category>

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

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=22</guid>
		<description><![CDATA[As you know when it comes to casting a la Java 1.4 a developer will have to write, typically, something like this: 


Object a = &#34;iron man&#34;;
String  b = (String)a;

Well, there is nothing wrong with this code. However, it is not pretty :). With Java 5.0 the casting mechanism is more explicit and nicer. [...]]]></description>
			<content:encoded><![CDATA[<p>As you know when it comes to casting a la Java 1.4 a developer will have to write, typically, something like this: </p>
<pre name="code" class="java">

Object a = &quot;iron man&quot;;
String  b = (String)a;
</pre>
<p>Well, there is nothing wrong with this code. However, it is not pretty :). With Java 5.0 the casting mechanism is more explicit and nicer. The best thing of it is that it does not throw warnings, which it is a big deal <img src='http://www.gotobject.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre name="code" class="java">

Object a = &quot;iron man&quot;;
String  b = String.class.cast(a);
</pre>
<p>Not that bad, huh? Hmm, well&#8230;Okay, Okay, you got me. This still does not look that pretty and it is more verbose than the (Object)a style.  How can I make it prettier? the ans: Generics</p>
<pre name="code" class="java">

public static &lt;T, E extends T&gt; E cast(T me, Class&lt;? extends E&gt; to){
    return to.cast(me);
}
....
Object a = &quot;iron man&quot;;
String  b = cast(a, String.class); 
</pre>
<p>Believe it or not, I love this technique. It works like a charm with objects that are part of the same inheritance chain. I know this method requires more tweaking to make it suitable for handling the casting of collections. But hey! this is just a working idea!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2008/07/class-cast-and-generics-a-powerful-combination/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Building stories from every angle</title>
		<link>http://www.gotobject.com/2008/06/building-stories-from-every-angle/</link>
		<comments>http://www.gotobject.com/2008/06/building-stories-from-every-angle/#comments</comments>
		<pubDate>Sat, 07 Jun 2008 13:30:18 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[branding]]></category>

		<category><![CDATA[latest gadgets]]></category>

		<guid isPermaLink="false">http://www.gotobject.com/2008/06/building-stories-around-products/</guid>
		<description><![CDATA[Do you want to build a community around your products? If you do, there is a new site in town that allows you to do that. It is called ProductStory. ProductStory&#8217;s idea is very neat and simple. You just pick your favorite product and start your own story around it. You should try it. Especially [...]]]></description>
			<content:encoded><![CDATA[<p>Do you want to build a community around your products? If you do, there is a new site in town that allows you to do that. It is called <a href="http://www.productstory.net/" target="_blank">ProductStory</a>. ProductStory&#8217;s idea is very neat and simple. You just pick your favorite product and start your own story around it. You should try it. Especially now since the ProductStory&#8217;s team has finished implementing a cool <a href="http://blog.productstory.net/blogs/ps/" target="_blank">feature</a> that allow us to embed rotating-enabled products in our web sites. See it for yourself:</p>
<p style="text-align: center;"><object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="350" height="380" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="src" value="http://images.vergencemedia.net/rotation.swf?id=hasbro_bumblebee&amp;ac=PRODUCTSTORY" /><param name="wmode" value="transparent" /><embed type="application/x-shockwave-flash" width="350" height="380" src="http://images.vergencemedia.net/rotation.swf?id=hasbro_bumblebee&amp;ac=PRODUCTSTORY" wmode="transparent"></embed></object></p>
<p>What do you think? This is a cool idea huh? Let&#8217;s be part of this new movement and start building a community around our hottest new products.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2008/06/building-stories-from-every-angle/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Documenting Exceptions via Factory Methods</title>
		<link>http://www.gotobject.com/2008/05/documenting-exceptions-via-factory-methods/</link>
		<comments>http://www.gotobject.com/2008/05/documenting-exceptions-via-factory-methods/#comments</comments>
		<pubDate>Wed, 28 May 2008 04:53:05 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[programming]]></category>

		<category><![CDATA[random ideas]]></category>

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=17</guid>
		<description><![CDATA[Jesse described a technique for handling methods that always throws. This is a very interesting technique. Having written that, would it not be nice to encourage the use of this technique, in our Java coding conventions, as a way to document DRY exceptions? Honestly, I&#8217;d&#8217; think we should. It would prevent us from repeating the [...]]]></description>
			<content:encoded><![CDATA[<p>Jesse <a href="http://publicobject.com/2008/05/calling-method-that-always-throws.html">described</a> a technique for handling methods that always throws. This is a very interesting technique. Having written that, would it not be nice to encourage the use of this technique, in our Java coding conventions, as a way to document DRY exceptions? Honestly, I&#8217;d&#8217; think we should. It would prevent us from repeating the same description of our exceptions numerous times in our JavaDocs&#8230; Disclaimer: this is just a very simple example that tries to convey my point <img src='http://www.gotobject.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre name="code" class="java">

/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
  try {
     //.... some code goes here to
     //.... load a config file.
  } catch (RuntimeException re){
	throw unableToFindConfigFile(
           &quot;loadConfig():void&quot;,
           re
        );
  }
}

/**
 * @throws Violation
 *      due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append(&quot;Error when calling &quot;)
		.append(pointOfCall)
		.append(&quot;. Reason:&quot;)
		.append(cause);
	throw new Violation(msg.toString(), cause);
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void loadConfig() throws
Violation {
   try {
	//.... some code goes here to load
	//.... a config file.
    } catch (RuntimeException re){
	throw unableToFindConfigFile(
		&quot;loadConfig():void&quot;,
		re
	);
    }
}

/**
 * @throws Violation
 *   due to {@link #unableToFindConfigFile(String, Throwable)}
 */
public void refreshConfig() throws
Violation {
	loadConfig();
}

private static Violation unableToFindConfigFile(
	String pointOfCall,
	Throwable cause
) throws Violation
{
	final StringBuilder msg = new StringBuilder()
		.append(&quot;Error when calling &quot;)
		.append(pointOfCall)
		.append(&quot;. Reason:&quot;)
		.append(cause);
	throw new Violation(msg.toString(), cause);
}
</pre>
<p>Some of this approach&#8217;s benefits:</p>
<ol>
<li>No more boilerplate text when documenting exceptions.</li>
<li>The intent of the exception is clearly communicated via a factory method.</li>
<li>We are hiding the complexity of the exception&#8217;s declaration behind a consistent exterior.</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2008/05/documenting-exceptions-via-factory-methods/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Do you need to cache your objects?</title>
		<link>http://www.gotobject.com/2008/05/do-you-need-to-cache-your-objects/</link>
		<comments>http://www.gotobject.com/2008/05/do-you-need-to-cache-your-objects/#comments</comments>
		<pubDate>Wed, 14 May 2008 15:20:21 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[patterns]]></category>

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

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

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

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=16</guid>
		<description><![CDATA[I&#8217;ve found the Cache Management Pattern very useful in more than a couple of projects that needed a simple caching mechanism. Now that we have Generics at our disposal, I think this pattern deserves a tiny change. Something like a generic structure or code that we can follow or use every time we need to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve found the <a href="http://www.developer.com/java/other/article.php/630481">Cache Management Pattern</a> very useful in more than a couple of projects that needed a simple caching mechanism. Now that we have <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html">Generics</a> at our disposal, I think this pattern deserves a tiny change. Something like a generic structure or code that we can follow or use every time we need to cache specific objects.</p>
<p><strong><span style="font-size: medium;">The Structure</span></strong></p>
<pre name="code" class="java">

public interface ObjectCacheManager&lt;K, T&gt; {
    T fetch(K aKey);
}

public interface ObjectFactory&lt;K, T&gt; {
    T make(K aKey);
}

public interface Cache&lt;K, T&gt; {
    void add(T anEntry);
    T fetch(K aKey);
}
</pre>
<p><span style="font-size: medium;"><strong>An Example</strong></span></p>
<p>Note: this is just a toy example&#8230; you&#8217;ve been warned <img src='http://www.gotobject.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> Its purpose is to show you the dynamics of this pattern.</p>
<pre name="code" class="java">

public class FooCache implements Cache&lt;String, Foo&gt; {
    private final Map&lt;String, Foo&gt; cache;
    public FooCache(){
        cache = new ConcurrentHashMap&lt;String, Foo&gt;();
    }

    public void add(Foo entry) {
        final String key = entry.getName();
        if(cache.get(key) == null){
            cache.put(key, entry);
        }
    }

    public Foo fetch(String givenAKey) {
       return cache.get(givenAKey);
    }
}

public class FooFactory implements ObjectFactory&lt;String, Foo&gt; {
    public Foo make(String aKey) {
        return new Foo(aKey);
    }
}

public class FooCacheManager implements ObjectCacheManager&lt;String, Foo&gt; {
    private final ObjectFactory&lt;String, Foo&gt;    server;
    private final Cache&lt;String, Foo&gt;            cache;
    public FooCacheManager(){
        server  = new FooFactory();
        cache   = new FooCache();
    }

    public Foo fetch(String aKey) {
        Foo foo = cache.fetch(aKey);
        if(null == foo){
            foo = server.make(aKey);
            if(null != foo){
                cache.add(foo);
            }
        }
        return foo;
    }
}
</pre>
<p>Let&#8217;s get more specific with its use.. shall we?</p>
<pre name="code" class="java">

    @Test
    public void verifyFooCachingSystem(){
        final FooCacheManager manager = new FooCacheManager();
        final Foo a = manager.fetch(&quot;Superman&quot;);
        final Foo b = manager.fetch(&quot;Superman&quot;);
        Assert.assertEquals(a, b);
    }
</pre>
<p>And there you go&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2008/05/do-you-need-to-cache-your-objects/feed/</wfw:commentRss>
		</item>
		<item>
		<title>DRY benchmarking&#8230;.</title>
		<link>http://www.gotobject.com/2008/05/dry-benchmarking/</link>
		<comments>http://www.gotobject.com/2008/05/dry-benchmarking/#comments</comments>
		<pubDate>Tue, 13 May 2008 02:01:42 +0000</pubDate>
		<dc:creator>h.sanchez</dc:creator>
		
		<category><![CDATA[patterns]]></category>

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

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

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

		<guid isPermaLink="false">http://www.gotobject.com/?p=14</guid>
		<description><![CDATA[Every time we try to write a benchmark for particular functionality, we habitually specify a load (max iterations), write a for-loop, set timers before and after the loop, and call the method of interest inside this loop. This typically involves copying &#038; pasting from another benchmark and adapting the current benchmark to your needs. Why [...]]]></description>
			<content:encoded><![CDATA[<p>Every time we try to write a benchmark for particular functionality, we habitually specify a load (max iterations), write a for-loop, set timers before and after the loop, and call the method of interest inside this loop. This typically involves copying &#038; pasting from another benchmark and adapting the current benchmark to your needs. Why don&#8217;t we try, instead of copy &#038; paste, to define an idiom that we could reuse for writin benchmarks? Something like this</p>
<pre name="code" class="java">

public class Benchmark {
    private final int iters;
    public Benchmark(int iters){
        this.iters = iters;
    }

    public &lt;T&gt;long given(
    final Callable&lt;? extends T&gt; op
    ) throws Exception
    {
    	// warm things up
        for(int idx = 0; idx &lt; 10000; idx++){}

        long time = System.nanoTime();
        for(int idx = 0; idx &lt; iters; idx++){
            op.call();
        }
        time = System.nanoTime() - time;
        return TimeUnit.NANOSECONDS.toMillis(time);
    }
}
</pre>
<p>How can use this? This is simple&#8230;.</p>
<pre name="code" class="java">

    public static void main(
    String[] args
    ) throws Exception
    {
      System.out.println(new Benchmark(100000).given(
      	new Callable&lt;Void&gt;(){
            public Void call() throws Exception {
                System.out.println();
                return null;
            }
      }));
    }
</pre>
<p>Using this idiom will make the benchmarking of method calls easier&#8230;So please start using it <img src='http://www.gotobject.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.gotobject.com/2008/05/dry-benchmarking/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
