<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" gd:etag="W/&quot;AkINSH4yeSp7ImA9WhRaE0U.&quot;"><id>tag:blogger.com,1999:blog-3821115221571460038</id><updated>2012-02-16T02:36:39.091-08:00</updated><category term="AppEngine" /><category term="OO Design" /><category term="JMockit" /><category term="Lab49" /><category term="Java" /><category term="Maven" /><category term="Bad Code Practice" /><title>Shanks' Tech Musings</title><subtitle type="html" /><link rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" href="http://www.vshank77.com/feeds/posts/default" /><link rel="alternate" type="text/html" href="http://www.vshank77.com/" /><author><name>Shankar Vasudevan</name><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="32" height="32" src="//lh6.googleusercontent.com/-_7KGeYn3p_M/AAAAAAAAAAI/AAAAAAAAAAA/HDmbwV-k2AI/s512-c/photo.jpg" /></author><generator version="7.00" uri="http://www.blogger.com">Blogger</generator><openSearch:totalResults>3</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/vshank77" /><feedburner:info uri="vshank77" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><entry gd:etag="W/&quot;Ck8NR3Y9fip7ImA9WxBWEEs.&quot;"><id>tag:blogger.com,1999:blog-3821115221571460038.post-9038156402701573604</id><published>2010-02-01T13:46:00.000-08:00</published><updated>2010-02-01T13:48:16.866-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-02-01T13:48:16.866-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="Lab49" /><category scheme="http://www.blogger.com/atom/ns#" term="JMockit" /><title>JMockit &amp; JavaAgent - Enterprise integration woes</title><content type="html">We've been using &lt;a href="http://code.google.com/p/jmockit/" target="_blank"&gt;JMockit&lt;/a&gt; as the preferred mocking utility at a large Bank that I'm consulting at. While generally the product and its &lt;a href="http://dhruba.name/2009/11/08/jmockit-no-holds-barred-testing-with-instrumentation-over-mocking/" target="_blank"&gt;non-intrusive mocking&lt;/a&gt; features are commendable, some of the under-the-hood mechanisms have caused us a nightmare with our continuous integration.

After upgrading to latest version of JMockit, version 0.996.0, we had ALL our unit tests failing with the following spurious error
&lt;br /&gt;
&lt;pre class="brush: java"&gt;java.lang.NoClassDefFoundError: org.junit.runner.Runner
 at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
 at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:24)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.&lt;init&gt;(JUnit4TestReference.java:29)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestClassReference.&lt;init&gt;(JUnit4TestClassReference.java:25)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:40)
 at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:30)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:452)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
 at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
&lt;/init&gt;&lt;/init&gt;&lt;/pre&gt;
While my colleague who had been advocating the use of the utility asked me for a way to change the order of libraries in the classpath, we smelt rot and started debugging under the hood. After quite a bit of digging around, we found that the actual error was caused by the failure to load the JMockit agent dynamically. The following code is the sequence of calls which JMockit makes to load the agent.
&lt;br /&gt;
&lt;pre class="brush: java"&gt; public class Startup {

   // other code omitted 
   public static void verifyInitialization()
   {
      if (instrumentation == null) {
         new AgentInitialization().initializeAccordingToJDKVersion();
      }
   }
}

public final class AgentInitialization
{
   public void initializeAccordingToJDKVersion()
   {
      String jarFilePath = discoverPathToJarFile();
      if (Startup.jdk6OrLater) {
         new JDK6AgentLoader(jarFilePath).loadAgent();
      }
      else if ("1.5".equals(Startup.javaSpecVersion)) {
         throw new IllegalStateException(
            "JMockit has not been initialized. Check that your Java 5 VM has been started " +
            "with the -javaagent:" + jarFilePath + " command line option.");
      }
      else {
         throw new IllegalStateException("JMockit requires a Java 5 VM or later.");
      }
   }
   private String discoverPathToJarFile()
   {
      CodeSource codeSource = AgentInitialization.class.getProtectionDomain().getCodeSource();
      if (codeSource == null) {
         return findPathToJarFileFromClasspath();
      }

      URI jarFileURI; // URI is needed to deal with spaces and non-ASCII characters
      try {
         jarFileURI = codeSource.getLocation().toURI();
      }
      catch (URISyntaxException e) {
         throw new RuntimeException(e);
      }

      return new File(jarFileURI).getPath();
   }

   private String findPathToJarFileFromClasspath()
   {
      String[] classPath = System.getProperty("java.class.path").split(File.pathSeparator);
      for (String cpEntry : classPath) {
         if (cpEntry.matches(".*jmockit[-.\\d]*.jar")) {
            return cpEntry;
         }
      }
      return null;
   }
}&lt;/pre&gt;
While this approach is non-intrusive and works out of the box in most cases, in large enterprise organisations, you are often limited extensively and work in a confined environment. My current environment loads files from a network file system and the following lines from the &lt;i&gt;discoverPathToJarFile()&lt;/i&gt; cause the class initialization error
&lt;br /&gt;
&lt;pre class="brush: java"&gt; jarFileURI = codeSource.getLocation().toURI(); &lt;/pre&gt;
returns 
&lt;br /&gt;
&lt;pre class="brush: java"&gt; CodeSource
file://remoterepository/libraries/jmockit/0.996.0/install/common/lib/jmockit.jar &lt;/pre&gt;
and &lt;br /&gt;
&lt;pre class="brush: java"&gt; return new File(jarFileURI).getPath(); &lt;/pre&gt;
returns &lt;br /&gt;
&lt;pre class="brush: java"&gt; IllegalArgumentException: URI has an authority component &lt;/pre&gt;
We had been using JMockit for a while now since 0.991.0 version and the agent loading had always been a problem. In our original usage, we had to do two things. We had to create our own version of the &lt;a href="http://code.google.com/p/jmockit/source/browse/trunk/main/src/mockit/internal/startup/JDK6AgentLoader.java" target="_blank"&gt;JDK6AgentLoader&lt;/a&gt; as this class has package level scope and create our own JUnit4 runner which loaded the agent from a hard-coded location, as below
&lt;br /&gt;
&lt;pre class="brush: java"&gt;public final class MyJMockitRunner extends BlockJUnit4ClassRunner
{
   static
   {
      MyJDK6AgentLoader.loadAgent(hardCodedPathtoAgentJar);
   }

   public JMockit(Class testClass) throws InitializationError
   {
      super(testClass);
   }
}
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;Why the problem now?&lt;/b&gt;&lt;br /&gt;

What changed majorly between the two versions was, Shadowing the org.junit.runner.Runner class which in the modified version loaded the java agent before initialization of the class. &lt;br /&gt;
&lt;pre class="brush: java"&gt;public abstract class Runner implements Describable
{
   static
   {
      Startup.initializeIfNeeded();
   }

   public abstract Description getDescription();

   public abstract void run(RunNotifier notifier);

   public int testCount()
   {
      return getDescription().testCount();
   }
}&lt;/pre&gt;
So even though we are trying to load the agent in our custom Runner, the loading of the Runner class itself preceding the sequence and aggressively loads the agent in its own strategy.

While this is a possible approach, I would highly criticize the usage of class shadowing for the following reasons

&lt;ol&gt;
&lt;li&gt;Open source API generally provide certain basic guarantees, and is generally tested extensively by the commnuity in different enviroments to ensure they work in the way they are designed. By shadowing a public class, you override this guarantee and for most common developers, the fact that they are using a modified class is oblivious. This can lead to late night debugging sessions and nightmares when things go wrong.&lt;/li&gt;
&lt;li&gt;In this particular case, while only the tests that used JMockit should have failed, thousands of test cases across multiple projects failed at once. As a programmer, I always believe to lazily load resources and only when they are needed. But there is a necessity for mocking or not, the agent is going to be loaded whenever a Unit test is run. This is fundamentally wrong.&lt;/li&gt;
&lt;li&gt;Any workarounds that had been applied to the library fail miserably with this aggressive approach to force your library to behave in a specific way.&lt;/li&gt;
&lt;li&gt;While I agree that the owner cannot foresee all the environments his library would be used, trying to perform gimmicks under the hood on an open library could have been avoided.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
&lt;b&gt;Solution&lt;/b&gt; &lt;br /&gt;

While I've criticized the usage of shadowing a class, unfortunately the only solution that worked for us was to shadow the JMockit class that loaded the agent as below.
&lt;br /&gt;
&lt;pre class="brush: java"&gt;public final class AgentInitialization
{
   public void initializeAccordingToJDKVersion()
   {
 MyJDK6AgentLoader.loadAgent(hardCodedPathtoAgentJar);
   }
}&lt;/pre&gt;
&lt;br&gt;&lt;b&gt;Better approach&lt;/b&gt;&lt;br /&gt;

There are a couple of suggestions for the JMockit API to overcome the shortcomings described above

&lt;ol&gt;
&lt;li&gt;Please do remove the shadowed JUnit class and make the agent loading explicit. This is already the case when you use the JMockit.class as the runner.&lt;/li&gt;
&lt;li&gt;While the auto detection of the agent is brilliant, there could be some hooking mechanism which allowed the developers to extend it with their own strategies.&lt;/li&gt;
&lt;/ol&gt;

Last but not least, there definitely was an obvious solution to the problem, which was to explicitly specify the agent path in the VM arguments. The issue we had in that was there were too many OS, at least a few IDE, a shared continuous integration server and many many ant build scripts that need to be updated. It would have been a far more involved effort to get all this modified and maintained than applying a code fix which worked "under the hood"&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3821115221571460038-9038156402701573604?l=www.vshank77.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vshank77/~4/er91ScKi2nQ" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.vshank77.com/feeds/9038156402701573604/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.vshank77.com/2010/02/jmockit-javaagent-enterprise.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3821115221571460038/posts/default/9038156402701573604?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3821115221571460038/posts/default/9038156402701573604?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/vshank77/~3/er91ScKi2nQ/jmockit-javaagent-enterprise.html" title="JMockit &amp; JavaAgent - Enterprise integration woes" /><author><name>Shankar Vasudevan</name><uri>http://www.blogger.com/profile/15139006072777819989</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>1</thr:total><feedburner:origLink>http://www.vshank77.com/2010/02/jmockit-javaagent-enterprise.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEQFQXo-cCp7ImA9WxBQGEg.&quot;"><id>tag:blogger.com,1999:blog-3821115221571460038.post-4120746873719326615</id><published>2010-01-17T11:51:00.000-08:00</published><updated>2010-01-18T14:05:10.458-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-01-18T14:05:10.458-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Java" /><category scheme="http://www.blogger.com/atom/ns#" term="AppEngine" /><category scheme="http://www.blogger.com/atom/ns#" term="Maven" /><category scheme="http://www.blogger.com/atom/ns#" term="Lab49" /><title>Google Appengine and Maven - another hack for datanucleus plugin</title><content type="html">After researching for mavenizing an Appengine pet project, most of the links that Google search returned were really old when first version of AppEngine was released and did not match the expectations. Also unfortunately there is really no maven plugin that supports the latest version as Google publishes them or a plugin that allows you to point to a local installation, so that you could update at the speed of Google releasing updates for AppEngine (as of this writing, there were atleast 3 updates in the shorter period of 2 weeks)
&lt;p /&gt;
Thanks to &lt;a href="http://www.salientpoint.com/blog/?p=480" target="_blank"&gt;Salient Point&lt;/a&gt;, this was the best article to configure a maven project and it allowed to configure any AppEngine version with the simplicity of changing a couple of variables in a script file and building the maven project. However the only caveat that needed a few hours of debugging was the &lt;i&gt;maven-datanucleus-plugin&lt;/i&gt;, as again the versions of the Jar files provided by datanucleus repository and the ones that are published by Google were slightly different and it was more simpler to use the same philosophy of having all the Jars provided by Google rather than downloading them from a different repository.
&lt;p /&gt;
On this note, the following are the only deviation of configurations from the original post

1) Define the local directory to which the AppEngine Jars have been downloaded, the preferred way is to use profiles such that we could specify a default location in each platform (windows / mac)
&lt;br /&gt;
&lt;pre class="brush: xml"&gt;        &amp;lt;profile&amp;gt;
            &amp;lt;id&amp;gt;gwt-dev-windows&amp;lt;/id&amp;gt;
            &amp;lt;properties&amp;gt;
                &amp;lt;platform&amp;gt;windows&amp;lt;/platform&amp;gt;
                &amp;lt;appengine.sdk.root&amp;gt;C:\Java\appengine-java-sdk-${appengineVersion}&amp;lt;/appengine.sdk.root&amp;gt;
            &amp;lt;/properties&amp;gt;
            &amp;lt;activation&amp;gt;
                &amp;lt;activeByDefault&amp;gt;false&amp;lt;/activeByDefault&amp;gt;
                &amp;lt;os&amp;gt;
                    &amp;lt;family&amp;gt;windows&amp;lt;/family&amp;gt;
                &amp;lt;/os&amp;gt;
            &amp;lt;/activation&amp;gt;
        &amp;lt;/profile&amp;gt;
&lt;/pre&gt;
2) Specify a antrun task that performs the datanucleus enhancement for entity objects rather than the datanucleus plugin
&lt;br /&gt;
&lt;pre class="brush: xml"&gt;            &amp;lt;plugin&amp;gt;
                &amp;lt;artifactId&amp;gt;maven-antrun-plugin&amp;lt;/artifactId&amp;gt;
                &amp;lt;executions&amp;gt;
                    &amp;lt;execution&amp;gt;
                        &amp;lt;id&amp;gt;datanucleus-enhance&amp;lt;/id&amp;gt;
                        &amp;lt;phase&amp;gt;process-classes&amp;lt;/phase&amp;gt;
                        &amp;lt;configuration&amp;gt;
                            &amp;lt;tasks&amp;gt;
                                &amp;lt;property name="appengine.tools.classpath"
                                    location="${appengine.sdk.root}/lib/appengine-tools-api.jar"/&amp;gt;
                                &amp;lt;property name="dependency_classpath" refid="maven.dependency.classpath"/&amp;gt;

                                &amp;lt;taskdef name="enhance" classname="com.google.appengine.tools.enhancer.EnhancerTask"
                                    classpath="${appengine.tools.classpath}"/&amp;gt;
                                &amp;lt;enhance failonerror="true" api="JPA"&amp;gt;
                                    &amp;lt;classpath&amp;gt;
                                        &amp;lt;pathelement path="${appengine.tools.classpath}"/&amp;gt;
                                        &amp;lt;pathelement path="${dependency_classpath}"/&amp;gt;
                                        &amp;lt;pathelement path="target/classes"/&amp;gt;
                                    &amp;lt;/classpath&amp;gt;
                                    &amp;lt;fileset dir="target/classes" includes="**/*.class"/&amp;gt;
                                &amp;lt;/enhance&amp;gt;
                            &amp;lt;/tasks&amp;gt;
                        &amp;lt;/configuration&amp;gt;
                        &amp;lt;goals&amp;gt;
                            &amp;lt;goal&amp;gt;run&amp;lt;/goal&amp;gt;
                        &amp;lt;/goals&amp;gt;
                    &amp;lt;/execution&amp;gt;
                &amp;lt;/executions&amp;gt;
            &amp;lt;/plugin&amp;gt;
&lt;/pre&gt;
Alas it works like magic for us and we are able to upgrade the AppEngine versions as and when they are released by Google. 
&lt;p /&gt;
Also to note is the link on configuring a &lt;a href="http://mojo.codehaus.org/gwt-maven-plugin/user-guide/multiproject.html" target="_blank"&gt;multi-project setup&lt;/a&gt; that is documented on the maven-gwt-plugin documentation that helps to organize your code into multiple projects (separating the core API / UI / service implementation and AppEngine deployment). Refer to our sample project setup that is hosted at &lt;a href="http://code.google.com/p/scrumsp/source/browse/"&gt;http://code.google.com/p/scrumsp&lt;/a&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3821115221571460038-4120746873719326615?l=www.vshank77.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vshank77/~4/MX4yVhnzpgU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.vshank77.com/feeds/4120746873719326615/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.vshank77.com/2010/01/google-appengine-and-maven-another-hack.html#comment-form" title="0 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3821115221571460038/posts/default/4120746873719326615?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3821115221571460038/posts/default/4120746873719326615?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/vshank77/~3/MX4yVhnzpgU/google-appengine-and-maven-another-hack.html" title="Google Appengine and Maven - another hack for datanucleus plugin" /><author><name>Shankar Vasudevan</name><uri>http://www.blogger.com/profile/15139006072777819989</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>0</thr:total><feedburner:origLink>http://www.vshank77.com/2010/01/google-appengine-and-maven-another-hack.html</feedburner:origLink></entry><entry gd:etag="W/&quot;CEMFRH84eSp7ImA9WxBQGEg.&quot;"><id>tag:blogger.com,1999:blog-3821115221571460038.post-9208868222180776443</id><published>2009-12-15T22:49:00.000-08:00</published><updated>2010-01-18T14:06:55.131-08:00</updated><app:edited xmlns:app="http://www.w3.org/2007/app">2010-01-18T14:06:55.131-08:00</app:edited><category scheme="http://www.blogger.com/atom/ns#" term="Bad Code Practice" /><category scheme="http://www.blogger.com/atom/ns#" term="OO Design" /><category scheme="http://www.blogger.com/atom/ns#" term="Lab49" /><title>Builder Pattern Abused</title><content type="html">&lt;span style="font-family: 'Lucida Grande'; font-size: 13px; line-height: 19px; white-space: pre-wrap;"&gt;Everyone has read Joshua Bloch's builder pattern, which he has also described at his &lt;a href="http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-2689&amp;amp;yr=2007&amp;amp;track=5"&gt;"Effective Java Reloaded" &lt;/a&gt;sessions at Javaone. However in this post, I am going to describe a misuse of this pattern, when used in conjunction with inheritance.&amp;nbsp;&lt;/span&gt;&lt;br /&gt;
&lt;span style="font-family: 'Lucida Grande'; font-size: 13px; line-height: 19px; white-space: pre-wrap;"&gt;When building a relational model, the biggest challenge is to maintain the integrity of inheritance and reduce the visibility of the properties completely. However if you need builders for this model, then you either have to create a class hierarchy of builders similar to the model itself or make all accesses protected (ugly #1) so that builders could appropriately initialize them. Making the properties less visible has at least two disadvantages though (1) you cannot make them final and ensure construction safe and (2) you'll end up copying the builders to more than one class (ugly #2)

I recently came across a horrendous implementation of the hierarchy of builders where the author could not solve the above issues elegantly. So he had resorted to creating copy constructors (ugly #3) for the builders and also duplicating the methods for each of the builders. 

The following code snippet exactly reproduces the code, in an example class hierarchy and its builders.&lt;/span&gt;
&lt;br /&gt;
&lt;pre class="brush: java"&gt;abstract class Shape {
    private String name;
    private Dimension dimension;

    public enum Dimension {
        TWO_D, THREE_D;
    }

    public static abstract class ShapeBuilder {
        private String name;
        private Dimension dimension;

        protected ShapeBuilder copyOf(ShapeBuilder builder) {
            ShapeBuilder copy = createBuilder();
            copy.name = builder.name;
            copy.dimension = builder.dimension;
            return copy;
        }
        public ShapeBuilder name(String name) {
            ShapeBuilder bldr = copyOf(this);
            bldr.name = name;
            return bldr;
        }
        public ShapeBuilder dimension(Dimension dimension) {
            ShapeBuilder bldr = copyOf(this);
            bldr.dimension = dimension;
            return bldr;
        }
        public Shape build() {
            Shape s = createInstance();
            s.name = this.name;
            s.dimension = this.dimension;
            return s;
        }
        abstract Shape createInstance();
        abstract ShapeBuilder createBuilder();
    }
    // omitting getters for clarity
}
abstract class TwoDShape extends Shape {
    private double area;

    public static abstract class TwoDShapeBuilder extends ShapeBuilder {
        private double area;

        protected TwoDShapeBuilder copyOf(TwoDShapeBuilder builder) {
            TwoDShapeBuilder copy = (TwoDShapeBuilder) super.copyOf(builder);
            copy.area = this.area;
            return copy;
        }
        public TwoDShapeBuilder name(String name) {
            return (TwoDShapeBuilder) super.name(name);
        }
        public TwoDShapeBuilder dimension(Dimension dimension) {
            return (TwoDShapeBuilder) super.dimension(dimension);
        }
        public TwoDShapeBuilder area(double area) {
            TwoDShapeBuilder bldr = copyOf(this);
            bldr.area = area;
            return bldr;
        }
        public TwoDShape build() {
            TwoDShape s = (TwoDShape) super.build();
            s.area = this.area;
            return s;
        }
    }
}
class Circle extends TwoDShape {
    private double radius;

    public static class CircleBuilder extends TwoDShapeBuilder {
        private double radius;

        protected CircleBuilder copyOf(CircleBuilder builder) {
            CircleBuilder copy = (CircleBuilder) super.copyOf(builder);
            copy.radius = this.radius;
            return copy;
        }
        public CircleBuilder name(String name) {
            return (CircleBuilder) super.name(name);
        }
        public CircleBuilder dimension(Dimension dimension) {
            return (CircleBuilder) super.dimension(dimension);
        }
        public CircleBuilder area(double area) {
            return (CircleBuilder) super.area(area);
        }
        public CircleBuilder radius(double radius) {
            CircleBuilder bldr = copyOf(this);
            bldr.radius = radius;
            return bldr;
        }
        public Circle build() {
            Circle s = (Circle) super.build();
            s.radius = this.radius;
            return s;
        }
        @Override
        protected Shape createInstance() {
            return new Circle();
        }
        @Override
        protected ShapeBuilder createBuilder() {
            return new CircleBuilder();
        }
    }
}
abstract class ThreeDShape extends Shape {
    private double volume;
    // builder similar to 2DShape
}
class Cube extends ThreeDShape {
    private int side;
    // builder similar to Circle
}
&lt;/pre&gt;
&lt;span style="font-family: 'Lucida Grande'; font-size: 13px; line-height: 19px; white-space: pre-wrap;"&gt;Now extrapolate this class into an enterprise relational model consisting of 10-15 objects with nested hierarchies and you can imagine the amount of stupid code that's been written. 

If you haven't solved this problem yourself before, please stop here and think for a solution. The biggest issue here is, when you create a CircleBuilder and call the name() method, you are again expecting a CircleBuilder back and not a ShapeBuilder. Thankfully there is a generic implementation (partly under documented) which helps to solve problems of this nature. The modified code is given below&lt;/span&gt;
&lt;br /&gt;
&lt;pre class="brush: java"&gt;abstract class Shape {
    private String name;
    private Dimension dimension;

    public enum Dimension {
        TWO_D, THREE_D;
    }

    public static abstract class ShapeBuilder&amp;lt;S extends Shape, SB extends ShapeBuilder&amp;lt;S, SB&amp;gt;&amp;gt; {
        private String name;
        private Dimension dimension;

        @SuppressWarnings("unchecked")
        public SB name(String name) {
            this.name = name;
            return (SB) this;
        }
        @SuppressWarnings("unchecked")
        public SB dimension(Dimension dimension) {
            this.dimension = dimension;
            return (SB) this;
        }
        public T build() {
            T result = createInstance();
            result.name = this.name;
            result.dimension = this.dimension;
            return result;
        }
        abstract T createInstance();
    }
}
abstract class TwoDShape extends Shape {
    private double area;

    public static abstract class TwoDShapeBuilder&amp;lt;S extends TwoDShape, SB extends TwoDShapeBuilder&amp;lt;S, SB&amp;gt;&amp;gt;
            extends ShapeBuilder&amp;lt;T, SB&amp;gt; {
        private double area;

        @SuppressWarnings("unchecked")
        public SB area(double area) {
            this.area = area;
            return (SB) this;
        }
        public T build() {
            T result = (T) super.build();
            result.area = this.area;
            return result;
        }
    }
}
class Circle extends TwoDShape {
    private double radius;

    public static class CircleBuilder extends
            TwoDShapeBuilder&amp;lt;Circle, CircleBuilder&amp;gt; {
        private double radius;

        public CircleBuilder radius(double radius) {
            this.radius = radius;
            return this;
        }
        public Circle build() {
            Circle s = (Circle) super.build();
            s.radius = this.radius;
            return s;
        }
        @Override
        protected Circle createInstance() {
            return new Circle();
        }
    }
}&lt;/pre&gt;
&lt;span style="font-family: 'Lucida Grande'; font-size: 13px; line-height: 19px; white-space: pre-wrap;"&gt;The only thing ugly about this code is that the builders themselves have to be cast to the generic implementation because of the type erasure. However this would be solved by the new &lt;a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-February/000009.html"&gt;"Type Inference"&lt;/a&gt; language feature that will be introduced in Java 7. &lt;br /&gt;&amp;nbsp;&lt;/span&gt;&lt;br /&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/3821115221571460038-9208868222180776443?l=www.vshank77.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/vshank77/~4/0o-TlN11tCU" height="1" width="1"/&gt;</content><link rel="replies" type="application/atom+xml" href="http://www.vshank77.com/feeds/9208868222180776443/comments/default" title="Post Comments" /><link rel="replies" type="text/html" href="http://www.vshank77.com/2009/12/builder-pattern-abused.html#comment-form" title="1 Comments" /><link rel="edit" type="application/atom+xml" href="http://www.blogger.com/feeds/3821115221571460038/posts/default/9208868222180776443?v=2" /><link rel="self" type="application/atom+xml" href="http://www.blogger.com/feeds/3821115221571460038/posts/default/9208868222180776443?v=2" /><link rel="alternate" type="text/html" href="http://feedproxy.google.com/~r/vshank77/~3/0o-TlN11tCU/builder-pattern-abused.html" title="Builder Pattern Abused" /><author><name>Shankar Vasudevan</name><uri>http://www.blogger.com/profile/15139006072777819989</uri><email>noreply@blogger.com</email><gd:image rel="http://schemas.google.com/g/2005#thumbnail" width="16" height="16" src="http://img2.blogblog.com/img/b16-rounded.gif" /></author><thr:total>1</thr:total><feedburner:origLink>http://www.vshank77.com/2009/12/builder-pattern-abused.html</feedburner:origLink></entry></feed>

