<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Object survivor space</title>
	<atom:link href="http://brixomatic.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://brixomatic.wordpress.com</link>
	<description>Random thoughts about Java programming</description>
	<lastBuildDate>Sat, 03 Sep 2011 10:07:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='brixomatic.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://0.gravatar.com/blavatar/a8e40cbbae94b8fce9e2c8510cc3afb5?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Object survivor space</title>
		<link>http://brixomatic.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://brixomatic.wordpress.com/osd.xml" title="Object survivor space" />
	<atom:link rel='hub' href='http://brixomatic.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Into the Void: Refining Java beans with rare weapons</title>
		<link>http://brixomatic.wordpress.com/2011/07/17/into-the-void-refining-java-beans-with-rare-weapons/</link>
		<comments>http://brixomatic.wordpress.com/2011/07/17/into-the-void-refining-java-beans-with-rare-weapons/#comments</comments>
		<pubDate>Sun, 17 Jul 2011 19:16:08 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[Reflection and Generics]]></category>
		<category><![CDATA[Coding-Style]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=241</guid>
		<description><![CDATA[Lately I&#8217;ve been experimenting with the Void class, because I asked myself what I could do with it that I haven&#8217;t yet thought about. I came across a use case that I&#8217;d like to share with you, because I think it is possible to beautify one&#8217;s code with it. In the process of slightly refactoring [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=241&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been experimenting with the Void class, because I asked myself what I could do with it that I haven&#8217;t yet thought about. I came across a use case that I&#8217;d like to share with you, because I think it is possible to beautify one&#8217;s code with it. In the process of slightly refactoring a Java bean in order to get a nicer, more refactoring-proof way of dealing with beans and reflection, I&#8217;m also using an inline-assignment in a way that you might already have come across, still I have hardly seen it anywhere in the wild, even though I find this particular use case for inline-assignments one of the best there is.<br />
<span id="more-241"></span></p>
<h2>Proxies love the Void.class</h2>
<p>You probably have asked yourself quite a long time: “What’s the class Void for?”, since you can’t create any object of it. You might be tempted to say that it’s just a placeholder to indicate that a generic method returns nothing, but it may serve you well beyond that, because these methods actually return something. As strange  as it sounds they return something that is meant to be nothing: null.<br />
In my previous blog “<a href="http://brixomatic.wordpress.com/2010/08/09/reflection-without-strings/">Reflection without Strings</a>” I have constructed a “MethodFinder” class that enables you to get method objects from any interface without referencing the methods by its name. So you’d have a refactoring-proof way to use reflection on interfaces. The trick was to create a dynamic proxy for the interface, which will remember the last method call that it got, call it and then ask it what it has remembered. You could then pass the method object on to any object that can deal with it.<br />
With some little syntax-trickery and a static import it was possible to get a nice and concise syntax that made it look like this:</p>
<pre class="brush: java;">
import static de.plush.brix.tools.reflection.MethodFinder.*;
//…
 final Method getter = method(call(IArticle.class).getPrice());
</pre>
<p>The method “call(IArticle.class)” will return a proxy implementing the “IArticle” interface, this is where you call “getPrice()” on. Now the MethodFinder class will remember (per thread), the method you have just called and return the default for the method’s return type, which is either null, 0, (byte)0, (short)0, 0, 0L, 0d or 0f. That useless result of the proxy call becomes the parameter of the “MethodFinder.method(Object)” method and the parameter solely exists to make the expression a one-liner.<br />
Mocking frameworks like Easymock work the same way. If you’re into unit tests, you might recognize this:</p>
<pre class="brush: java;">
final IArticle mock = EasyMock.createMock(IArticle.class);
EasyMock.expect(mock.getPrice()).andReturn(testPrice).anyTimes();
//…
EasyMock.replay(mock);
</pre>
<p>Now the problem is, that for calling a setter, which is a void method, you cannot use the return value as parameter for “MethodFinder.method(Object)”, because void methods don’t  return anything it won’t compile. So for void methods, the syntax looks like that:</p>
<pre class="brush: java;">
import static de.plush.brix.tools.reflection.MethodFinder.*;
//…
 call(IArticle.class).setPrice(null);
 final Method setter = method();
</pre>
<p>At this point you should consider biting the bullet and refactoring your IArticle interface as follows:</p>
<pre class="brush: java;">
public interface IArticle{
 Price getPrice();
 Void setPrice(final Price newPrice) ; //note the uppercase “V”
}
</pre>
<p>This will make a setter look like this:</p>
<pre class="brush: java;">
public class Article implements IArticle{
 //…
 public Void setPrice(final Price newPrice) {
  price = newPrice;
  return null; //works, as “null” has no type
 };
}
</pre>
<p>As a result your reflection code can now look like this:</p>
<pre class="brush: java;">
import static de.plush.brix.tools.reflection.MethodFinder.*;
//…
 final Method getter = method(call(IArticle.class).getPrice());
 final Method setter = method(call(IArticle.class).setPrice(null));
 final Binding&lt;IArticle,Price&gt; binding = new Binding&lt;IArticle,Price&gt;(getter, setter);
 binding.setModel(Article.none());
//..
</pre>
<p>The same happens with the EasyMock example:</p>
<pre class="brush: java;">
final IArticle mock = EasyMock.createMock(IArticle.class);
EasyMock.expect(mock.setPrice(testPrice)).andReturn(null).anyTimes();
//…
EasyMock.replay(mock);
</pre>
<p>This looks a lot slicker, doesn’t it? The “return null” in Article.class sucks however, but since we’d probably like some event handling anyway, we can beef it up too.  More on that follows.</p>
<h2>Inline assignments beautify your setters</h2>
<p>You have for sure seen something like this before, haven’t you?</p>
<pre class="brush: java;">
public class Article implements IArticle{
 //…
 public Void setPrice(final Price newPrice) {
  final Price oldPrice = price;
  price = newPrice;
  firePropertyChange(“price“, oldPrice, newPrice);
  return null;
 };
}
</pre>
<p>This method stinks in many ways: The property key is referenced by a String, we have a temporary variable for the old price and just because of our neat “Void” type, we have a “return null” here. Don’t worry; Salvation is near. Let’s tackle one problem after the other.<br />
First we kill the temporary variable with a simple inline-assignment, which is discouraged by some style guides and is hardly used elsewhere than in loops to read streams, but it serves very well in this case:</p>
<pre class="brush: java;">
public class Article implements IArticle{
 //…
 public Void setPrice(final Price newPrice) {
  firePropertyChange(“price“, price, (price = newPrice));
  return null;
 };
}
</pre>
<p>To understand how this works is to understand how parameters are evaluated, which is from left to right:  To call firePropertyChanged, the runtime must first push all 3 parameters on the Stack in order of appearance, which is the String “price”, the value of the price itself and finally the value of the bracketed statement. Now the statement in brackets not only results in the new price, it also assigns the new price to the price field.<br />
Getting rid of the ugly “return null”, is as easy as it can get: Just change the “firePropertyChange” method to return the “Void” type instead of the “void” primitive and you can write it like that:</p>
<pre class="brush: java;">
public class Article implements IArticle{
 //…
 public Void setPrice(final Price newPrice) {
  return firePropertyChange(“price“, price, (price = newPrice));
 };
}
</pre>
<p>Its seems a little bit awkward to return anything after firing a property change, but I can live with it, can you?<br />
The last thing that looks so incoherent is that even though we’ve now managed to access the method without referencing it by its name, we identify the property by the name. And there’s really no way around throwing a string around, when you need to stay compatible with the existing property change mechanism of the java beans framework, which you should. But then again we can get the string automagically by assuming the convention “setX”, “addX” and “removeX” for modifier methods. We just ask the stack trace which method we’re in and analyse the string and I’m using a little utility for that to not repeat myself. Alas, working with the stack trace is a bit of a mess, because call depths matter and these may change when refactoring, but that’s where testing getters and setters with unit tests pays off.<br />
I like to have some sweet little methods in a utility class to get me the current property name:</p>
<pre class="brush: java;">
public static String propertyName(){
 final StackTraceElement x = Thread.currentThread().getStackTrace()[2];
 return extractPropertyName(x.getMethodName());
}
public static String propertyName(Method method){
 return extractPropertyName(method.getName());
}
private static String extractPropertyName(String methodName){
 final String[] prefixes={&quot;get&quot;,&quot;set&quot;,&quot;add&quot;,&quot;remove&quot;};
 for (final String prefix : prefixes){
  if (methodName.startsWith(prefix)
   &amp;&amp; methodName.length() &gt; prefix.length()){
   return Character.toLowerCase(methodName.charAt(prefix.length()))
   + methodName.substring(prefix.length()+1);
  }
 }
 throw new IllegalStateException(methodName
 +&quot; is not a property get, set, add or remove method&quot;);
}
</pre>
<p>With this method in place and a static import to get it, my business object now looks as follows:</p>
<pre class="brush: java;">
public class Article implements IArticle{
 //…
 public Price getPrice(){
  return price;
 }
 public Void setPrice(final Price newPrice) {
  return firePropertyChange(propertyName(), price, (price = newPrice));
 };
}
</pre>
<p>Et Voilà! Here is your business object with property change support, Void return type and no need to keep any property name strings in sync, in other words “fully refactoring-proof”. Thanks to the “strange” Void class and a little utility, property change support looks pretty much like straightforward Java code without magic constants:</p>
<pre class="brush: java;">
 String priceProperty = propertyName(method(call(IArticle.class).setPrice(null)));
 article.addPropertyChangeListener(priceProperty, updatePriceView);
</pre>
<p>So what is the take-home message of this blog? The Void.class is a quite useful replacement for the void primitive. Inline-assignments may seem like a black sheep in the Java language and are prone to be misread, in non-complex situations like these, they beautify the code considerably.<br />
Mind you the Java bean was just an example to demonstrate possible uses of these rare tools &#8211; in the real world a setter that returns the old value is usually more beneficial.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a>, <a href='http://brixomatic.wordpress.com/category/reflection-and-generics/'>Reflection and Generics</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/coding-style/'>Coding-Style</a>, <a href='http://brixomatic.wordpress.com/tag/refactoring/'>Refactoring</a>, <a href='http://brixomatic.wordpress.com/tag/reflection/'>Reflection</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/241/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/241/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/241/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/241/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/241/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/241/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/241/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/241/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=241&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2011/07/17/into-the-void-refining-java-beans-with-rare-weapons/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Java actor framework &#8220;Kilim&#8221;: A solution without a problem?</title>
		<link>http://brixomatic.wordpress.com/2010/11/26/java-actor-framework-kilim-a-solution-without-a-problem/</link>
		<comments>http://brixomatic.wordpress.com/2010/11/26/java-actor-framework-kilim-a-solution-without-a-problem/#comments</comments>
		<pubDate>Fri, 26 Nov 2010 19:08:02 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[Threading and Concurrency]]></category>
		<category><![CDATA[Actors]]></category>
		<category><![CDATA[BlockingQueue]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Producer/Consumer]]></category>
		<category><![CDATA[Threading]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=201</guid>
		<description><![CDATA[Some time ago I read a posting from a workmate, that was linking to an IBM developerworks article about the actor-framework “Kilim” and he seemed to be quite fond of it. Since I know this guy’s a very skilled technician and since actors are one of the bigger hypes in software technology nowadays, with languages [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=201&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
Some time ago I read a posting from a workmate, that was linking to an <a href="http://www.ibm.com/developerworks/java/library/j-javadev2-7.html">IBM developerworks article</a> about the actor-framework “Kilim” and he seemed to be quite fond of it. Since I know this guy’s a very skilled technician and since actors are one of the bigger hypes in software technology nowadays, with languages like Scala openly supporting that concurrency model, and since the IBM developerworks articles are usually quite good, I instantly dived into it, only to be left perplexed.<span id="more-201"></span><br />
<br />
Let me start with some of the commonly repeated claims regarding actors, which in this particular article reads like this:</p>
<blockquote><p>The actor model is a different way of modeling concurrent processes. Rather than threads interacting via shared memory with locks, the actor model leverages &#8220;actors&#8221; that pass asynchronous messages using mailboxes. A mailbox, in this case, is just like one in real life — messages can be stored and retrieved for processing by other actors. Rather than sharing variables in memory, the mailbox effectively separates distinct processes from each other.</p></blockquote>
<p>First I notice something fundamentally wrong here: Actors do interact via shared memory. It’s the mailbox, which is both shared with the outside world and synchronized. Well, to be fair a mailbox does not need to be synchronized, it may well be implemented using a <a href="http://www.cs.rochester.edu/u/michael/PODC96.html">lock free algorithm</a>. If you look at <a href="https://github.com/kilim/kilim/blob/master/src/kilim/Mailbox.java">Kilim’s implementation</a>, however, you will find a lot of synchronization over a shared array there.<br />
<br />
And there was another thing that bugged me:
</p>
<blockquote><p>There are no locks and synchronized blocks in the actor model, so the issues that arise from them — like deadlocks and the nefarious lost-update problem — aren&#8217;t a problem.</p></blockquote>
<p>As a user of actors I don’t need the synchronized keyword, true, and in fact you don’t find any synchronization in the user code. But seriously: Do we need a framework for that?</p>
<h2>Translating the example to plain Java SE</h2>
<p>What else is an actor like a (lightweight) thread and what else is a mailbox than a thread safe container? Let me translate the example code from the article to use only classes from the Java Standard Edition.<br />
The &#8220;calculation type message&#8221; (I&#8217;ll try to use the same terms as in the article) is exactly the same as the original:</p>
<pre class="brush: java;">
public class Calculation{
 private BigDecimal dividend;

 private BigDecimal divisor;

 private BigDecimal answer;

 public Calculation(BigDecimal dividend,BigDecimal divisor){
  this.dividend=dividend;
  this.divisor=divisor;
 }

 public BigDecimal getDividend(){
  return dividend;
 }

 public BigDecimal getDivisor(){
  return divisor;
 }

 public void setAnswer(BigDecimal ans){
  this.answer=ans;
 }

 public BigDecimal getAnswer(){
  return answer;
 }

 public String printAnswer(){
  return &quot;The answer of &quot; + dividend + &quot; divided by &quot; + divisor + &quot; is &quot; + answer;
 }
}
</pre>
<p>The DeferredDivision class, which is our first actor, looks almost the same as in the article. Instead of a mailbox class it uses a blocking queue, it implements Runnable, instead of extending the framework class &#8220;Task&#8221; and it handles InterruptedExceptions:</p>
<pre class="brush: java;">
public class DeferredDivision implements Runnable{

 private BlockingQueue&lt;Calculation&gt; mailbox;

 public DeferredDivision(BlockingQueue&lt;Calculation&gt; mailbox){
  this.mailbox=mailbox;
 }

 @Override
 public void run(){
  try{
   Random numberGenerator=new Random(new Date().getTime());
   MathContext context=new MathContext(8);
   while(true){
    System.out.println(&quot;I need to know the answer of something&quot;);
    mailbox.offer(
     new Calculation(new BigDecimal(numberGenerator.nextDouble(),context),
      new BigDecimal(numberGenerator.nextDouble(),context)));
    Thread.sleep(1000);
    Calculation answer=mailbox.poll(); // no block
    if(answer != null &amp;&amp; answer.getAnswer() != null){
     System.out.println(&quot;Answer is: &quot; + answer.printAnswer());
    }
   }
  }catch(InterruptedException e){
   e.printStackTrace();
  }
 }
}
</pre>
<p>The Calculator class, which is the second actor, is not very different either. The modifications to the original code are exactly the same as in the DeferredDivision:</p>
<pre class="brush: java;">
public class Calculator implements Runnable{

 private BlockingQueue&lt;Calculation&gt; mailbox;

 public Calculator(BlockingQueue&lt;Calculation&gt; mailbox){
  this.mailbox=mailbox;
 }

 @Override
 public void run(){
  try{
   while(true){
    Calculation calc=mailbox.take(); // blocks
    if(calc.getAnswer() == null){
     calc.setAnswer(
      calc.getDividend().divide(calc.getDivisor(),8,RoundingMode.HALF_UP));
     System.out.println(&quot;Calculator determined answer&quot;);
     mailbox.offer(calc); // no block
    }
    Thread.sleep(1000);
   }
  }catch(InterruptedException e){
   e.printStackTrace();
  }
 }
}
</pre>
<p>We don’t need the Ant script for Kilim’s Weaver here, because we don’t need to weave anything. So we don&#8217;t need to understand and maintain any XML definition either, which is great. Instead we can continue with the runner, which looks as simple as the original from the article, but I can give it an own maximum amount of messages. I chose 300, the same value that is hard coded in the Kilim framework:</p>
<pre class="brush: java;">
public class CalculationCooperation{
 public static void main(String[] args){
  BlockingQueue&lt;Calculation&gt; sharedMailbox
   =new ArrayBlockingQueue&lt;Calculation&gt;(300);

  Runnable deferred=new DeferredDivision(sharedMailbox);
  Runnable calculator=new Calculator(sharedMailbox);

  new Thread(deferred).start();
  new Thread(calculator).start();
 }
}
</pre>
<p>Voila! This code does not only look very similar to the original, it also acts very similar. There are just two differences:  It doesn’t use lightweight threads and there’s a difference in the way it fails. It fails? Wait! I was told that&#8230;
</p>
<h2>When an example backfires on a bold claim</h2>
<blockquote><p>There are no locks and synchronized blocks in the actor model, so the issues that arise from them — like deadlocks and the nefarious lost-update problem — aren&#8217;t a problem.</p></blockquote>
<p>The funny thing is: That particular article itself is probably the best proof that it&#8217;s wrong. The code that the author presents is free of deadlocks, sure, but ironically it contains a huge lost-update problem, as does my no-framework translation.</p>
<p>The mailbox from the original will silently reject new messages  (returning “false”), when it is full, while the BlockingQueue in my version will throw an IllegalStateException in the same situation. So this is the first obvious flaw in the code from the article and its translation. If the mailbox is full, we have a problem: We lose updates or we crash. Since I am a great fan of “fail fast” programming, I’d prefer the exception, because it enables me to quickly analyze what went wrong and take countermeasures, I don’t simply lose something without notice. Fortunately the fix for both of these problems is easy: Use a blocking “put” that waits for space in the mailbox.</p>
<p>There is a second bug, which is not that obvious. It&#8217;s also shared by the original code and the translation. Just follow the program: The DeferredDivision posts a Calculation, waits a second and takes a calculation from the mailbox. If the calculation has been solved it prints the result, else it just starts over. It reads good, it looks good and it&#8217;s wrong. Imagine this situation:<br />
The DeferredDivision posts a Calculation, but before the calculator can take it from the mailbox (because it&#8217;s still busy), the DeferredDivision wakes up again, takes the unsolved calculation from the mailbox, and omits it. Now the calculator wakes up, can’t find that calculation and blocks until the DeferredDivision posts another. As a result the calculation has been lost.<br />
Fortunately the second problems can also be fixed: One could use a blocking “get”, so the program doesn’t progress until there is a result in the mailbox/queue. Or one could repost the unsolved calculation and progress. Still the second solution may re-evoke the first problem: If you use a putnb (non blocking) with Kilim you could lose the new and reposted calculations as soon as the mailbox is filled (so you’d need to evaluate the return param of the putnb call) or with my alternative implementation a non blocking put (=offer) would throw an IllegalStatetException that indicates the queue is full. So you’d better use a blocking &#8220;put&#8221; here aswell. As a result the worst case scenario would be a constantly filled queue, and threads waiting to do something. Which is annoying but normal under heavy load.
</p>
<p>
So what is the take-home-message of this blog? Without the need for any actor abstraction framework I have recreated this example with nearly the same code. And, as I’ve shown, the actor model has not saved the author of  the article from introducing a lost-update problem on two occasions in just about 20 lines of code. In fact it is equally easy to create the spaghetti eating philosopher’s problem with actors (the forks being messages in the shared mailboxes). So does that actor framework really make our life simpler as programmers?<br />
And what’s left besides lightweight threads? What’s it really worth having lightweight threads anyway, facing multicore chips like AMD’s and Intel’s current consumer line or even SUN/Oracle’s Ultrasparc T2 chips, that eat entire thread pools for breakfast? Could it even hurt performance based on the fact that these CPU base their internal scheduling partly on the information that threads are independent instruction streams?<br />
To be honest, I am not convinced this framework solves me any problem, I’m terribly sorry. Or is it just that I&#8217;m missing something important here?</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a>, <a href='http://brixomatic.wordpress.com/category/threading-and-concurrency/'>Threading and Concurrency</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/actors/'>Actors</a>, <a href='http://brixomatic.wordpress.com/tag/blockingqueue/'>BlockingQueue</a>, <a href='http://brixomatic.wordpress.com/tag/concurrency/'>Concurrency</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a>, <a href='http://brixomatic.wordpress.com/tag/performance/'>Performance</a>, <a href='http://brixomatic.wordpress.com/tag/producerconsumer/'>Producer/Consumer</a>, <a href='http://brixomatic.wordpress.com/tag/threading/'>Threading</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/201/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=201&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/11/26/java-actor-framework-kilim-a-solution-without-a-problem/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Paint faster!</title>
		<link>http://brixomatic.wordpress.com/2010/08/29/paint_faster/</link>
		<comments>http://brixomatic.wordpress.com/2010/08/29/paint_faster/#comments</comments>
		<pubDate>Sun, 29 Aug 2010 16:43:49 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[Swing]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Oddities]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=182</guid>
		<description><![CDATA[It&#8217;s been a while since I came across this stuff and I already wrote about it on a company blog in the German language, but I thought this could be interesting enough for more people out there, so I&#8217;m sitting here translating what I wrote almost 2 years ago, keen on validating it with today&#8217;s [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=182&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
It&#8217;s been a while since I came across this stuff and I already wrote about it on a company blog in the German language, but I thought this could be interesting enough for more people out there, so I&#8217;m sitting here translating what I wrote almost 2 years ago, keen on validating it with today&#8217;s Java Runtime. So what&#8217;s this fuzz about? Simply put: I noticed that you might have wasted a lot of time in swing, if you relied on the Graphics-object you get passed by Swing and the difference was dramatic!<br />
<span id="more-182"></span>
</p>
<p>
It all started when I got a pixel-exact specification on how to draw some round borders, which I  implemented and one of the next reports that we got said that our application&#8217;s resizing/repainting behavior showed undesirable lags. As I recently made a lot of changes in the way the look and feel paints the borders, I instantly felt guilty of it and luckily the report was also assigned to me, so I took my profiler to identify the slowest methods. The repainting of the borders took in fact most of the time when you resized the window, if not the most. It turned out that the borders were still painting fast enough. But I produced this little micro benchmark in my eager attempt to optimize that part of the code in order to see if a bit less load would make a difference (I suspected it could be flooding the EDT with lots of short repaints enough to cause that effect, so I thought reducing the time could change something – unfortunately it didn&#8217;t). And I got pretty surprised!
</p>
<p>
Here&#8217;s a little demo:</p>
<pre class="brush: java;">
public class DrawingPixels extends JPanel {

  private int index = 0;
  private List&lt;Color&gt; colors;
  private long totalTimes;
  private long measures;

  public DrawingPixels() {
    final Dimension dim = new Dimension( 800, 800 );
    setMinimumSize( dim );
    setPreferredSize( dim );
    setMaximumSize( dim );
    setSize( dim );
    final Timer timer = new Timer();
    timer.scheduleAtFixedRate( new TimerTask() {
      @Override
      public void run() {
        repaint();
      }
    }, 1000, 1000 );

    colors = new ArrayList();
    for ( int t = 0; t &lt; 256; t += 8 ) {
      colors.add( new Color( t, t, t ) );
    }
    for ( int t = 254; t &gt; 0; t -= 8 ) {
      colors.add( new Color( t, t, t ) );
    }
  }

  @Override
  protected void paintComponent( final Graphics g ) {
    super.paintComponent( g );
    index = ( index + 1 ) % colors.size();
    System.out.println( index );
    final Color color = colors.get( index );
    final long start = System.currentTimeMillis();
    paintStuff( g, color );
    final long end = System.currentTimeMillis();
    final long elapsed = end - start;
    totalTimes += elapsed;
    ++measures;
    g.setColor( Color.WHITE );
    g.drawString(
      String.valueOf( totalTimes / measures ), 100, 100 );
  }

  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      public void run() {
        final JFrame f = new JFrame();
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        f.setContentPane( new DrawingPixels() );
        f.pack();
        f.setVisible( true );
      }
    } );
  }

  private void paintStuff( final Graphics g, final Color color ) {
    g.setColor( color );
    for ( int y = 0; y &lt; getHeight(); ++y ) {
      for ( int x = 0; x &lt; getWidth(); ++x ) {
        g.drawLine( x, y, x, y );
      }
    }
  }
}
</pre>
<p>You don&#8217;t have to understand and read most of the code. The important part is the last method &#8220;paintStuff&#8221; which does the drawing. It fills this 800&#215;800 pixel panel one pixel at a time. My development-machine back then took a whopping 2300 milliseconds to do that, which was quite frankly insane.
</p>
<p>
The next try got me a quite interesting result:</p>
<pre class="brush: java;">
  private void paintStuff( final Graphics g, final Color color ) {
    final BufferedImage image =
      new BufferedImage( getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB );
    final Graphics imageGfx = image.getGraphics();
    imageGfx.setColor( color );
    for ( int y = 0; y &lt; getHeight(); ++y ) {
      for ( int x = 0; x &lt; getWidth(); ++x ) {
        imageGfx.drawLine( x,y,x,y);
      }
    }
    g.drawImage( image, 0, 0, this );
  }
</pre>
<p>This code just needed 590 ms, so painting into a buffered image and painting the buffered image onto the panel was faster than painting directly onto the panel and that took me by complete surprise!
</p>
<p>
Since a BufferedImage allows for setting the RGB-values of a pixel directly, I also tried that aswell and see if that would improve things:</p>
<pre class="brush: java;">
  private void paintStuff( final Graphics g, final Color color ) {
    final BufferedImage image =
      new BufferedImage( getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB );
    final Graphics imageGfx = image.getGraphics();
    for ( int y = 0; y &lt; getHeight(); ++y ) {
      for ( int x = 0; x &lt; getWidth(); ++x ) {
        image.setRGB( x, y, color.getRGB() );
      }
    }
    g.drawImage( image, 0, 0, this );
  }
</pre>
<p>This version did it in just 96 miliseconds – quite an improvement to the 2500 milliseconds the first version needed!
</p>
<h2>Improvements with JRE 1.6</h2>
<p></p>
<p>
Now I&#8217;m sitting at home at a machine which is not exactly as fast as my development machine these days, but this test is not so much about raw CPU-Power, is more about the graphics subsystems sending data and commands to the graphics adapter, so it is rather testing how well Swing implements its drawing-machanisms. Back then, when I timed it, we were running Java 1.5 and now I am repeating this test with version 1.6.0_18 of SUNs Java virtual machine.<br />
These are the results:
</p>
<p>
<div id="attachment_192" class="wp-caption alignnone" style="width: 547px"><a href="http://brixomatic.files.wordpress.com/2010/09/paint_faster_chart.png"><img src="http://brixomatic.files.wordpress.com/2010/09/paint_faster_chart.png?w=537&#038;h=329" title="paint_faster_chart" width="537" height="329" class="size-full wp-image-192" /></a><p class="wp-caption-text">Things got considerably faster with the 1.6 runtimes. The results finally look sane.</p></div><br />
The runtime of the first test has improved from 2500 ms to 315 ms. The second test improved from 590 ms to 350 ms. The last test turned out to be equally fast: 97 ms. <br />
The results I got from 1.6 virtual machine finally make sense:<br />
Painting onto the screen with a line-drawing method that can do all the alpha-blending and transformation stuff the Graphics object provides is faster than doing the same thing on a buffered image fist. And just setting some RGB-Values on an image and painting that is faster, because it&#8217;s omitting all the fancy stuff – it just sets some values and tells the graphics adapter to display them.<br />
Well, and one last thing: If anyone thinks that filling a canvas one pixel at a time is a stupid idea: He is right, because g.fillrect(0,0,getWidth(),getHeight()); does it in 2ms, which is well below the 10 ms tolerance of System.currentTimeMillis(), so hardly measurable. I&#8217;ll just feel I need to leave that figure here for the &#8220;Swing is slow&#8221;-zealots, before they start rambling about some hundreds of milliseconds for filling a screen – you can fill a screen faster than you&#8217;ll ever need it that is for sure, but the bottom line is:<br />
With Java 6 Sun have really improved the graphics subsystem for the most common case, where you just override the paintComponent-method and paint your stuff directly. And the good thing is: you don&#8217;t need to change code, recompile and redeploy, it just comes for free.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/swing/'>Swing</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a>, <a href='http://brixomatic.wordpress.com/tag/oddities/'>Oddities</a>, <a href='http://brixomatic.wordpress.com/tag/performance/'>Performance</a>, <a href='http://brixomatic.wordpress.com/tag/swing/'>Swing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/182/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/182/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/182/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=182&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/08/29/paint_faster/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>

		<media:content url="http://brixomatic.files.wordpress.com/2010/09/paint_faster_chart.png" medium="image">
			<media:title type="html">paint_faster_chart</media:title>
		</media:content>
	</item>
		<item>
		<title>Reflection without Strings</title>
		<link>http://brixomatic.wordpress.com/2010/08/09/reflection-without-strings/</link>
		<comments>http://brixomatic.wordpress.com/2010/08/09/reflection-without-strings/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 18:08:36 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[Reflection and Generics]]></category>
		<category><![CDATA[API-Design]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Reflection]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=148</guid>
		<description><![CDATA[Sometimes reflection is very handy, but using reflection often involves referencing methods by Strings, which can get you into major trouble when you are refactoring your code. If a method belongs to an interface though, there is salvation. But let me first tell you how it started and what I did about it. The framework [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=148&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Sometimes reflection is very handy, but using reflection often involves referencing methods by Strings, which can get you into major trouble when you are refactoring your code. If a method belongs to an interface though, there is salvation. But let me first tell you how it started and what I did about it.<span id="more-148"></span></p>
<p>
The framework we are using in my current Project uses a UI abstraction layer, made of so-called “adapters&#8221;, which represent a GUI-toolkit independent representation of UI widgets to be used in the controllers. In the simplest case these adapters are just bound to a model and fire PropertyChangeEvents, which are handled by a GUI toolkit dependent adapter that translates these events to method calls on the UI-widget. So what this framework does is to separate the GUI toolkit from the controller side and it does that really well.<br />
For the rest of this blog, I will stay on the controller side, where we find the GUI toolkit independent adapters. Now to bind an adapter to a model one possible technique is to give it a so-called ValueProvider, which has a simple interface (there are no generics yet):</p>
<p><pre class="brush: java;">
public interface IValueProvider{
 Object getValue();
 void setValue(Object o);
}
</pre>
<p>
These value providers sometimes hold some conversion logic or lazy initializations on write access, which is just what happened in my case. In my controller I had 11 of these value providers and 9 of them were similar, except the called another method in the business object:</p>
<p><pre class="brush: java;">
IValueProvider newFooValueProvider(){
  return new IValueProvider(){
    public Object getValue(){
     return convertToUi(getOptions().getFoo());
    }
    public void setValue(final Object value){
      ensureOptionsInitialized();
      getOptions().setFoo(convertToModel(value));
    }
  };
}
IValueProvider newBarValueProvider(){
  return new IValueProvider(){
    public Object getValue(){
     return convertToUi(getOptions().getBar());
    }
    public void setValue(final Object value){
      ensureOptionsInitialized();
      getOptions().setBar(convertToModel(value));
    }
  };
}
//…seven more like these …
</pre>
<p>
Pretty repetitive and screaming to be refactored, you’d think. I first thought of using an abstract ValueProvider class, but that meant I still needed a new class per attribute, which still cluttered my code. This is one of these moments where you probably wished you had closures to avoid the clutter. Without closures I decided to use the next best thing: Reflection. </p>
<h2>An intermediate solution</h2>
<p>
Reflection is a mighty tool in cases like this: I could just create a ValueProvider that takes a proper getter and setter method and let it invoke those after doing the standard stuff. This is almost as easy said than done:</p>
<p><pre class="brush: java;">
private IValueProvider newValueProvider(final Method getter, final Method setter){
  return new IValueProvider(){
    public Object getValue(){
     try{
       return convertToUi(getter.invoke(getOptions()));
     }catch ( IllegalAccessException e){
       ExceptionHelper.toRuntimeException(e);
     }catch( InvocationTargetException){
       ExceptionHelper.toRuntimeException(e);
     }
    }
    public void setValue(final Object value){
      try{
        ensureOptionsInitialized();
        setter.invoke(getOptions(),convertToModel(value));
     }catch ( IllegalAccessException e){
       ExceptionHelper.toRuntimeException(e);
     }catch( InvocationTargetException){
       ExceptionHelper.toRuntimeException(e);
     }
    }
  };
}
//…
</pre>
<p>Now I had nine methods which looked like:</p>
<pre class="brush: java;">
IValueProvider newFooValueProvider(){
  Method getter = ReflectionHelper.getMethod(IOptions.class,“getFoo&quot;);
  Method setter = ReflectionHelper.getMethod(IOptions.class, “setFoo&quot;, Integer.class);
  return newValueProvider(getter,setter);
}
IValueProvider newBarValueProvider(){
  Method getter = ReflectionHelper.getMethod(IOptions.class,“getBar&quot;);
  Method setter = ReflectionHelper.getMethod(IOptions.class, “setBar&quot;, Integer.class);
  return newValueProvider(getter,setter);
}
//…seven more like these…
</pre>
<p>
This looks pretty slick, don’t you think so? The best thing is: it saved me 33 lines of cluttered code. Only thing is: it has a smell, because it references methods by strings and when you rename or move a method your compiler won’t tell you a thing if you mess it up. Your unit tests may uncover your mistake, but then again: It could be so much easier. How nice would it be, if you had fist class methods, so you could write something like: <code>Method&nbsp;getter&nbsp;=&nbsp;#IOptions.getFoo();</code> to get a reference on the Method object?</p>
<h2>Dynamic proxies make your day</h2>
<p>A co-worker asked me if there was a way to reference a method without using strings, to make it refactoring-proof. And I told him that I didn’t know how and that this problem has bugged ever since, but as I spoke it out, I happened to have one of the brighter moments in my life, because: As far as interfaces are concerned, this is actually quite easy and the solution was always right in front of me: Dynamic proxies. I love them, for real. The Proxy class probably belongs to the 5 most underrated additions to the Java runtime ever. Application servers make extensive use of dynamic proxies to wrap aspects like thread pooling, remoting, load balancing, transaction logic and similar stuff around beans and services and there are of course some tiny handy tools which use them, some of you might use a particular one on a regular basis, like me: EasyMock.<br />
As it turned out the API of the tool I am about to develop in this blog shared some characteristics with EasyMock in the end.</p>
<p>
Let’s start with the simple idea and refine the API step by step. </p>
<div id="attachment_147" class="wp-caption alignnone" style="width: 488px"><a href="http://brixomatic.files.wordpress.com/2010/08/methodfinder.png"><img src="http://brixomatic.files.wordpress.com/2010/08/methodfinder.png?w=478&#038;h=299" alt="Class diagram: a dynamic proxy that can implement any interface that uses an InvocationHandler which stores the last method call on the proxy." title="MethodFinder" width="478" height="299" class="size-full wp-image-147" /></a><p class="wp-caption-text">The basic idea: The tool creates a dynamic proxy that can implement any interface. Its InvocationHandler hands over the last method that was called on the proxy.</p></div>
<p>
I first started with a class of stateful objects that provide a proxy and a simple getter to provide the user access to the called method:</p>
<p><pre class="brush: java;">
class MethodFinder {
  private Method method;
  public &lt;T&gt; call(final Class&lt;? extends T&gt; clazz){
    return (T) Proxy.newProxyInstance(
     getClassLoader(),
     getInterfaces(clazz),
     new InvocationHandler(){
      public Object invoke(final Object proxy, final Method method,
          final Object[] args) throws Throwable{
        this.method = method;
        return null;
      }
    });
  }

  private static Class&lt;?&gt;[] getInterfaces( final Class&lt;?&gt; clazz ) {
    final List&lt;Class&lt;?&gt;&gt; interfaces
     = new ArrayList&lt;Class&lt;?&gt;&gt;( Arrays.asList( clazz.getInterfaces() ) );
    if ( clazz.isInterface() ) {
      interfaces.add( clazz );
    }
    return interfaces.toArray( new Class&lt;?&gt;[interfaces.size()] );
  }
  public Method method(){return method;}
}
</pre>
<p>
This was the basic draft and it was flawed: It would throw NullPointerExceptions with primitive return types and using it looked like this:</p>
<pre class="brush: java;">
  final MethodFinder mf = new MethodFinder();
  mf.call(IOptions.class).getFoo();
  final Method getter = mf.method();
</pre>
<p>
I liked to get rid of the new-operator. To achieve that I would need to use a static method and a static field. That would get me into new trouble: Multithreaded access. I don’t want to see unpredictable results because one thread might overwrite another one’s current method reference. Luckily I can have an own variable per thread by using a ThreadLocal object, so we can avoid this conflict easily. This way I could also move the proxy’s invocation handler to a constant field and avoid unnecessary object creation. Here’s a second take on the tool:</p>
<p><pre class="brush: java;">
public class MethodFinder {

  private static final InvocationHandler HANDLER = new InvocationHandler() {
    public Object invoke( final Object proxy, final Method method,
      final Object[] args ) throws Throwable {
      tlMeth.set( method );
      return null;
    }
  };

  private static final ThreadLocal&lt;Method&gt; tlMeth = new ThreadLocal&lt;Method&gt;();

  public static &lt;T&gt; T call( final Class&lt;? extends T&gt; clazz ) {
    return (T) Proxy.newProxyInstance(
      getClassLoader(),
      getInterfaces( clazz ),
      HANDLER );
  }

  private static Class&lt;?&gt;[] getInterfaces( final Class&lt;?&gt; clazz ) {
    final List&lt;Class&lt;?&gt;&gt; interfaces
    = new ArrayList&lt;Class&lt;?&gt;&gt;( Arrays.asList( clazz.getInterfaces() ) );
    if ( clazz.isInterface() ) {
      interfaces.add( clazz );
    }
    return interfaces.toArray( new Class&lt;?&gt;[interfaces.size()] );
  }

  public static Method method() {
    try {
      return tlMeth.get();
    } finally {
      tlMeth.remove();
    }
  }

  private static ClassLoader getClassLoader() {
    ClassLoader cl = Thread.currentThread().getContextClassLoader(); //primary
    return cl != null ? cl : MethodFinder.class.getClassLoader(); // fallback
  }
}
</pre>
<p>
With this modification, using this tool looks a little bit better:</p>
<pre class="brush: java;">
  MethodFinder.call(IOptions.class).getFoo();
  final Method getter = MethodFinder.method();
</pre>
<p>
There is still room for improvement. By introducing a new method, I can nest those proxy-calls that call methods, which have a return value. This is the idea expressed in Java code:</p>
<pre class="brush: java;">
  public static Method method() {
    return method(null);
  }

  public static Method method(Object doesntMatter) {
    try {
      return tlMeth.get();
    } finally {
      tlMeth.remove();
    }
  }
</pre>
</p>
<p>So we can now use this shortcut for non-void-methods:</p>
<pre class="brush: java;">
  final Method getter = MethodFinder.method(MethodFinder.call(IOptions.class).getFoo());
</pre>
<p>
I’d like to add static imports at this point. That makes it look a lot better. Likewise I’d like to notice that for void-methods we cannot use the nested method, but use the two-liner we have used before. Here’s how it looks:</p>
<pre class="brush: java;">
  import static de.plush.brix.tools.reflection.MethodFinder.*;
  //…
  final Method getter = method(call(IOptions.class).getFoo());
  call(IOptions.class).setFoo(null);
  final Method setter = method();
</pre>
<p>
As you can see this is pretty much like configuring expectations with EasyMock. The only thing that keeps us from using this tool in production is that it can’t handle primitive return types yet, but that is easily fixed. Here’s the final result:</p>
<pre class="brush: java;">
import static java.lang.Boolean.FALSE;
import java.lang.reflect.*;
import java.util.*;

public class MethodFinder {

  private static final InvocationHandler HANDLER = new InvocationHandler() {
    public Object invoke( final Object proxy, final Method method,
        final Object[] args ) throws Throwable {
      tlMeth.set( method );
      final Class&lt;?&gt; returnType = method.getReturnType();
      if ( Boolean.TYPE.equals( returnType ) ) {
        return FALSE;
      } else if ( Byte.TYPE.equals( returnType ) ) {
        return (byte) 0;
      } else if ( Short.TYPE.equals( returnType  ) ) {
        return (short) 0;
      } else if ( Integer.TYPE.equals( returnType ) ) {
        return 0;
      } else if ( Long.TYPE.equals( returnType ) ) {
        return 0L;
      } else if ( Float.TYPE.equals( returnType ) ) {
        return 0f;
      } else if ( Double.TYPE.equals( returnType ) ) {
        return 0d;
      }
      return null;
    }
  };

  private final static ThreadLocal&lt;Method&gt; tlMeth = new ThreadLocal&lt;Method&gt;();

  public static &lt;T&gt; T call( final Class&lt;? extends T&gt; clazz ) {
    return (T) Proxy.newProxyInstance(
      getClassLoader(),
      getInterfaces( clazz ),
      HANDLER );
  }

  private static Class&lt;?&gt;[] getInterfaces( final Class&lt;?&gt; clazz ) {
    final List&lt;Class&lt;?&gt;&gt; interfaces
    = new ArrayList&lt;Class&lt;?&gt;&gt;( Arrays.asList( clazz.getInterfaces() ) );
    if ( clazz.isInterface() ) {
      interfaces.add( clazz );
    }
    return interfaces.toArray( new Class&lt;?&gt;[interfaces.size()] );
  }

  public static Method method(){
    return method(null);
  }

  public static Method method(final Object doesntMatter){
    try{
      return tlMeth.get();
    }finally{
      tlMeth.remove();
    }
  }

  private static ClassLoader getClassLoader() {
    ClassLoader cl = Thread.currentThread().getContextClassLoader(); //primary
    return cl != null ? cl : MethodFinder.class.getClassLoader(); // fallback
  }
}
</pre>
<p>Now here it is: A surprisingly small and simple tool which can ease your pain with refactoring code that relies on reflection.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a>, <a href='http://brixomatic.wordpress.com/category/reflection-and-generics/'>Reflection and Generics</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/api-design/'>API-Design</a>, <a href='http://brixomatic.wordpress.com/tag/refactoring/'>Refactoring</a>, <a href='http://brixomatic.wordpress.com/tag/reflection/'>Reflection</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/148/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/148/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/148/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=148&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/08/09/reflection-without-strings/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>

		<media:content url="http://brixomatic.files.wordpress.com/2010/08/methodfinder.png" medium="image">
			<media:title type="html">MethodFinder</media:title>
		</media:content>
	</item>
		<item>
		<title>Hack of the day: Unchecking checked exceptions.</title>
		<link>http://brixomatic.wordpress.com/2010/04/29/hack-of-the-day-unchecking-checked-exceptions/</link>
		<comments>http://brixomatic.wordpress.com/2010/04/29/hack-of-the-day-unchecking-checked-exceptions/#comments</comments>
		<pubDate>Thu, 29 Apr 2010 19:57:54 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[Reflection and Generics]]></category>
		<category><![CDATA[Exceptionhandling]]></category>
		<category><![CDATA[Generics]]></category>
		<category><![CDATA[Hacks]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Oddities]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=121</guid>
		<description><![CDATA[In my last blog I announced to write something about some nice reflection magic, but it turned out that I got a little short on time, so that blog isn’t ready yet. But to keep you entertained I’d like to write something about a little hack I’ve found and instead of Reflection magic, you can [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=121&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
In my last blog I announced to write something about some nice reflection magic, but it turned out that I got a little short on time, so that blog isn’t ready yet. But to keep you entertained I’d like to write something about a little hack I’ve found and instead of Reflection magic, you can read about some wild Generics magic. Not bad either, isn’t it? This hack is also really helpful!<span id="more-121"></span><br />
To surprise you, let me just start with the code and have you try it yourself.
</p>
<p><pre class="brush: java;">
public class Unchecked {

 public static void rethrow( final Throwable checkedException ) {
  Unchecked.&lt;RuntimeException&gt;thrownInsteadOf( checkedException );
 }

 @SuppressWarnings(&quot;unchecked&quot;)
 private static &lt;T extends Throwable&gt; void thrownInsteadOf(Throwable t) throws T {
  throw (T) t;
 }

 public static void main( final String[] args ) {
  // throw new IOException(); // we don’t want to declare this exception
  Unchecked.rethrow( new IOException() );
 }
}
</pre>
</p>
<p>
In case you haven’t tried this: what this code does is stripping the “checked” attribute from the checked IOException! So with this little generic magic, you may now throw any checked exception without having to catch or declare it, as you can see in the main method. </p>
<h2>Why does it work?</h2>
<p></p>
<p>
At first sight, this looks like an ugly hack which won’t be available in future Java versions, but will it? I dare to say there is little danger. To understand why I think so, let me get into more depth.<br />
</p>
<blockquote><p>JLS 14.18 The throw Statement<br />
A throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V&#8217; of class NullPointerException is created and thrown instead of null. The throw statement then completes abruptly, the reason being a throw with value V&#8217;.</p></blockquote>
<p>
What the Java Language Specification tells us in this paragraph is that the cast should be executed before the throws is executed, and in fact it is! Here is the proof:
</p>
<p><pre class="brush: java; first-line: 8;">
 private static &lt;T extends Throwable&gt; void thrownInsteadOf(Throwable t) throws T {
  throw (RuntimeException) t;
 }
</pre>
</p>
<p>
When we execute our class with this changed method we get a ClassCastException. Wait: if a cast is executed before throwing the exception, how can the hack work then? I cannot cast this IOException to RuntimeException! To explain this, let’s dive into Type-Erasure. Type erasure happens when generic methods are compiled. The generic type information is erased according to the given type bounds. Applied to our hack, the rules for type erasure would make the compiler create this method signature:
</p>
<p><pre class="brush: java; first-line: 8;">
 private static void thrownInsteadOf(Throwable t) throws Throwable {
  throw (Throwable) t;
 }
</pre>
</p>
<p>
As we can see the cast is unnecessary and can be eliminated by the compiler. Let’s test if it really is: I will change the generic method to just return the exception and have the caller throw it instead and see what happens.
</p>
<p><pre class="brush: java; first-line: 3;">
 public static void rethrow( final Throwable checkedException ) {
  throw Unchecked.&lt;RuntimeException&gt;thrownInsteadOf( checkedException );
 }

 @SuppressWarnings(&quot;unchecked&quot;)
 private static &lt;T extends Throwable&gt; T thrownInsteadOf(Throwable t) {
  return (T) t;
 }
</pre>
<p>
When I execute my hack with these changes, this is what I get:</p>
<pre class="brush: java;">
Exception in thread &quot;main&quot; java.lang.ClassCastException:
java.io.IOException cannot be cast to java.lang.RuntimeException
	at de.plush.brix.exeptions.Unchecked.rethrow(Unchecked.java:4)
</pre>
</p>
<p>
Interesting, isn’t it? I’ve got a ClassCastException, but not where one would expect it to be. This is the proof, that the cast in the “thrownInsteadOf”-method got eliminated. It is the caller who does the cast and from what we’ve seen from the type erasure, placing the cast there is the only correct way to do it. If we think about it for a while: how else would it be possible to keep the method generic? For private methods the compiler could create synthetic methods for every generic type it is called with, but for the sake of simplicity, behavioural consistency and memory consumption, this should be avoided. For public methods it would be impossible anyway. The compiler’s behaviour is sane. Since the caller does the cast it is not executed, because the Java runtime must abort abuptly and pass the exception up the call graph until it is caught or terminates the thread. So by specification the outer cast must never be executed, no matter how bonkers it is. Which means the Java runtime&#8217;s behaviour is also sane and the compiler knows what it&#8217;s doing.
</p>
<h2>Revisiting type erasure for throws clauses:</h2>
<p></p>
<p>
Type erasure and throws clauses are a strange couple, no really! In order to understand how the hack works I had to shed a little light on how those two work together. To analyze this, let’s start with the signature of our generic method:
</p>
<p><pre class="brush: java; first-line: 7;">
 @SuppressWarnings(&quot;unchecked&quot;)
 private static &lt;T extends Throwable&gt; void thrownInsteadOf(Throwable t) throws T {
  throw (T) t;
 }
</pre>
</p>
<p>
If I used this method like this:</p>
<pre class="brush: java; first-line: 4;">
 Unchecked.thrownInsteadOf(new IOException());
</pre>
<p>
The compiler would infer the type signature and ask me to catch or declare the Exception. However, if I used the method like this:</p>
<pre class="brush: java; first-line: 4;">
 Unchecked.thrownInsteadOf(new RuntimeException());
</pre>
<p>Then the type interference would see it is a RuntimeException and not ask me to do any exception handling. Now here’s the surprising bit: As I stated above, type erasure would translate this method to this:<br />
 </p>
<pre class="brush: java; first-line: 8;">
 private static void thrownInsteadOf(Throwable t) throws Throwable {
  throw t;
 }
</pre>
</p>
<p>
You see: This method, at runtime, would always throw checked exceptions, but the compiler would always have to force me to handle exceptions, wouldn’t it? Funny thing is: The compiler cannot, because that would break the semantics for RuntimeExceptions. This may seem inconsistent, but it is legal because of what is the really weird part: While in the Java language the unchecked RuntimeException is a subtype of the checked Exception, the Java runtime environment itself knows no such thing as a checked exception. This is why the above method will work at runtime, after type erasure has made it throw a “checked” exception type.<br />
Sun could have avoided this by making the checked Exception a subtype of the unchecked RuntimeException, but they haven’t. God knows why. But this is why we got that sweet loophole.
</p>
<p>
Bottom line is: If I’m not heavily mistaken this is no “hack”, but perfectly legal loophole which is not likely to change in the future. This is a good thing for all those among us who are really annoyed by handling all those checked exceptions, but please don’t overuse it: Checked exceptions are really not that bad, if they are used with care.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/reflection-and-generics/'>Reflection and Generics</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/exceptionhandling/'>Exceptionhandling</a>, <a href='http://brixomatic.wordpress.com/tag/generics/'>Generics</a>, <a href='http://brixomatic.wordpress.com/tag/hacks/'>Hacks</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a>, <a href='http://brixomatic.wordpress.com/tag/oddities/'>Oddities</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/121/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/121/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/121/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=121&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/04/29/hack-of-the-day-unchecking-checked-exceptions/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Don&#8217;t handle just another state if you can query, please!</title>
		<link>http://brixomatic.wordpress.com/2010/04/14/dont-handle-just-another-state-if-you-can-query-please/</link>
		<comments>http://brixomatic.wordpress.com/2010/04/14/dont-handle-just-another-state-if-you-can-query-please/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 21:31:19 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Coding-Style]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=107</guid>
		<description><![CDATA[How often do you find yourself having trouble to understand a big chunk of code? At the moment I&#8217;m pretty busy with refactoring just another controller. Even though the number of WTF/min from my office is quite large at the moment, I&#8217;m not angry with the fellows who wrote it. The code was made under [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=107&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
How often do you find yourself having trouble to understand a big chunk of code? At the moment I&#8217;m pretty busy with refactoring just another controller. Even though the number of WTF/min from my office is quite large at the moment, I&#8217;m not angry with the fellows who wrote it. The code was made under time pressure and as far as I&#8217;m informed, people were under constant threat to be criticized for introducing a bug by changing working code for no apparent reason. Unfortunately refactoring and code cleanups are sometimes hard to sell as “apparent reason”, especially to non-technical staff. As a result code quality starts to decay, changes take longer than necessary and refactoring gets harder every day. I&#8217;m placing my bet on my “new kid on the block” credits to go for the risk of breaking code at the moment. So what&#8217;s making my life hard at the moment? State! <span id="more-107"></span>To make the code easier to understand and enhance I&#8217;m working hard to eliminate any unnecessary state, because state is what makes it hard to follow a program flow. When writing code you should avoid unnecessary state it in the first place, you&#8217;ll make your life easier, trust me!<br />
Let me show you what I mean:
</p>
<p><pre class="brush: java;">
public class Foo{

 private String from;
 private String to;
 private Date when;
 private boolean valid;

 void setFrom(String x){
  if(x == null || x.isEmpty()){
   from=&quot;&quot;;
   valid=false;
  }else{
   from=x;
   valid=true;
  }
 }

 void setTo(String x){
  if(x == null || x.isEmpty() || x.equals(from)){
   to=&quot;&quot;;
   valid=false;
  }else{
   to=x;
  }
 }

 void setDate(Date x){
  if(x.after(new Date())){
   when=null;
   valid=false;
  }else{
   when=x;
   setFrom(from);
   setTo(to);
  }
 }

 boolean isValid(){
  return valid;
 }
}
</pre>
<p>The original code included some UI-widgets, asynchronous web service calls, more sophisticated validation, but it roughly boils down to something like the code you can see above. This example is fairly small, but he ugliest part of it is the “valid” state, which gets updated on any change.<br />
Code like this is harder to follow than necessary, because you have to track the state-change, especially if you try to change the code. Now just compare that to this code:
</p>
<p><pre class="brush: java;">
public class Foo{

 private String from;
 private String to;
 private Date when;

 void setFrom(String x){
  if(x == null || x.isEmpty()){
   from=&quot;&quot;;
  }else{
   from=x;
  }
 }

 void setTo(String x){
  if(x == null || x.isEmpty() || x.equals(from)){
   to=&quot;&quot;;
  }else{
   to=x;
  }
 }

 void setDate(Date x){
  if(x.after(new Date())){
   when=null;
  }else{
   when=x;
  }
 }

 boolean isValid(){
  return !from.isEmpty() &amp;&amp; !to.isEmpty()
    &amp;&amp; when != null &amp;&amp; !when.after(new Date());
 }
}
</pre>
<p>Just by removing the extra “valid” state and replacing it with a query method, the code got dramatically more readable and it was even possible to remove some ugly code in the “setDate” method, which existed solely to manage that field correctly, plus it is absolutely obvious when this object&#8217;s state is considered valid and when it&#8217;s not.<br />
This simple example shows a basic rule: Each modified field in your class represents state and each state which can be substituted by a query is usually unnecessary and should be avoided, unless it causes an unbearable performance-penalty.
</p>
<p>
Update:<br />
I just found another example, which has nothing to do with queries, but in general it&#8217;s the same problem with unnecessary state:
</p>
<p><pre class="brush: java;">
class Bar{
 private List&lt;Object&gt; items = new ArrayList&lt;Object&gt;();
 private boolean save;

 public void reset(){
  items.clear();
  save = true;
 }

 public void buzz(int x){
  for(int t = 0; t&lt;x; ++t){
   items.add(SomeFactory.create(x,t));
  }
  if(save){
   save();
  }
 }

 public void bell(int x){
  save = false;
  buzz(x);
  save = true;
  for(int t = 0; t&lt;x; ++t){
   items.add(SomeOtherFactory.create(x,t));
  }
  save();
 }

 private void save(){
  for(Object item : items){
   SomeService.save(item);
  }
 }
}
</pre>
</p>
<p>
Believe it or not, but I just had to work on code structured exactly like that, only it had 3 times as many public methods like that. I can hardly express how much I hate it! First it is easy to get wrong, because the callee always has to reset(); before using any of the public method. Second, this class has way too much state and is hard to follow. Third: I didn&#8217;t mention that this is a shared class in a multithreaded context. The callee must make sure no two calls use the object at the same time. Please, please with sugar topping, please: Beware of writing code like that! In this case pass the list as a parameters, make the boolean field a parameter and replace it with a meaningful enum. If you want to keep the public API clean, introduce new public methods without these parameters. And what you&#8217;ll get is this:
</p>
<p><pre class="brush: java;">
class Bar{
 private enum Save{REQUESTED, SKIPPED}

 public void buzz(int x){
  buzz(x, new List(), Save.REQUESTED);
 }

 public void bell(int x){
  bell(x, new List());
 }

 private void buzz(int x, List items, Save save){
  for(int t = 0; t&lt;x; ++t){
   items.add(SomeFactory.create(x,t));
  }
  if(save == REQUESTED){
   save(items);
  }
 }

 private void bell(int x, List items){
  buzz(x, items, Save.SKIPPED);
  for(int t = 0; t&lt;x; ++t){
   items.add(SomeOtherFactory.create(x,t));
  }
  save(items);
 }

 private void save(List&lt;Object&gt; items){
  for(Object item : items){
   SomeService.save(item);
  }
 }
}
</pre>
</p>
<p>
This may be more code, but it is easier to refactor, the public API is hard to use in a wrong way (and has less methods by the way), the code is easy to follow because you don&#8217;t have to keep global variables in mind and any object of this class is safe to share.<br />
Let me repeat the mantra once again: Avoid unnecessary state if you can.
</p>
<p>
Just to keep you interested in case this blog might have been too trivial in your opinion: My next Blog will contain some cool reflection magic.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/uncategorized/'>Uncategorized</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/coding-style/'>Coding-Style</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/107/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/107/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/107/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=107&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/04/14/dont-handle-just-another-state-if-you-can-query-please/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Minimizing ripple effects</title>
		<link>http://brixomatic.wordpress.com/2010/04/06/minimizing-ripple-effects/</link>
		<comments>http://brixomatic.wordpress.com/2010/04/06/minimizing-ripple-effects/#comments</comments>
		<pubDate>Mon, 05 Apr 2010 23:56:09 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[API-Design]]></category>
		<category><![CDATA[Coding-Style]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=87</guid>
		<description><![CDATA[In the good old times when racing was dangerous and sex was safe and real programmers coded machine language we were used to use jumps and branches to addresses or labels if you had more than just a ML-monitor. BASIC just took this paradigm to a higher language level and the art of programming involved [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=87&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
In the good old times when racing was dangerous and sex was safe and real programmers coded machine language we were used to use jumps and branches to addresses or labels if you had more than just a ML-monitor. BASIC just took this paradigm to a higher language level and the art of programming involved tracing all the jumps and conditions at the same time until Edsger Dijkstra spoiled it all &#8211; and rightly so! There are better ways to waste your testosterone and show you&#8217;re a real man than working successfully with untraceable spaghetti-code no one else understands – including yourself some months later. Sadly you can still create a tangled mess if you&#8217;re programming in Java and other OOP languages alike. Often you find yourself in a situation where you have to change something which would break a lot of code, because that small change you need to make ripples through several classes. The higher the fan-in-complexity of your code is, the worse it gets. This is why some code analysis tools punish a high fan-in-complexity, which may be misleading if you take the DRY-principle seriously.  Especially if you work on frameworks you need to take countermeasures to avoid ripple-effects so you can continue to develop your framework while it&#8217;s being used. Let me introduce you to a coding style that helps to reduce ripple effects.
</p>
<p><span id="more-87"></span></p>
<h2>Not exposing inner state</h2>
<p>
How often do you see code like this?</p>
<pre class="brush: java;">
class Foo{
 private final List&lt;Data&gt; list = new ArrayList&lt;Data&gt;();
 public List&lt;Data&gt; getData(){
  return list;
 }
}
</pre>
</p>
<p>
This code is simple and looks good, but even if it looks completely harmless &#8211; it isn&#8217;t! The first thing I notice is that this class exposes inner state, it exposes its list, which is stateful. Any class could get the list and modify it, potentially breaking your class. Your class can, in no way, control its inner state. Which also means that you cannot get a class like this thread safe. You cannot work on this list safely from within the class. Modifying the list from inside your class will potentially break every class that uses it. Even switching to another List-implementation can ruin the performance of any algorithm that works on this list. And what happens if you decide to use a set instead? Every class that expected a list would need to adapt! As a user of this class you would need to copy the result of the list to your favourite data-structure to be safe. </p>
<pre class="brush: java;">
class Bar{
 private final Foo foo = new Foo();
 public void doSomething(){
    //might break foo:
    foo.getData().add(new Data()); 

    //runtime is sensitive to changes in the list type:
    final Iterator&lt;Data&gt; itr = foo.getData().iterator();
    while(itr.hasNext()){
     final Data data = itr.next();
     if(condition(data)){
      itr.remove();
     }
    }

    //what foo returns might not be what you like
    final Set&lt;Data&gt; set = new TreeSet&lt;Data&gt;(foo.getData());
  }
}
</pre>
</p>
<p>
Now let&#8217;s imagine you had to change Foo from using lists to using sets:</p>
<pre class="brush: java;">
class Foo{
 private final Set&lt;Data&gt; set = new HashSet&lt;Data&gt;();
 public List&lt;Data&gt; getData(){ //legacy API
  return new ArrayList&lt;Data&gt;(set);
 }
}
</pre>
</p>
<p>
Wait&#8230; this one will break every class which relies on the fact that the getter always returns the same list instead of a copy! So you need to do this:</p>
<pre class="brush: java;">
class Foo{
 private final List&lt;Data&gt; list = new ArrayList&lt;Data&gt;();
 public List&lt;Data&gt; getData(){
  return list;
 }
 private void doSomeWork(){
  final Set&lt;Data&gt; set = new HashSet&lt;Data&gt;(list);
  //work with data
  list.clear();
  list.addAll(set);
 }
}
</pre>
</p>
<p>
You can see the ugly creeping into the source code, can&#8217;t you? No matter what you&#8217;re trying to achieve, problems are all over you. You can&#8217;t change the return type of the method without hassles, you can&#8217;t even change the inner workings of your class without running into problems. Imagine a full blown, complex application code with thousands lines of code all built on classes like this and now watch your Eclipse workspace. Do you see something familiar? I&#8217;m sure! And I guess that would be a safe bet, because I see this happening everywhere. Can a programming style suck more than that? Why is it, that even experienced programmers keep on using this kind of style, even though they must feel the pain every time they need to change their code? I guess this pattern is used a lot because beans are used a lot, because it is quickly written without a lot of boilerplate code and because it&#8217;s just like a bad habit. The worst thing is: I can&#8217;t deny that I frequently fall into the same pit over and over again. I&#8217;m trying to improve though, as the solution is astonishingly simple.<br />
Let&#8217;s get rid of the problems by simply moving the responsibility for copying the list from outside of the class to the inside, pepper it with generics and serve it:</p>
<pre class="brush: java;">
class Foo{
 private final List&lt;Data&gt; list = new ArrayList&lt;Data&gt;();
  public &lt;T extends Collection&lt;? super Data&gt;&gt; T dataTo(final T target){
   for(final Data data : list){
    target.add(data);
   }
   return target;
 }
}
</pre>
</p>
<p>
Any user is now free to chose the type he likes, he can control which collection instances share the data and which don&#8217;t and the user-side code doesn&#8217;t look too bad either:</p>
<pre class="brush: java;">
class Bar{
 private  Foo foo = new Foo();
 public void doSomething(){
    final Set&lt;Data&gt; set = foo.dataTo(new TreeSet&lt;Data&gt;());
    //...
  }
}
</pre>
</p>
<p>
The class Foo can be thread-safe and changing the collection implementation in Foo won&#8217;t affect the performance of any class that obtained data from it, it will not break the build of dependent classes and you don&#8217;t need ugly workarounds inside of Foo to honor a legacy API: you could even make Foo use a HashMap internally and all you needed was to change the method to copy the HashMap&#8217;s values instead. And if you need to share state with Foo, you can still use listeners, at the expense of some annoying boilerplate code though.<br />
But wait! Doesn&#8217;t „copy on get“ mean you waste performance? Sure. But how often does performance matter and how often do ripple effects matter? If you measure a real performance problem somewhere, you can still tune this particular class, use a caching proxy or build a workaround. It&#8217;s better to have a small amount workarounds to fix performance problems than to have hundreds of them to cope with structural problems.
</p>
<h2>Hiding Structure</h2>
<p>
This is very similar to the stuff above, but rather concentrating on the data structure. Let&#8217;s take a look at some piece of code you might see once in a while, after we have learned something from the stuff above:</p>
<pre class="brush: java;">
class Foo{
 public void doSomething(final Fizz fizz){
    final Iterable&lt;Data&gt; datas
     = fizz.getBar().getBuzz().dataTo(new ArrayList&lt;Data&gt;());
    for(final Data data : datas){
     if(attrib.equals(data))){
      //...
     }
    }
  }
}
</pre>
</p>
<p>
The problem is almost the same as with the list-example. As you can easily see, Foo depends on three other classes: Fizz, Bar and Buzz. As soon as any of these classes needs a change in its API, for example if Bar needs a list of Buzz, the class Foo is subject to a change. This means Foo is a target of ripple effects. To avoid that, the Law of Demeter should always be in the back of your mind. The Law Of Demeter roughly says that an object should only talk to its closest friends, which are own fields, own parameters and objects it created on its own. It&#8217;s a rule, which is sometimes hard to follow and you shouldn&#8217;t waste your time hacking up your code like mad just to follow it perfectly. It&#8217;s enough to follow its intent: keep dependency-chains very short!<br />
The example above would violate the Law Of Demeter, because Foo talks to Bar, even though it has to ask Fizz for it. It would be better if Foo only talked to Fizz and let Fizz handle it&#8217;s business with Bar and Buzz.<br />
As a result the code could look like this:</p>
<pre class="brush: java;">
class Foo{
  public void doSomething(final Fizz fizz){
    final Iterable&lt;Data&gt; datas= fizz.dataTo(new ArrayList&lt;Data&gt;());
    for(final Data data : datas){
     if(attrib.equals(data))){
      //...
     }
    }
  }
}
</pre>
</p>
<p>
Alas, the example above means that Fizz would have to delegate the call to Bar and Bar would have to delegate the call to Buzz which obviously creates a lot of boilerplate code. If you like to avoid some of that it may be a good idea to  just eliminate some of the dependency but not everything of it. But it may be worth it. Since Foo will have no business with any of the intermediate objects any more, we&#8217;re rid of some of the ripple effects with this kind of style. <br />
Unfortunately, Foo still has to iterate over a copy of Fizz&#8217; data, which means that this approach will fail if the Data objects are stored in a structure that is not easy to iterate, say, because it&#8217;s so huge that it won&#8217;t fit into memory. Therefore it might be a good idea to just pass the algorithm and let the data owner do the iteration. We wouldn&#8217;t need to copy anything either, which is good for the application&#8217;s performance and memory consumption. This is how it works:</p>
<pre class="brush: java;">
interface Function&lt;R,A&gt;{
  R execute(A param);
}

class Foo{
  public void doSomething(final Fizz fizz){
    final Function&lt;Void, Data&gt; something = new Function&lt;Void, Data&gt;(){
      public Void execute(final Data candidate){
        if(attrib.equals(data){
         //...
        }
        return null;
      }
    };
    fizz.forEachDataDo(something);
  }
}
</pre>
</p>
<p>
Alas, this solution requires a new Interface which means even more code and the creation of a class that implements the interface is rather cumbersome and hard to read.
</p>
<h2>Enter Closures</h2>
<p>
With Java 7 Sun promised to bring Closures to the Java language. Closures, or Lambda Expressions, will in most situations save you from writing just another interface. Following <a href="//mail.openjdk.java.net/pipermail/lambda-dev/2010-January/000349.html">the recent Java Closure proposal</a> by Alex Buckley the code above would look as follows:</p>
<pre class="brush: java;">
class Foo{
  public void doSomething(final Fizz fizz){
    final #void(Data) something = #(Data data){
     if(attrib.equals(data){
      //...
     }
   };
   fizz.forEachDataDo(something);
  }
}
</pre>
</p>
<p>
Or shorter:</p>
<pre class="brush: java;">
class Foo{
  public void doSomething(final Fizz fizz){
   fizz.forEachDataDo(#(Data data){
    if(attrib.equals(data){
     //...
    }
   });
  }
}
</pre>
</p>
<p>
The code with closures is almost as short as the naïve original but it has none of it&#8217;s shortcomings, apart from the delegation. So there we are stuck between a rock and a hard place: you can clearly see that this code doesn&#8217;t look quite as readable and requires more boilerplate than the first, naïve example, but it decouples way better which will pay off when you have to apply changes later. Since we don&#8217;t have closures yet, thus with the interface still necessary for this coding style, it is especially hard to break the habit of writing it the way you always do. You should consider it though.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/api-design/'>API-Design</a>, <a href='http://brixomatic.wordpress.com/tag/coding-style/'>Coding-Style</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/87/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/87/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/87/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=87&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/04/06/minimizing-ripple-effects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Using annotations for validation</title>
		<link>http://brixomatic.wordpress.com/2010/03/20/using-annotations-for-validation/</link>
		<comments>http://brixomatic.wordpress.com/2010/03/20/using-annotations-for-validation/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 21:06:05 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[Fluent interfaces]]></category>
		<category><![CDATA[Annotations]]></category>
		<category><![CDATA[API-Design]]></category>
		<category><![CDATA[Coding-Style]]></category>
		<category><![CDATA[Fluent]]></category>
		<category><![CDATA[Immutability]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Reflection]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=62</guid>
		<description><![CDATA[There is one common case I often come across and that&#8217;s validation of parameters. There are different situations in which you like to validate parameters, the most common case is validation of method parameters, usually performed with guard-clauses and assertions. This is not what I&#8217;d like to write about in this blog. I may come [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=62&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
There is one common case I often come across and that&#8217;s validation of parameters. There are different situations in which you like to validate parameters, the most common case is validation of method parameters, usually performed with guard-clauses and assertions. This is not what I&#8217;d like to write about in this blog. I may come across this later. This time it&#8217;s all about annotation driven validation on fields.<span id="more-62"></span><br />
In my last blog I&#8217;ve written on how to deal with long constructors, which are common if you fancy immutable objects. I&#8217;ve proposed a builder-pattern to create a fluent API for object initialization, which gives you the ability to check all fields upon construction. Let me just repeat the source code to get you up to date:
</p>
<p><pre class="brush: java;">
@Immutable
public final class Address{

 private final String street;
 private final String zipcode;
 private final String town;
 private final String country;

 private Address(final AddressBuilder b){
  street=b.street;
  zipcode=b.zipcode;
  town=b.town;
  country=b.country;
 }

 public String getStreet(){
  return street;
 }
 //..

 public static AddressBuilder build(){
  return new AddressBuilder();
 }
 //..

 public static class AddressBuilder{
  private final SingleThreadBarrier barrier
   = new SingleThreadBarrier(getClass());
  private String street;
  private String zipcode
  //..
  public AddressBuilder withStreet(final String street){
   barrier.pass();
   this.street=street;
   return this;
  }

  //..

  public Address noNullPropertyAllowed(){
   barrier.pass();
   if(Arrays.asList(street, zipcode, town, country).contains(null)){
     throw new NullPointerException();
   }
   return new Address(this);
  }

 }
}
</pre>
</p>
<p>
Now, the last method was pretty interesting. I wrote a very short method to keep the example small, alas that method won&#8217;t deliver a rather useless error message. If you really want to make things more concise in terms of debugging, the naive approach could look a little something like this:
</p>
<p><pre class="brush: java;">
  public Address noNullPropertyAllowed(){
   barrier.pass();
   if(street==null){throw new IllegalArgumentException(“street is null“);}
   if(zipcode==null){throw new IllegalArgumentException(“zipcode is null“);}
   if(town==null){throw new IllegalArgumentException(“town is null“);}
   if(country==null){throw new IllegalArgumentException(“ country is null“);}
   return new Address(this);
  }
</pre>
</p>
<p>
This code is repetitive and as soon as the validation involves more than just a little check like this, it will become the coleslaw-and-beer equivalent for method bodies: it expands and expands and expands and at some point you will wish your co-workers away, so nobody will notice when you release the stink. Time to build a better tool to do the job, really! Why not chose annotations?</p>
<h2>A basic annotation based validation mechanism</h2>
<p></p>
<p>
Update (March 24, 2010): After reading a <a href="http://java.dzone.com/articles/bean-validation-and-jsr-303"> blog about the JSR 303 for bean validation</a>, I&#8217;m pretty amazed that my idea was not that dumb at all. I do like the idea of binding the validator to its annotation woth a @Constraint-annotation and I initially thought of something similar. There was just one sole reason why I didn&#8217;t do it: I had no idea how to retrofit any of the the NotNull annotations around. But I&#8217;m thinking about changing my code accordingly and just have a special Mapping for @NotNull.
</p>
<p>
Lets start with defining an interface for checking an object&#8217;s field against an annotation:
</p>
<p><pre class="brush: java;">
interface AnnotationCheck&lt;A extends Annotation&gt; {
 void check(final Object o,final Field field,final A annotationType)
           throws IllegalAccessException;
}
</pre>
</p>
<p>
And implement that for the NotNull annotation:
</p>
<p><pre class="brush: java;">
class NotNullCheck implements AnnotationCheck&lt;NotNull&gt; {
 @Override
 public void check(Object o,Field field,NotNull annotationType)
                   throws IllegalAccessException {
  if ( field.get( o ) == null ) {
   throw new IllegalArgumentException(
   &quot;Field &quot;+o.getClass().getName()+'#'+field.getName()+&quot; must not be null&quot;);
  }
 }
}
</pre>
</p>
<p>
To have something a little more sophisticated, let&#8217;s create a Range annotation to check numbers:
</p>
<p><pre class="brush: java;">
@Target(ElementType.FIELD)
@Retention(RUNTIME)
public @interface Range {
 double from()  default Double.NEGATIVE_INFINITY ;
 double to()  default Double.POSITIVE_INFINITY;
}
</pre>
</p>
<p>
Here&#8217;s a simple check against a number range. Note that this won&#8217;t work perfectly with BigDecimals and doesn&#8217;t care for Double.NaN, but let&#8217;s keep things simple:
</p>
<p><pre class="brush: java;">
class RangeCheck implements AnnotationCheck&lt;Range&gt;{

 private static int LESS=-1;
 private static int EQUAL=0;
 private static int GREATER=1;

 @Override
 public void check(final Object o,final Field field,final Range range)
                   throws IllegalAccessException{
  final Object value=field.get(o);
  if(value != null){ //null-checks are @NotNull's business.
   if(value instanceof Number){
    final Double number=((Number)value).doubleValue();
    final int lowerBound
     =compareTolerant(range.from(),number,Math.ulp(number));
    if(lowerBound == GREATER){
     throw new IllegalArgumentException(message(o,field,
      &quot;must be greater or equal &quot;+range.from()+&quot; but is: &quot;+value));
    }
    final int upperBound
      =compareTolerant(range.to(),number,Math.ulp(number));
    if(upperBound == LESS){
     throw new IllegalArgumentException(message(o,field,
      &quot;must be less or equal &quot;+range.to() + &quot; but is: &quot;+value));
    }
   }else{
    throw new IllegalArgumentException(message(o,field,
     &quot;must reference a number. Found: &quot;+value.getClass()+&quot;: &quot;+value));
   }
  }
 }

 private static String message(final Object o,final Field field,final String details){
  return &quot;Field &quot;+o.getClass().getName()+'#'+field.getName() + &quot; &quot;+details;
 }

 private static int compareTolerant(final double a,final double b,final double tolerance){
  return a == b ? EQUAL //
    : a == Double.POSITIVE_INFINITY ? GREATER
    : b == Double.NEGATIVE_INFINITY ? GREATER
    : b == Double.POSITIVE_INFINITY ? LESS
    : a == Double.NEGATIVE_INFINITY ? LESS
    : b - tolerance &lt;= a &amp;&amp; b + tolerance &gt;= a ? EQUAL
    : a &lt; b - tolerance ? LESS : GREATER;
 }
}
</pre>
</p>
<p>
Now as we have the checks ready for action, it&#8217;s time to implement an API to use these checkers in a concise way:
</p>
<p><pre class="brush: java;">
public final class Check{

 @SuppressWarnings(&quot;unchecked&quot;)
 private static Map&lt;Class&lt;? extends Annotation&gt;,AnnotationCheck&gt; strategies
 =new HashMap&lt;Class&lt;? extends Annotation&gt;,AnnotationCheck&gt;();

 static{
  strategies.put(NotNull.class,new NotNullCheck());
  strategies.put(Range.class,new RangeCheck());
 }

 private Check(){
  // utility class
 }

 public static void declaredFieldsOf(final Object o){
  for(final Field field:o.getClass().getDeclaredFields()){
   for(final Annotation annotation:field.getAnnotations()){
    checkField(o,field,annotation);
   }
  }
 }

 private static void checkField(final Object o,final Field field,final Annotation annotation){
  final Class&lt;? extends Annotation&gt; annotationType=annotation.annotationType();
  @SuppressWarnings(&quot;unchecked&quot;)
  final AnnotationCheck&lt;Annotation&gt; checkStrategy=strategies.get(annotationType);
  if(checkStrategy != null){
   final boolean acs=field.isAccessible();
   try{
    field.setAccessible(true);
    checkStrategy.check(o,field,annotation);
   }catch(final IllegalAccessException e){
    throw new RuntimeException(e); // not expected to happen
   }finally{
    field.setAccessible(acs);
   }
  }
 }

}
</pre>
</p>
<p>
Voilà, c&#8217;est prêt à l&#8217;emploi! Now using this thing becomes a breeze:<br />
Let&#8217;s take a look at an immutable class with it&#8217;s builder, which used this new tool:
</p>
<p><pre class="brush: java;">
@Immutable
public final class Position{

 private final Article article;
 private final int amount;

 private Position(final OrderBuilder b){
  article=b.article;
  amount=b.amount;
 }

 public String getAmout(){
  return amount;
 }
 //..

 public static OrderBuilder order(){
  return new OrderBuilder();
 }

 //..

 public static class OrderBuilder{
  private final SingleThreadBarrier barrier
   = new SingleThreadBarrier(getClass());

  @NotNull
  private Article account;
  @Range(from=1)
  private int amount;
  //..
  public OrderBuilder ofArticle(final Article article){
   barrier.pass();
   this.article=article;
   return this;
  }

  //..

  public Position received(){
   barrier.pass();
   Check.declaredFieldsOf(this);
   return new OrderPosition(this);
  }

 }
}
</pre>
</p>
<p>
The methods may have some rather odd names, as they don&#8217;t seem to do what they&#8217;re called, but this is the programmers perspective from inside the API. Actually you should write a decent javadoc to accompany this. If you leave the inside-view and start looking at the API from the user&#8217;s perspective, you may notice that writing code against an API like this is a bit cumbersome, as the methods don&#8217;t do what they&#8217;re called. But remember: Code is read more often than written and just look how beautiful this one reads:
</p>
<p><pre class="brush: java;">
Position pos=Position().order() //get a builder object
 .ofArticle(kermitTheFrog) //initialize the builder
 .withAmount(10)
 .received(); //check and construct the object
</pre>
</p>
<p>
Now the reason why I validate the builder and not the built object is that I don&#8217;t want to lose flexibility. I could well design another builder for a return shipment, which builds a position with a negative amount only:
</p>
<p><pre class="brush: java;">
public static class ReturnShipmentBuilder{
   //..
  @NotNull
  private Article account;
  @Range(to=-1)
  private int amount;
  //..
</pre>
</p>
<p>
And it would still look good:
</p>
<p><pre class="brush: java;">
Position pos=Position().returnShipment()
 .ofArticle(kermitTheFrog)
 .withAmount(10) //boom! This should be negative!
 .received();
</pre>
</p>
<p>
Alas, setting up multiple builders which just have some differently annotated fields stinks. Here we could create one common builder and just let it use another internal mutable class to hold the data, just what a C++-programmer would call a struct. One builder, but different structs with different annotations. The common builder would run the check against its struct and everything is honkey dory. But I&#8217;m gonna leave you that as a little homework. Right now my mind fills with ideas for a flexible validation mechanism, where a validator nothing more than some annotated fields and a method which fills those from a model and calls the checker. I&#8217;m not sure yet, whether I want to write about that or find something different to fiddle with. We will see. Stay tuned!</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a>, <a href='http://brixomatic.wordpress.com/category/fluent-interfaces/'>Fluent interfaces</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/annotations/'>Annotations</a>, <a href='http://brixomatic.wordpress.com/tag/api-design/'>API-Design</a>, <a href='http://brixomatic.wordpress.com/tag/coding-style/'>Coding-Style</a>, <a href='http://brixomatic.wordpress.com/tag/fluent/'>Fluent</a>, <a href='http://brixomatic.wordpress.com/tag/immutability/'>Immutability</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a>, <a href='http://brixomatic.wordpress.com/tag/reflection/'>Reflection</a>, <a href='http://brixomatic.wordpress.com/tag/validation/'>Validation</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/62/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/62/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/62/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=62&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/03/20/using-annotations-for-validation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Dealing with immutability and long constructors in a fluent way.</title>
		<link>http://brixomatic.wordpress.com/2010/03/10/dealing-with-immutability-and-long-constructors-in-a-fluent-way/</link>
		<comments>http://brixomatic.wordpress.com/2010/03/10/dealing-with-immutability-and-long-constructors-in-a-fluent-way/#comments</comments>
		<pubDate>Wed, 10 Mar 2010 19:29:13 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[Fluent interfaces]]></category>
		<category><![CDATA[API-Design]]></category>
		<category><![CDATA[Coding-Style]]></category>
		<category><![CDATA[Fluent]]></category>
		<category><![CDATA[Immutability]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/?p=43</guid>
		<description><![CDATA[I use to state that the best thing to do is to keep your code simple and clean. But if your task is to design an easy-to-understand and easy-to-change API, this may be a bad advice. There simply is no silver bullet in programming and simplicity ain&#8217;t one either. There is a common case you [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=43&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
I use to state that the best thing to do is to keep your code simple and clean. But if your task is to design an easy-to-understand and easy-to-change API, this may be a bad advice. There simply is no silver bullet in programming and simplicity ain&#8217;t one either.
</p>
<p>
There is a common case you may have encountered more than once, which is long constructors with repeating types. You&#8217;re likely to see them in immutable classes. I&#8217;m not going to discuss why immutable classes are desirable, I&#8217;m going to talk about easing the pain to construct them. <span id="more-43"></span>Take this for example, I must admit that I tended to write code like this quite often.:</p>
<pre class="brush: java;">
@Immutable
public Address(String street, String zipcode, String town, String country){
 //...
}
</pre>
</p>
<p>
True, the IDE may help you with displaying the parameter names in a pop up, but no one will warn you if you get the order wrong and if Murphy loves your company, you&#8217;ll end up with a pile of unusable data in a productive database. It gets worse if you decide to re-factor the class. If you change the parameter order of example, it just needs a bad moment for a CVS-commit to cause major mayhem, which gets more likely the bigger the team and the higher the fan-in-complexity of the class is.<br />
<br />
This can be avoided, unfortunately at the price of complexity. Let me introduce to you two approaches: The copy-mutator-method and the builder-class.
</p>
<h2>Copy-Mutator</h2>
<p>
This pattern is quite nice to enforce immutability and at the same time avoid problems with ambiguous constructor arguments plus it is easy to write, but it has downsides. Let me first show the source code and discuss the rest later.</p>
<pre class="brush: java;">
@Immutable
public final class Address{

  private String street;
  private String zipcode;
  private String town;
  private String country;

  public Address(){}

  private Address(final Address a){
   street=a.street;
   zipcode=a.zipcode;
   town=a.town;
   country=a.country;
  }

  public String getStreet(){
   return street;
  }
  //..

  public final Address withStreet(final String steet){
   final Address a=new Address(this);
   a.street=street;
   return a;
  }

  public final Address withZipcode(final String zipcode){
   final Address a=new Address(this);
   a.zipcode=zipcode;
   return a;
  }

   //..
}
</pre>
</p>
<p>
Here we go. To initialize an object with this pattern is a nice and fluent expression:</p>
<pre class="brush: java;">
Address home=new Address()
 .withStreet(&quot;Sesame St. 10&quot;)
 .withZipcode(&quot;12345&quot;)
 .withTown(&quot;Muppetcity&quot;)
 .withCountry(&quot;USA&quot;);
</pre>
</p>
<p>
So why not simply use a bean and setters? Well, it may be just as readable, but objects made like this can be immutable and beans can not. So if you want to enforce immutability, here&#8217;s a solution.
</p>
<p>But there are downsides to this pattern:<br />
First, the fields are not final, which requires a little more care when you touch and change the internals of the class, so you don&#8217;t introduce mutable state to an immutable class by accident. I would consider that a low risk, but it&#8217;s there.
</p>
<p>
Secondly this pattern creates a lot of intermediate objects that get thrown away immediately. This may seem to be a problem if you want to create a lot of these objects in a tight loop, but it isn&#8217;t. It isn&#8217;t, because you will rarely find yourself in a situation, where such a constant cost is a real issue – and if you do you can still tune this hot spot and keep the rest of the code tidy. And it isn&#8217;t because a modern JVM can handle these kind of object allocations very well, as pointed out in <a href="http://www.ibm.com/developerworks/java/library/j-jtp09275.html">this excellent article by Brian Goetz</a>. So consider this a non-issue.
</p>
<p>
The last downside with this pattern I&#8217;d like to mention is the only real downside in my humble opinion: If your requirement is to disallow &#8220;null&#8221; for any fields, you have a problem.<br />
You&#8217;d have to write a method to check the fields against null, but you are not forced to call it right after initialization. And if you install a check at field-access time, your object may cause an exception way after initialization, which makes it hard to impossible to find the cause, because you needed to check every initialization.<br />
In short: If you need to check invariants on initialization, this pattern is not an option.
</p>
<p>
Luckily there is another pattern which allows to avoid this particular downside at the expense of some more lines of code:
</p>
<h2>The Builder</h2>
<p>
The builder is a mutable object which creates the immutable object after checking everything is set up as required. Because the builder is mutable it cannot be shared safely among threads (thanks for the hint, Theo!). It is therefore wise to prevent any other thread from accessing the builder than the one that created it. A simple barrier will do the job:<br />
</p>
<pre class="brush: java;">
public class SingleThreadBarrier{
 private final Class&lt;?&gt; c;
 private final Thread thread;

 public SingleThreadBarrier(final Class&lt;?&gt; c){
  this.c=c;
  thread=Thread.currentThread();
 }

 void pass(){
  if(thread != Thread.currentThread()){
   throw new IllegalStateException(&quot;Multithreaded access to &quot;+c+&quot; forbidden.&quot;);
  }
 }
}
</pre>
</p>
<p>
Now with our barrier ready to go, let me show you the sourcecode for the builder:</p>
<pre class="brush: java;">
 @Immutable
 public final class Address{

  private final String street;
  private final String zipcode;
  private final String town;
  private final String country;

  private Address(final AddressBuilder b){
   street=b.street;
   zipcode=b.zipcode;
   town=b.town;
   country=b.country;
  }

  public String getStreet(){
   return street;
  }
  //..

  public static AddressBuilder build(){
   return new AddressBuilder();
  }
  //..

  public static class AddressBuilder{
   private final SingleThreadBarrier barrier
    = new SingleThreadBarrier(getClass());
   private String street;
   private String zipcode
   //..
   public AddressBuilder withStreet(final String street){
    barrier.pass();
    this.street=street;
    return this;
   }

   public AddressBuilder withZipcode(final String zipcode){
    barrier.pass();
    this.zipcode=zipcode;
    return this;
   }

   //..

   public Address noNullPropertyAllowed(){
    barrier.pass();
    if(Arrays.asList(street, zipcode, town, country).contains(null)){
      throw new NullPointerException();
    }
    return new Address(this);
   }

  }
 }
</pre>
</p>
<p>
As you can see building an address with this pattern is just a tiny bit longer, but still a very fluent expression which almost reads like a book:</p>
<pre class="brush: java;">
Address home=Address.build() //get a builder object
 .withStreet(&quot;Sesame St. 10&quot;) //initialize the builder
 .withZipcode(&quot;12345&quot;)
 .withTown(&quot;Muppetcity&quot;)
 .withCountry(&quot;USA&quot;)
 .noNullPropertyAllowed(); //check builder's setup and construct the address
</pre>
</p>
<p>
One nice thing about this pattern is, for a start, that the fields of the immutable object are final, so you can&#8217;t create a mutable state by accident. The more important goodie is the method which finally checks and constructs the immutable object. Because you can have more than one! In other words: it&#8217;s an extensible design. I just wrote a very basic implementation to keep it short, but you may add other validation methods without breaking anything and when you start thinking about it for a moment, things like &#8220;@NotNull&#8221;, annotations in general, &#8220;Reflection&#8221; and &#8220;Strategy Pattern&#8221; might spring to mind. Maybe I&#8217;ll revisit this topic in a later blog posting, but for now I&#8217;ll call it a day and leave you with your own thoughts or even the urge to comment, which is highly appreciated.</p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a>, <a href='http://brixomatic.wordpress.com/category/fluent-interfaces/'>Fluent interfaces</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/api-design/'>API-Design</a>, <a href='http://brixomatic.wordpress.com/tag/coding-style/'>Coding-Style</a>, <a href='http://brixomatic.wordpress.com/tag/fluent/'>Fluent</a>, <a href='http://brixomatic.wordpress.com/tag/immutability/'>Immutability</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/43/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/43/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/43/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=43&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/03/10/dealing-with-immutability-and-long-constructors-in-a-fluent-way/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
		<item>
		<title>Boolean parameters considered harmful &#8211; almost</title>
		<link>http://brixomatic.wordpress.com/2010/02/24/boolean-harmful/</link>
		<comments>http://brixomatic.wordpress.com/2010/02/24/boolean-harmful/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 21:54:04 +0000</pubDate>
		<dc:creator>Wanja Gayk</dc:creator>
				<category><![CDATA[API and Patterns]]></category>
		<category><![CDATA[API-Design]]></category>
		<category><![CDATA[Coding-Style]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://brixomatic.wordpress.com/2010/02/24/boolean-harmful/</guid>
		<description><![CDATA[I have to admit this blog&#8217;s title is a bit exaggerated, but since I have lately seen some bad examples of using booleans as parameters, I just felt the urge to write about it. Code is more often read than written, so readability is a great concern in programming and often it&#8217;s the small things [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=1&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
I have to admit this blog&#8217;s title is a bit exaggerated, but since I have lately seen some bad examples of using booleans as parameters, I just felt the urge to write about it.
</p>
<p><span id="more-1"></span></p>
<p>
Code is more often read than written, so readability is a great concern in programming and often it&#8217;s the small things that make things worse and can it get smaller than a boolean? The other big issue with programming in general is that code must be maintainable, so it must be easy to change it. Sometimes it needs to be cleaned up, sometimes functionality has to be added, so ripple effects is something we don&#8217;t need.<br />
For both reasons I have noticed myself using less boolean parameters every day.  Today I would even state that using a boolean parameter is a bad idea in most cases. Let me demonstrate my point with a little example:
</p>
<p><pre class="brush: java;">
&lt;T extends Component&gt; T find(final Class&lt;T&gt; type,String name,final boolean descend,final Component... components){
 T result=null;
 if (components != null){
  for (int t=0; result==null &amp;&amp; t&lt;components.length; ++t){
   final Component candidate=components[t];
   if (type.isInstance(candidate) &amp;&amp; equals(name, candidate.getName())) {
    return type.cast(candidate);
   } else if (descend &amp;&amp; candidate instanceof Container){
    result = find(type,name,descend,((Container)candidate).getComponents());
   }
  }
 }
 return result;
}
</pre>
<p>This code doesn&#8217;t look suspicious, but the ugly gets apparent when this method gets used:
</p>
<p><pre class="brush: java;">
Component x = find( Button.class, &quot;button&quot;, true, root );
</pre>
<p>If you see a line like this in a program, you usually have no idea what &#8216;true&#8217; stands for, until you dig into the code of the method &#8211; which gets worse if the sourcecode is not available. <br />
And what if you need to introduce scanning upwards in the hierarchy? You would need to change the API significantly and break every method that uses this API. Or you&#8217;d need to introduce a new method which will probably make you copy code or deprecate the old method (which you will never get rid of).
</p>
<p>
So usually it&#8217;s a better strategy to use an enumeration, which creates a few more lines of code, but just have a look:</p>
<pre class="brush: java;">
static enum Search{
 FLAT, DESCENDING;
}

&lt;T extends Component&gt; T find(final Class&lt;T&gt; type,String name,final Search strategy,final Component... components){
 T result = null;
 if(components != null){
  for(int t=0; result==null &amp;&amp; t&lt;components.length; ++t){
   final Component candidate = components[t];
   if(type.isInstance(candidate) &amp;&amp; equals(name,candidate.getName())){
    return type.cast(candidate);
   } else if (strategy==Search.DESCENDING &amp;&amp; candidate instanceof Container){
    result=find(type,name,strategy,((Container)candidate).getComponents());
   }
  }
 }
 return result;
}
</pre>
<p>The full beauty of this API is visible when it is used, just have a look at this:
</p>
<p><pre class="brush: java;">
Component x = find( Button.class, &quot;button&quot;, Search.DESCENDING, root );
Component y = find( JPanel.class, &quot;rightPanel&quot;, Search.FLAT, root );
</pre>
<p>Just by looking at the code you could guess what the parameter does.
</p>
<p>
This API also supports enhancing the functionality way better. To implement scanning upwards the hierarchy, just modify the enumeration and add some lines to the method:
</p>
<p><pre class="brush: java;">
static enum Search{
 ASCENDING, FLAT, DESCENDING;
}

&lt;T extends Component&gt; T find(final Class&lt;T&gt; type,String name,final Search strategy,final Component... components){
 T result = null;
 if(components != null){
  for(int t=0; result==null &amp;&amp; t&lt;components.length; ++t){
   final Component candidate = components[t];
   if(type.isInstance(candidate) &amp;&amp; equals(name,candidate.getName())){
    return type.cast(candidate);
   } else if (strategy==Search.DESCENDING &amp;&amp; candidate instanceof Container){
    result=find(type,name,strategy,((Container)candidate).getComponents());
   }
  }
  if (strategy==Search.ASCENDING){
   result=find(type,name,strategy,candidate.getParent());
  }
 }
 return result;
}
</pre>
<p>So here it is: I&#8217;ve enhanced the functionality without breaking the old API just by adding an enumeration and another branch.
</p>
<p><pre class="brush: java;">
Component x = find( Button.class, &quot;button&quot;, Search.DESCENDING, root );
Component y = find( JPanel.class, &quot;rightPanel&quot;, Search.FLAT, root );
Component z = find( TabbedPane.class, &quot;tabs&quot;, Search.ASCENDING, textField );
</pre>
<p>The old stuff still works, it is still readable. A much better solution than a boolean.
</p>
<p>
Now just imagine the Swing API, if it looked a little bit like:</p>
<pre class="brush: java;">
jFrame1.setState(State.MAXIMIZED);
jFrame2.setState(State.RESTORED);
jFrame3.setState(State.MINIMIZED);
jFrame4.setState(State.ICONIFIED);
jFrame5.setState(State.INVISIBLE);
</pre></p>
<br />Filed under: <a href='http://brixomatic.wordpress.com/category/api-and-patterns/'>API and Patterns</a> Tagged: <a href='http://brixomatic.wordpress.com/tag/api-design/'>API-Design</a>, <a href='http://brixomatic.wordpress.com/tag/coding-style/'>Coding-Style</a>, <a href='http://brixomatic.wordpress.com/tag/java/'>Java</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/brixomatic.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/brixomatic.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/brixomatic.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/brixomatic.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/brixomatic.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/brixomatic.wordpress.com/1/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/brixomatic.wordpress.com/1/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/brixomatic.wordpress.com/1/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=brixomatic.wordpress.com&amp;blog=12229220&amp;post=1&amp;subd=brixomatic&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://brixomatic.wordpress.com/2010/02/24/boolean-harmful/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/1719bd4e2c17ea53f48f56ff0fddceee?s=96&#38;d=monsterid&#38;r=G" medium="image">
			<media:title type="html">brixomatic</media:title>
		</media:content>
	</item>
	</channel>
</rss>
