<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>random  programmable thought bubbles on java javascript occasional css even php</title>
	<atom:link href="http://www.anzaan.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.anzaan.com</link>
	<description></description>
	<lastBuildDate>Mon, 16 Apr 2012 04:20:57 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Java Visitor Pattern and the Expression Problem &#8211; part 2 : Object Algebra Approach</title>
		<link>http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-2-object-algebra-approach/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-visitor-pattern-and-the-expression-problem-part-2-object-algebra-approach</link>
		<comments>http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-2-object-algebra-approach/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 12:53:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Visitor Pattern]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=234</guid>
		<description><![CDATA[In the previous post I presented a Visitor Pattern framework adaptation that solves the Expression Problem. But nice as it was it has its limitations and and drawbacks which I detailed at the end of the post. In this post I&#8217;ll explore a  Visitor pattern implementation with Object Algebras. The solution is actually quite straight-forward &#8230; <a href="http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-2-object-algebra-approach/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>In the previous post I presented a <span style="color: #993300;">Visitor Pattern</span> framework adaptation that solves the <strong><span style="color: #993300;">Expression Problem</span></strong>.<br />
But nice as it was it has its limitations and and drawbacks which I detailed at the end of the post.<br />
In this post I&#8217;ll explore a  Visitor pattern implementation with Object Algebras.</p>
<p>The solution is actually quite straight-forward adaptation of a solution presented in a paper called <a href="http://www.cs.utexas.edu/~wcook/Drafts/2012/ecoop2012.pdf" target="_blank"><em>Extensibility for the Masses: Practical Extensibility with Object Algebras</em></a>.<br />
The paper is interesting  without veering into highly academic discussion and provides some nice examples.<br />
I have added another layer of  abstraction to the visitor to provide a higher degree of reuse and extensibility. To achieve higher degree of reuse I have defined a  final Void class with one static method that returns a singleton<br />
instance of the Void class. This class is merely used by visitors that aren&#8217;t interested in returning values from their visit method, the methods  in those visitors simply return an instance of Void once the code block in the method body finishes executing.  Since every visitor returns something from its visit methods it provides us with a better means of abstraction.</p>
<p>The pattern implementation is simple and provides static type safety ensuring that no data class can be passed to visitors unless there is an implementation for it.</p>
<p>I&#8217;ll start off with a simple implementation that simply contains application code and doesn&#8217;t depend on any other classes except the application specific ones.<br />
The example is the same as the one in previous post with shapes data classes. This time the classes are pure pojo with no interface or abstract class. And the pattern doesn&#8217;t creep into the data classes as no <span style="color: #993300;">accept</span> methods are required.</p>
<p><strong><span style="color: #993300;">Circle</span></strong> class:</p>
<pre class="brush: java; title: ; notranslate">
public class Circle    {

private final double radius;

public Circle(double radius){
this.radius = radius;

}

/**
* @return the radius
*/
public double getRadius() {
return radius;
}

}
</pre>
<p><span style="color: #993300;"><strong>Rectangle</strong></span> class:</p>
<pre class="brush: java; title: ; notranslate">

public class Rectangle  {
private final double height;
private final double width;

public Rectangle(double height, double width){
this.height = height;
this.width = width;
}

/**
* @return the height
*/
public double getHeight() {
return height;
}

/**
* @return the width
*/
public double getWidth() {
return width;
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Next we&#8217;ll define an interface used for printing as the first example will use a visitor that simply prints the output to the console.<br />
Its only method <span style="color: #993300;">print</span> will be called to actually print to console.</p>
<p><span style="color: #993300;"><strong>IPrint</strong></span> Class:</p>
<pre class="brush: java; title: ; notranslate">

public interface Print {

public void print();
}
</pre>
<p><strong><span style="color: #993300;">IShapeVisitor</span></strong> interface:</p>
<pre class="brush: java; title: ; notranslate">
public interface IShapeVisitor&lt;T&gt; {

public T visit(Circle c);

public T visit (Rectangle r);
}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p><strong><span style="color: #993300;">PrintVisitor</span></strong> : Implementation of <span style="color: #993300;">IShapeVisitor</span> interfacewith methods that return anonymous <span style="color: #993300;">Print</span> implementation.<br />
The printing task is handled by the <span style="color: #993300;">Print</span> implelentation</p>
<pre class="brush: java; title: ; notranslate">
public class PrintVisitor implements IShapeVisitor&lt;Print&gt; {

@Override
public Print visit(Circle c) {
return new Print() {

@Override
public void print() {
System.out.println(&quot;Circle&quot;);
}
};
}

@Override
public Print visit(Rectangle r) {
return new Print() {

@Override
public void print() {
System.out.println(&quot;Rectangle&quot;);
}
};
}

}
 </pre>
<p><span style="color: #ffffff;">.</span></p>
<p>That&#8217;s all that required for the the visitor implementation. Its a clean implementation as its not pervasive and the data classes are blissfully unaware of Visitors and the implementations don&#8217;t require them to extend super classes or to implement interface.</p>
<pre class="brush: java; title: ; notranslate">

IShapeVisitor&lt;Print&gt; v= new PrintVisitor();

v.visit(new Circle(10)).print();//prints out Circle.
v.visit(new Rectangle(10, 10)).print();//prints out Rectangle
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p><strong><span style="color: #003366;"><span style="color: #0000ff;">Subclassing Test</span>:</span></strong><em>Data Extensibility test </em><br />
We now need to confirm that adding new data doesn&#8217;t require any source-level extension and can be handled without modifying the existing classes.</p>
<p><span style="color: #993300;"><strong>Triangle</strong></span> class:</p>
<pre class="brush: java; title: ; notranslate">

public class Triangle  {

private final double height;
private final double base;

public Triangle(double height, double base){
this.height = height;
this.base = base;
}

/**
* @return the height
*/
public double getHeight() {
return height;
}

/**
* @return the width
*/
public double getBase() {
return base;
}
}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Now we need to define an interface for handling the new Triangle class.</p>
<p><strong><span style="color: #993300;">ITriangleExtendedVisitor</span></strong> interface:</p>
<pre class="brush: java; title: ; notranslate">

public interface ITriangleExtendedVisitor&lt;T&gt;  extends IShapeVisitor&lt;T&gt;{

public T visit(Triangle t);

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p><strong><span style="color: #993300;">TriangleExtendedPrintVisitor</span></strong> class: trivial implementation of <span style="color: #993300;">ITriangleExtendedVisitor</span>.</p>
<pre class="brush: java; title: ; notranslate">

public class TriangleExtendedPrintVisitor  extends PrintVisitor implements ITriangleExtendedVisitor&lt;Print&gt; {

@Override
public Print visit(Triangle t) {
return new Print() {

@Override
public void print() {
System.out.println(&quot;Triangle&quot;);
}
};
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Test code:</p>
<pre class="brush: java; title: ; notranslate">

ITriangleExtendedVisitor pv = new TriangleExtendedPrintVisitor();

pv.visit(new Circle(10)).print();//prints Circle
pv.visit(new Rectangle(10, 10)).print();//prints Rectangle
pv.visit(new Triangle(10, 10)).print();//prints Triangle
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>With that test passing, we can safely say that the visitor approach promises us data extensibility without the need to make source code changes.</p>
<p><span style="color: #0000ff;"><strong>Operation Extensibility test</strong>:<em></em></span><br />
To test the other side of the coin, we&#8217;ll implement a visitor to calculate area of the shapes.<br />
Before we define the visitor we need to define an interface similar to Print that with a method that returns a double value this instead of void.<br />
The calculation will be performed in its method body and the calling code need to call the method to obtain the area value.</p>
<p><strong><span style="color: #993300;">AreaCalculator</span></strong> interface:</p>
<pre class="brush: java; title: ; notranslate">

public interface AreaCaclulator {

public double calculate();
}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>With that interface defined we have got all the necessary ingredients to whip up a <span style="color: #993300;">AreaVisitor</span>.<br />
I have directly defined a concrete class rather than using an interface to keep things small.</p>
<p><strong><span style="color: #993300;">AreaVisitor</span></strong> class:</p>
<pre class="brush: java; title: ; notranslate">

public class AreaVisitor implements ITriangleExtendedVisitor&lt;AreaCaclulator&gt; {

@Override
public AreaCaclulator visit(final Triangle t) {
return new AreaCaclulator() {

@Override
public double calculate() {
return t.getBase()*t.getHeight()/2;
}
};
}

@Override
public AreaCaclulator visit(final Circle c) {
return new AreaCaclulator() {

@Override
public double calculate() {
return Math.PI * (Math.pow(c.getRadius(), 2.0));
}
};
}

@Override
public AreaCaclulator visit(final Rectangle r) {
return new AreaCaclulator() {

@Override
public double calculate() {
return r.getHeight()*r.getWidth();
}
};
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>As with the <span style="color: #993300;">PrintVisitor</span> the visit method returns an anonymous class with one method and this time its a value returning methods which gives us the area of the Shapes we are interested in.</p>
<p>Unit Test:</p>
<pre class="brush: java; title: ; notranslate">

AreaVisitor av = new AreaVisitor();

assertEquals(78.5, av.visit(new Circle(5)).calculate(),0.1);
assertEquals(100, av.visit(new Rectangle(10, 10)).calculate(),0.001);
assertEquals(50, av.visit(new Triangle(10, 10)).calculate(),0.001);
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>With that test passing we can be assured that the visitor pattern implementation with Object Algebras solves the expression problem and gives us an implementation allowing data and operation extensibility<br />
without requiring any change in the source code. As with the previous example suing Visitor framework it provides object-level extensibility as old object will continue to work if the new implementations are added to a running system.</p>
<p>But, that doesn&#8217;t necessarily mean that the implementation we have is the cleanest one robust enough to handle various types of visitors. We have had to define two separate interfaces for handling the actual<br />
printing and for actual area calculation. Which means that every-time we add a new visitor chances are we&#8217;ll have to add a new interface along with Visitor implementation.</p>
<p>The problem with Visitors is that a visitor may be either required to return an interface that provides computes and returns a value or it might just perform some side-effect and have no return value.<br />
We cannot define a single interface to cater for both requirements as with one the method in the interface implementation will have a return value, where as the one performing side-effect will<br />
have a <span style="color: #993300;"><strong>void</strong></span> method signature.<br />
The only way we can abstract away both the requirements is by modelling the <span style="color: #993300;">void</span> as a data type that has no property and no operation. So any method that isn&#8217;t interesting in returning value will simple return a<br />
singleton instance of a Void data type.Its essentially a Java equivalent functional programming&#8217;s Unit type. We aren&#8217;t using the Void class provided by JVM because it cannot be instantiated and programmers will always<br />
have to remember to pass in <span style="color: #993300;">null</span>.</p>
<p><strong><span style="color: #993300;">Void</span></strong> class:</p>
<pre class="brush: java; title: ; notranslate">

public final class Void {

private static final Void instance= new Void();

private Void(){}

public static Void Void(){
 return instance;
 }

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>We can now define a generic value returning interface that can be used by all visitor without each visitor having to define one -which is essentially poor-man&#8217;s higher order function.</p>
<p><span style="color: #993300;"><strong>IValue</strong></span> interface: It has one method <span style="color: #993300;">get</span> that returns computes and returns value which is a parametrized type.</p>
<pre class="brush: java; title: ; notranslate">

public interface IValue&lt;T&gt; {

public T get();

}
</pre>
<p>We&#8217;ll use the <span style="color: #993300;">IValue</span> interface as return type of all visit methods in our visitor interface definition.</p>
<p><span style="color: #993300;"><strong>IShapeVisitor</strong></span> interface:</p>
<pre class="brush: java; title: ; notranslate">

public interface IShapeVisitor&lt;T&gt; {

public IValue&lt;T&gt; visit(final Circle c);

public IValue&lt;T&gt; visit (final Rectangle r);
}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>We&#8217;ll again start off with a visitor that prints the name of a shape data object to console.<br />
We can actually make the visitor return a value and print that value to console outside of the implementation, but we won&#8217;t do that just to make it as a test case for<br />
operations that don&#8217;t return a value- e.g database write, file write, logging.</p>
<pre class="brush: java; title: ; notranslate">

import static object.algebra.strategy.Void.*;

public class PrintVisitor implements IShapeVisitor&lt;Void&gt; {

@Override
public IValue&lt;Void&gt; visit(final Circle c) {
return new IValue&lt;Void&gt;() {

@Override
public Void get() {
System.out.println(&quot;Circle&quot;);
return Void();
}
};
}

@Override
public IValue&lt;Void&gt; visit(final Rectangle r) {

return new IValue&lt;Void&gt;() {

@Override
public Void get() {
System.out.println(&quot;Rectangle&quot;);
return Void();
}
};
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>I have used static import on Void class to use its static <span style="color: #993300;">Void</span> method that return a singleton instance of <span style="color: #993300;">Void</span> class.Although it looks like a constructor call without <span style="color: #993300;">new</span> keyword, that&#8217;s not the case<br />
and since lowercase <span style="color: #993300;">void</span> is a keyword in Java I can&#8217;t define a <span style="color: #993300;">void</span> method so have to resort to <span style="color: #993300;">Void</span> instead.</p>
<p><strong><span style="color: #0000ff;">Subclassing Test</span>:</strong><em>Data Extensibility test </em></p>
<p><span style="color: #993300;"><strong>Triangle</strong></span> print visitor interface and implementation:</p>
<pre class="brush: java; title: ; notranslate">

public interface ITriangleExtendedVisitor&lt;T&gt;  extends IShapeVisitor&lt;T&gt;{

public IValue&lt;T&gt; visit(Triangle t);

}

public class TriangleExtendedPrintVisitor  extends PrintVisitor implements ITriangleExtendedVisitor&lt;Void&gt; {

@Override
public IValue&lt;Void&gt; visit(Triangle t) {
return new IValue&lt;Void&gt;() {

@Override
public Void get() {
System.out.println(&quot;Triangle&quot;);
return Void();
}
};
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>In the Visitor framework in the previous post the framework failed to dispatch to the right visitor if a data class was sub-classed, the visit method for its super-class was always called instead.<br />
Overcoming that might be possible but I didn&#8217;t dig into it because the framework was going to get over-complicated when accommodating such behavior. But with this implementation there&#8217;s no such problem<br />
because visitor methods are statically type checked and the correct method is executed no matter what hierarchy of sub classing for data class is.<br />
To demonstrate we&#8217;ll add a Square class to the mix and provide a visitor extension for it.</p>
<pre class="brush: java; title: ; notranslate">

public class Square extends Rectangle{

public Square(double side){
super(side, side);
}
}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Visitor interface extension and implementation for Square sub class.</p>
<pre class="brush: java; title: ; notranslate">

public interface ISquareExtendedVisitor&lt;T&gt;  extends ITriangleExtendedVisitor&lt;T&gt; {

public IValue&lt;T&gt; visit(final Square t);

}

&amp;nbsp;

public class SquareExtendedPrintVisitor  extends TriangleExtendedPrintVisitor implements ISquareExtendedVisitor&lt;Void&gt; {

@Override
public IValue&lt;Void&gt; visit(final Square t) {
return new IValue&lt;Void&gt;() {

@Override
public Void get() {
System.out.println(&quot;Square&quot;);
return Void();
}
};
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Litmus test:</p>
<pre class="brush: java; title: ; notranslate">

ISquareExtendedVisitor&lt;Void&gt;  pv = new SquareExtendedPrintVisitor  ();

pv.visit(circle).get();//prints circle
pv.visit(rectangle).get();//prints  Rectangle
pv.visit(triangle).get();//prints Triangle
pv.visit(square).get();//prints Square
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>The Visitor correctly dispatches the method for printing Square.</p>
<p>That provides the proof that the implementation has no problem with data extensibility and goes half-way toward solving the expression problem.</p>
<pre></pre>
<p><strong><span style="color: #0000ff;">Operation Extensibility test:</span></strong><br />
We again add Area calculating visitor implementation.<br />
<em></em></p>
<pre class="brush: java; title: ; notranslate">
public class AreaVisitor implements ISquareExtendedVisitor&lt;Double&gt; {

@Override
public IValue&lt;Double&gt; visit(final Triangle t) {
return new IValue&lt;Double&gt;() {

@Override
public Double get() {
return t.getBase()*t.getHeight()/2;
}
};
}

@Override
public IValue&lt;Double&gt; visit(final Circle c) {
return new IValue&lt;Double&gt;() {

@Override
public Double get() {
return Math.PI * (Math.pow(c.getRadius(), 2.0));
}
};
}

@Override
public IValue&lt;Double&gt; visit(final Rectangle r) {
return new IValue&lt;Double&gt;() {

@Override
public Double get() {
return r.getHeight()*r.getWidth();
}
};
}

@Override
public IValue&lt;Double&gt; visit(final Square s) {
return new IValue&lt;Double&gt;() {

@Override
public Double get() {
return s.getHeight()*s.getWidth();
}
};
}

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Test for operation extensibility:</p>
<pre class="brush: java; title: ; notranslate">

AreaVisitor av = new AreaVisitor();

assertEquals(78.5, av.visit(new Circle(5)).get(), 0.1);
assertEquals(100, av.visit(new Rectangle(10, 10)).get(), 0.001);
assertEquals(50, av.visit(new Triangle(10, 10)).get(), 0.001);
assertEquals(25, av.visit(new Square(5)).get(), 0.001);
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>The passing of the test proves that visitor pattern implementation with Object Algebras provides the flexibility for data as well as operation extension and doesn&#8217;t depend on any framework or tool</p>
<p>for it to work properly.  It also provides perhaps the cleanest and most straight-forward implementation for tackling the &#8216;<span style="color: #993300;">Expression Problem</span>&#8216; and <span style="color: #993300;">data-centric</span> vs <span style="color: #993300;">operation-centric</span> duality.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-2-object-algebra-approach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Visitor Pattern and the Expression Problem &#8211; part 1 : Framework Based Approach</title>
		<link>http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-1-framework-based-approach/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-visitor-pattern-and-the-expression-problem-part-1-framework-based-approach</link>
		<comments>http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-1-framework-based-approach/#comments</comments>
		<pubDate>Tue, 10 Apr 2012 08:59:10 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Design Pattern]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[Visitor Pattern]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=207</guid>
		<description><![CDATA[Visitor pattern provides a flexible mechanism for adding operations to a set of classes. Its much better option than having to retrofit existing interface and its implementations with operations as needs arise. Retrofitting has bigger consequence if the interface api is used by 3rd party clients as their code will no longer compile after upgrade &#8230; <a href="http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-1-framework-based-approach/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Visitor pattern provides a flexible mechanism for adding operations to a set of classes. Its much better option than having to retrofit existing interface and its implementations with operations as needs arise. Retrofitting has bigger consequence if the interface api is used by 3rd party clients as their code will no longer compile after upgrade due to missing implementation for the added operation in the interface.<br />
But Visitor pattern has its own extensibility issue. If a new subclass is added then the Visitor interfaces have to be changed to add operation for the new subclass and the implementations have to be changed to accommodates the newly added class.</p>
<p>There has been quite a lot of attempts to solve this dilemma of date-centric and operation-centric approach in various languages.<br />
The solutions try to address source-level extensibility, code-level extensibility and object-level extensibility.<br />
The most promising of those solutions I came across came in two flavors.</p>
<p>In this post I will explore the solution presented <a href="http://www.daimi.au.dk/~madst/ecoop04/main.pdf ">Mads Torgersen</a> using a visitor framework to dispatch to correct methods on visitors and provided a default handler method to handle subclasses which hasn&#8217;t been addressd in a visitor implementation. The solution is robust and supports both data and operation extensions without having to tinker with existing code and goes a long way towards solving the expression problem.<br />
The solution allows all three levels of extensibility.</p>
<p>The original solution had rather unnecessary boiler-plate and framework itself was unnecessarily creeping in the implementation classes. I have pushed all methods on Visitable classes to the framework except for the accept method and I have also pushed all framework specific methods on visitor classes to the framework so that it only needs overloaded visit methods.<br />
More generics has been added to the original framework for type safety and extensibility.<br />
Since the framework relies on type discovery of visitor and visited classes and due to runtime type erasure of classes in Java, I had to pinch the code written by Ian Robertson that uses reflection to find the generic type parameter class. The type discovery method is the only dependency required by the framework. Visit <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=208860">here </a> for the article and code.</p>
<p>The framework consist of Visitor and Visitable interface and their abstract implementation that does all the heavy lifting.</p>
<p><span style="color: #993300;"><strong>Visitor </strong></span>Interface:</p>
<pre class="brush: java; title: ; notranslate">

public interface Visitor {

     /**
     * The primary method used to route Visitables to their respective
     * methods in visitor implementation using double dispatch
     * via Visitable's handle method.
      * @param e data object
     */
      public void apply(Visitable e);

     /**
     * default handler where no suitable method for dispatching exist for a Visitable     *
     * @param e data object
     */
      public void handleDefault(Visitable e);
}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong>Visitable</strong></span> interface. The interface implemented by data classes through Abstract class.</p>
<pre class="brush: java; title: ; notranslate">

public interface Visitable {

    /**
     * The primary method used to route Visitables to their respective
     * methods in visitor implementation using double dispatch
     * via Visitable's handle method.
      * @param e data object
     */
    public  void handle(V v);
}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong>AbstractVisitor </strong></span>class: Abstract class used to delegate Visitables to the correct method using triple-dispatch.</p>
<pre class="brush: java; title: ; notranslate">
public abstract class AbstractVisitor implements Visitor {

    /**
     *  {@inheritDoc }
    */
    @Override
    public final  void apply(Visitable e) {
            e.handle(this);
    }

    /**
     *  {@inheritDoc }
    */
    @Override
    public final void handleDefault(Visitable e) {
        throw new UnsupportedOperationException(&quot;No Suitable method to handle Visitable[&quot; + e.getClass().getSimpleName() + &quot;].  &quot;);
    }
}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong> AbstractVisitable </strong></span>class: This class does the heavy lifting with some help from reflection. Reflection is used for type discovery of Visitor implementations.<br />
If a Visitor is deemed to have a suitable method then its passed to the accept method of concrete implementation which knows which method on a visitor to<br />
call.<br />
<strong>ClassUtil</strong>&#8216;s <strong>getTypeArguments </strong>method is used for runtime generic type discovery of<strong> V</strong> parameter that extends <strong>Visitor</strong>.<br />
Copy getTypeArguments and getClass method from the site and stick it to a Util class or you can put it in the AbstractVisitor class for simplicity.</p>
<pre class="brush: java; title: ; notranslate">

public abstract class AbstractVisitable implements Visitable {

    private final Class clazz;

    public AbstractVisitable() {
        clazz = (Class) ClassUtil.getTypeArguments(AbstractVisitable.class, getClass()).get(0);
    }

    /**
     * method to check if the visitor passed in is the required type.
     *
     * @param v
     * @return
     */
    private boolean canAccept(Visitor v) {
        return clazz.isAssignableFrom(v.getClass());

    }

    /**
     * {@inheritDoc }
     */
    public final void handle(Visitor v) {
        if (canAccept(v)) {
            accept(clazz.cast(v));
        } else {
            v.handleDefault(this);
        }
    }

    /**
     * Methods concrete Visitable class need to implement. This is where the
     * actual dispatch to the correct Visitor method need to be done. The
     * implementation is just a boiler-plate and should contain v.visit(this)
     * call;
     *
     * @param v
     */
    public abstract void accept(V v);
}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>Those four classes are what drives the Visitor framework and what makes it work.</p>
<p>I will use some trivial Shape classes to test the framework and validate it. I&#8217;ll initially start off with just two Shapes-Rectangle and Circle.<br />
I&#8217;ll use a visitor that simply prints the type of the shape to the console.</p>
<p><span style="color: #993300;"><strong>Shape</strong></span>: A marker interface to group all the shapes under.</p>
<pre class="brush: java; title: ; notranslate">

public interface Shape  extends Visitable{

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong>Circle </strong></span>Class:</p>
<pre class="brush: java; title: ; notranslate">

public class Circle  extends AbstractVisitable implements Shape  {

    private final double radius;

    public Circle(double radius){
        this.radius = radius;
    }

    /**
     * @return the radius
     */
    public double getRadius() {
        return radius;
    }

       @Override
    public void accept(ShapeVisitor v) {
        v.visit(this);
    }

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong>Rectangle </strong></span>Class:</p>
<pre class="brush: java; title: ; notranslate">

public class Rectangle  extends AbstractVisitable implements Shape {

    private final double height;
    private final double width;

    public Rectangle(double height, double width){
        this.height = height;
        this.width = width;
    }

    /**
     * @return the height
     */
    public double getHeight() {
        return height;
    }

    /**
     * @return the width
     */
    public double getWidth() {
        return width;
    }

        @Override
    public void accept(ShapeVisitor v) {
        v.visit(this);
    }

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong>ShapeVisitor</strong></span>: The interface with visit methods specific to Circle and Rectangle objects.</p>
<pre class="brush: java; title: ; notranslate">

public interface  ShapeVisitor extends Visitor  {

    public  void visit(Rectangle rectangle) ;

    public  void visit(Circle circle) ;

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #993300;"><strong>PrintVisitor</strong></span>: Visitor that simply prints the name of Visitable object Class to the console</p>
<pre class="brush: java; title: ; notranslate">

public class PrintVisitor extends AbstractVisitor implements ShapeVisitor {

    @Override
    public void visit(Rectangle rectangle) {
        System.out.println(&quot;Rectangle&quot;);
    }

    @Override
    public void visit(Circle circle) {
        System.out.println(&quot;Circle&quot;);
    }

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Here&#8217;s some sample test code.</p>
<pre class="brush: java; title: ; notranslate">

       ShapeVisitor v= new PrintVisitor();
       Shape c= new Circle(5);
       v.apply(c);// prints Circle

       Shape r= new Rectangle(5, 5);
       v.apply(r); //prints Rectangle
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Now that the basic framework has been tested out, its time to test its extensibility.</p>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #0000ff;"><strong>Subclassing Test</strong></span>: <em>Data Extensibility test </em><br />
Ability to add Data Class without the need to change source code while maintaining object level extensibility.</p>
<p>We&#8217;ll add a Triangle class to the mix first.</p>
<pre class="brush: java; title: ; notranslate">

public class Triangle  extends AbstractVisitable implements Shape {
    private final double height;
    private final double base;

    public Triangle(double height, double base){
        this.height = height;
        this.base = base;
    }

    /**
     * @return the height
     */
    public double getHeight() {
        return height;
    }

    /**
     * @return the width
     */
    public double getBase() {
        return base;
    }

    @Override
    public void accept(ITriangleExtendedVisitor v) {
        v.visit(this);

    }

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>Adding data class requires a Visitor implementation to be created to handle the new data class. Otherwise there&#8217;s no point in adding a new data class.<br />
The ITriangleExtendedVisitor interface used in the accept method needs to be defined.</p>
<pre class="brush: java; title: ; notranslate">

public interface ITriangleExtendedVisitor extends ShapeVisitor {

    public void visit(Triangle t);

}
</pre>
<div class="divider top-shortcode"><a href="#">Top</a></div>
<p>Now let&#8217;s test it :</p>
<pre class="brush: java; title: ; notranslate">

 ShapeVisitor v= new PrintVisitor();

 Shape t = new Triangle(12, 11);
       v.apply(t); // throws java.lang.UnsupportedOperationException: No Suitable method to handle Visitable[Triangle].
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>The test failed because PrintVisitor class used doesn&#8217;t have a suitable method to handle Triangle class.<br />
Let&#8217;s implement a Visitor to provide handling for Triangle class.</p>
<pre class="brush: java; title: ; notranslate">

public class TriangleExtendedPrintVisitor extends PrintVisitor implements ITriangleExtendedVisitor{

    @Override
    public void visit(Triangle t) {
        System.out.println(&quot; Triangle&quot;);
    }

}
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Its very important to keep track of the latest implementation of Visitor and to ensure that the new Visitor class extends the latest implementation.<br />
In our case we only have one PrintVisitor class as yet and as such we can extend that to create the new visitor to handle Triangle class.</p>
<p>Testing time:</p>
<pre class="brush: java; title: ; notranslate">
 ShapeVisitor v= new TrianglePrintVisitor();

       Shape t = new Triangle(12, 11);
       v.apply(t);// prints Triangle

Shape c= new Circle(5);
       v.apply(c);//prints Circle
</pre>
<p><span style="color: #ffffff;">.</span></p>
<p>Data Extensibility test has passed with flying color- at least so it seems for now.</p>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p><span style="color: #0000ff;"><strong>Operation Extensibility test</strong>:</span><em><br />
</em>Ability to add new operation to data without the need to change source code.</p>
<p>To test operation extensibility I&#8217;ll add a trivial Visitor to calculate area of Shape. This visitor differs from PrintVisitor in that<br />
it needs to keep a state of the calculated area. Although this can be rectified by making the accept method in Visitable as well<br />
as visit method in Visitor return a value, but that creates an issue for visitors that doesn&#8217;t require to return a value like the PrintVisitor.<br />
A Void marker class can be defined to use when the return value is of no interest, but we&#8217;ll keep it simple and use state in Visitor for now.</p>
<p><span style="color: #993300;">IAreaVisitor</span> interface makes use of the existing definition of <span style="color: #993300;">ITriangleExtendedPrintVisitor</span></p>
<pre class="brush: java; title: ; notranslate">

public interface IAreaVisitor extends ITriangleExtendedPrintVisitor{

    Double getResult();

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>The concrete implementation</p>
<pre class="brush: java; title: ; notranslate">

public class AreaVisitor extends AbstractVisitor implements IAreaVisitor {

    double result=0.0;

      public void visit(Rectangle rectangle) {
         result= rectangle.getHeight() * rectangle.getWidth();
    }

    public void visit(Circle circle) {
         result= Math.PI * (Math.pow(circle.getRadius(), 2.0));
    }

    @Override
    public void visit(Triangle t) {
         result=t.getBase()*t.getHeight()/2;
    }

     @Override
    public Double getResult() {
        return result;
    }
}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>Testing time again:</p>
<pre class="brush: java; title: ; notranslate">

IAreaVisitor v= new AreaVisitor();

       Shape c= new Circle(5);
       v.apply(c);
       assertEquals(78.5, v.getResult(),0.1);

       Shape r= new Rectangle(5, 5);
       v.apply(r);
       assertEquals(25, v.getResult(),0.1);

       Shape t = new Triangle(10, 10);
       v.apply(t);
        assertEquals(50, v.getResult(),0.1);
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>Operation extension poses no problem as that&#8217;s the real strength of Visitor pattern.<br />
With both operation and data extensibility this framework is a good solution to the expression problem.</p>
<p>The drawback of this solution is the lack of static type checking on data classes which means that a visitable object which doesn&#8217;t yet have implementation for it in a visitor can be passed in causing it to raise runtime exception. It also requires programmers to be disciplined when extending visitors to ensure that the latest version of a visitor is extended.<br />
If another Shape is to be added and a visitor interface needs to be defined to extend ITriangleExtendedVisitor. IF by mistake ShapeVisitor interface is extended, the implementation will not be able to handle Triangle as ShapeVisitor was created when Triangle wasn&#8217;t in the scope and as such has no method for handling Triangle.</p>
<p>Another issue is that if you subclass a data class that has already got operation defined in a visitor, and extend the visitor to provide implementation for the new subclass, the framework fails to dispatch the subclass to the correct visitor method.</p>
<p>If we define a Square that extends Rectangle, and pass the Square to a Visitor that has method to handle Square, it will be dispatched to the method implemented to handle Rectangle.</p>
<pre class="brush: java; title: ; notranslate">
public class Square  extends Rectangle {

    public Square(double side){
        super(side,side);
    }

}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span></p>
<p>If we have an interface <span style="color: #993300;">ISquareExtendedVisitor</span> with the required method definition and create <span style="color: #993300;">SquareExtendedPrintVisitor</span> concrete class and use, the framework won&#8217;t dispatch to the<br />
visit(Square s) method in the Visitor implementation.</p>
<p>The reason for this is because the accept method in Rectangle has <span style="color: #993300;">ShapeVisitor</span> as parameter and not <span style="color: #993300;">ISquareExtendedVisitor</span> and <span style="color: #993300;">ShapeVisitor</span> was created when Square wasn&#8217;t in scope and as such has no implementation for handling Square.</p>
<p>We can use Generics to overcome this issue but there&#8217;s a price to pay.<br />
Suppose we changed all the Shape classes to accept a type parameter</p>
<p>Here&#8217;s an example implementation of rectangle and the Square using type parameter</p>
<pre class="brush: java; title: ; notranslate">
public class Rectangle&lt;T extends ShapeVisitor&gt;  extends AbstractVisitable&lt;T&gt; implements Shape  {

..............

     @Override
    public void accept(T  v) {
        v.visit(this);
    }

}

public class Square  extends Rectangle {
........
}
</pre>
<p><span style="color: #ffffff;">.</span><br />
<span style="color: #ffffff;">.</span><br />
The above change will ensure that the correct implementation to handle Square will be used. But the problem is the framework will no longer work.<br />
The current utility method for generic type discovery fails to discover the type parameter of AbstractVisitable extension in Rectangle class. Runtime Generic Type parameter information is only available for anonymous or Abstract class and not for concrete class. There might be a way to dig it out using <a href="http://code.google.com/p/gentyref/" target="_blank">gentyref </a>library for runtime Generic information using reflection ,but I haven&#8217;t tried it. And besides as soon as you have to include a whole library for a simple Visitor framework to work, then it might be time to find another solution.<br />
Which is where the second solution comes in.<br />
The second solution is covered in my next<a href="http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-2-object-algebra-approach/"> post</a>.</p>
<div class="divider top-shortcode"><a href="#">Top</a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2012/04/java-visitor-pattern-and-the-expression-problem-part-1-framework-based-approach/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java Iterable Circular Queue</title>
		<link>http://www.anzaan.com/2012/02/java-iterable-circular-queue/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-iterable-circular-queue</link>
		<comments>http://www.anzaan.com/2012/02/java-iterable-circular-queue/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 05:53:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Data Structure]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=197</guid>
		<description><![CDATA[  <a href="http://www.anzaan.com/2012/02/java-iterable-circular-queue/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Most of circular Queue implementations I have found keep track of the head and tail of queue. Adding and removing items are done using head and tail pointers.<br />
I decided to implement a circular queue my using modulo operation to figure head and tail instead of defining head and tail pointer variables.<br />
The queue class also implements <strong>Iterable </strong>so that the usual &#8216;for&#8217; comprehension can be used to iterate through the queue.</p>
<p>The queue is backed by <strong>ArrayList </strong>and as such its not thread-safe.</p>
<p>Although in reality queue class should only expose enqueue(),dequeue(),size() and isEmpty() methods to keep the API clean , I implementation has extra methods to provide<br />
 list operations.<br />
 Although allowing index based access may not really be that useful since item indexes will be rotated when items overwrite existing items, I couldn&#8217;t help but over-engineer the queue <img src='http://www.anzaan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>here&#8217;s the  <strong>iterable circular queue</strong> implementation:</p>
<pre class="brush: java; title: ; notranslate">

public class IterableCircularQueue&lt;T&gt; implements Iterable&lt;T&gt; {

    private final int capacity;
    private List&lt;T&gt; list;
    private int count = 0;

    public IterableCircularQueue(int capacity) {
        this.capacity = capacity;
        list = new ArrayList&lt;T&gt;(capacity);

    }

    /**
     * add item to queue
     * @param elem
     */
    public void enqueue(T elem) {

        if (count &lt; capacity) {
            list.add(elem);
        } else {
            if (list.size() == capacity) {
                list.set(count % capacity, elem);
            } else {
                list.add(count % capacity, elem);
            }
        }
        count++;

    }

    /**
     * Inspect the first item of the queue.
     * @return
     */
    public T peek() {

        if (list.isEmpty()) {
            throw new RuntimeException(&quot; queue is empty&quot;);
        }
        T value = null;
        if (count &gt; capacity) {
            int head = count % capacity;
            if (head &gt;= list.size()) {
                head = head - list.size();
            }
            value = list.get(head);
        } else {
            value = list.get(0);
        }

        return value;
    }

    /**
     * remove an item from the queue
     * @return
     */
    public T dequeue() {

        if (list.isEmpty()) {
           throw new RuntimeException(&quot; queue is empty&quot;);
        }
        T value = null;
        if (count &gt; capacity) {
            int head = count % capacity;
            if (head &gt;= list.size()) {
                head = head - list.size();
            }
            value = list.remove(head);
        } else {
            value = list.remove(0);
        }
        if (list.isEmpty()) {
            count = 0;
        }

        return value;
    }

    /**
     * index-based access to items in queue.
     * @note The item won't be removed when accessed using index
     * @param index
     * @return
     */
    public T get(int index) {

        if (index &lt; 0 || index &gt;= list.size()) {
            throw new IndexOutOfBoundsException();
        }

        int i = index;

        if (count &gt; capacity) {
            i = count % capacity + index;
            if (i &gt;= list.size()) {
                i = i - list.size();
            }
        }
        return list.get(i);
    }

    /**
     * number of items in queue
     * @return
     */
    public int size() {
        return list.size();
    }

    /**
     * check if the queue is empty
     * @return
     */
    public boolean isEmpty() {
        return list.isEmpty();
    }

    public String toString() {
        return list.toString();
    }

    /**
     * Fetch an Iterator to iterate through the queue.
     * @return
     */
    public Iterator&lt;T&gt; iterator() {
        return new QueueIterator();
    }

    /**
     * Queue Iterator implementation
     */
    private class QueueIterator implements Iterator&lt;T&gt; {

        int cursor = 0;

        public boolean hasNext() {

            if (cursor &gt;= capacity) {
                return false;
            }

            try {
                return get(cursor) != null;
            } catch (Exception e) {
                return false;
            }
        }

        public T next() {
            T val = get(cursor);
            cursor++;
            return val;
        }

        public void remove() {
            throw new UnsupportedOperationException(&quot;Not supported yet.&quot;);
        }
    }
}
</pre>
<p><strong>Test cases:</strong></p>
<pre class="brush: java; title: ; notranslate">

 IterableCircularQueue&lt;Integer&gt; q = new IterableCircularQueue(5);

        q.enqueue(0);
        q.enqueue(1);
        q.enqueue(2);
        q.enqueue(3);
        q.enqueue(4);

        assertEquals(new Integer(4), q.get(4));

        q.enqueue(5);// first item gets over-written

        assertEquals(new Integer(5), q.get(4));
         assertEquals(new Integer(1), q.dequeue());

        q.enqueue(6);
        q.enqueue(7);

        assertEquals(new Integer(3), q.dequeue());

        assertEquals(new Integer(5), q.get(1));
        assertEquals(new Integer(6), q.get(2));

        q.enqueue(8);
        q.enqueue(9);

        assertEquals(new Integer(6), q.get(1));
        assertEquals(new Integer(5), q.dequeue());
        assertEquals(new Integer(7), q.get(1));
        assertEquals(new Integer(6), q.dequeue());
        assertEquals(new Integer(8), q.get(1));

         assertEquals(new Integer(7), q.peek());

        assertEquals(new Integer(7), q.dequeue());
        assertEquals(new Integer(8), q.dequeue());
        assertEquals(new Integer(9), q.dequeue());

        assertTrue( q.isEmpty());

        q.enqueue(10);
        q.enqueue(11);
        q.enqueue(12);
        q.enqueue(13);

        assertEquals(new Integer(10), q.get(0));

        q.enqueue(14);
        q.enqueue(15);
        q.enqueue(16);
        q.enqueue(17);

        assertEquals(new Integer(13), q.get(0));
        assertEquals(new Integer(13), q.peek());
        assertEquals(new Integer(13), q.dequeue());
        assertEquals(new Integer(14), q.get(0));

        System.out.println(q);//prints [15,16,17,14]

        for (Integer i : q) {
            System.out.println(i + &quot; &quot;); //prints 14 15 16 17
        }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2012/02/java-iterable-circular-queue/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Automatic Unit Testing Test Packages recursively in JUnit</title>
		<link>http://www.anzaan.com/2012/01/automatic-unit-testing-test-packages-recursively-in-junit/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=automatic-unit-testing-test-packages-recursively-in-junit</link>
		<comments>http://www.anzaan.com/2012/01/automatic-unit-testing-test-packages-recursively-in-junit/#comments</comments>
		<pubDate>Wed, 18 Jan 2012 02:49:05 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[JUnit]]></category>
		<category><![CDATA[Java JUnit Test]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=189</guid>
		<description><![CDATA[One of the issues when I write unit test is having to create TestSuite after TestSuite at package level to run all the test in a package or run all tests in a project. And I really dislike the repetitiveness of it. And sometimes I just like to test all classes in a package and &#8230; <a href="http://www.anzaan.com/2012/01/automatic-unit-testing-test-packages-recursively-in-junit/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the issues when I write unit test is having to create TestSuite after TestSuite at package level to run all the test in a package or run all tests in a project. And I really dislike the repetitiveness of it.<br />
And sometimes I just like to test all classes in a package and its sub packages rather than running all the tests in a project due to the amount of time it takes to setup all the necessary resources.<br />
Finally I decided to do something about it and started digging into JUnit to figure out a way to automate testing classes in a package without having to add  test classes to a TestSuite.<br />
The initial version of Suite I developed added all classes from the package a class was marked with RunWith annotation as well as all classes from sub-packages recursively.<br />
It was all great. I could just mark a class with <strong>@RunWith(DynamicSuite.class)</strong> annotation at the root of a project&#8217;s root package and it would<br />
run all the tests for the project. Or I could mark a class in a package with<strong> @RunWith(DynamicSuite.class)</strong> annotation and I could test just the classes in the package and its sub-packages.All sweet.<br />
But later in some cases I only wanted to run classes in a package and not all classes in its sub-packages as well due to the speed of test as some tests in sub-packages were resource intensive. So I had to come up with a finer-grained test Suite mechanism.</p>
<p>To tackle that issue, I decided to add an Annotation -<strong>@NonRecursive</strong> &#8211; that marked a Test entry point ( class marked with  <strong>@RunWith(DynamicSuite.class)</strong> annotation as being non-recursive.<br />
I wanted to be able to test just a package when I wanted to without testing sub-packages, but I also wanted a over-riding mechanism to be able to run all tests in a project or a package and its sub-package such that if the entry point class is not marked as <strong>@NonRecursive</strong> , all the <strong>@NonRecursive</strong> annotaitons get ignored in subsequent sub-packages and all classes in the package and below get executed.</p>
<p>Here&#8217;s the DynamicSuite Class code.</p>
<pre class="brush: java; title: ; notranslate">
/**
 *TestSuite execute all test classes from the package of  &lt;br&gt;
 * classes that are annotated to run with this class&lt;br&gt;
 * It loads all classes in the same package as the setup class and
 * loads classes from sub packages recursively.
 * If a sub-package contains a class that's marked to be run with this class&lt;br&gt;
 * it only loads that class so that the marked class can in turn load and execute&lt;br&gt;
 * test classes in its package and its subpackages.&lt;br&gt;&lt;br&gt;
 * To cut it short: This class loads and executes all test classes in its package and its
 * subpackages recursively.&lt;br&lt;br&gt;
 * Example usage:Just create an empty class and add &lt;code&gt;@RunWith&lt;/code&gt; annotation&lt;br&gt;
 *
 *  &lt;code&gt;@RunWith(DynamicSuite.class)&lt;br&gt;
 * public class BatchTest {&lt;br&gt;
 * //no methods or body needed.&lt;br&gt;
 * }&lt;/code&gt;
 * &lt;br&gt;&lt;br&gt;
 * To test only classes in a package and ignore test classes in subpackages mark the class with @NonRecursive.
 * To test all test classes in a project mark a class at a project's  root test  package  with &lt;code&gt;@RunWith(DynamicSuite.class)&lt;/code&gt;
 * and it will run all test classes in the project.
 * The only catch so far is that all the methods of all test classes gets run under
 * this the setup class and the results are all grouped under that class , at least from what I can see in Netbeans.
 *
 *
 * @author anjan
 */
public class DynamicSuite extends Suite {

    static boolean isEntrySuite=true;
    public DynamicSuite(Class&lt;?&gt; setupClass) throws InitializationError {

        super(setupClass, getTestClasses(setupClass,setupClass.isAnnotationPresent(NonRecursive.class)));

            //this will run after the initial setup has been done;
            //If a  Class is marked as NonRecursive and its the entry point of tests
            // it won't load test classes from subpackages.
            //but if the Class is marked as NonRecursive and its not the entry point
           // of tests the annotation will be ignored and all classes from subpackages of the containing
          //package will be loaded
            isEntrySuite=false;

    }

    public static Class&lt;?&gt;[] getTestClasses(Class setupClass ,boolean nonRecursive) {

        List&lt;Class&gt; classes = null;

        String packageName = setupClass.getPackage().getName();
        String path = setupClass.getProtectionDomain().getCodeSource().getLocation().getFile();
        path = path + packageName.replace('.', File.separatorChar);

        File dir = new File(path);

        try {
            classes = findTestClasses(dir, setupClass,nonRecursive);
        } catch (Exception ex) {
            throw new RuntimeException(&quot;Problem loading classes from package[&quot; + packageName + &quot;]&quot;, ex);
        }
        return classes.toArray(new Class[classes.size()]);
    }

    /**
     * recursively finds Classes in test package &lt;br&gt;
     * if it finds a class annotated with @RubWith(DynamicSuite.class)
     * if loads that class and ignores all classes and sub-packages in that package
     * because the loaded class is responsible for loading classes under ite hierarchy
     * @param dir   The root directory
     * @return The classes
     * @throws ClassNotFoundException
     */
    private static List&lt;Class&gt; findTestClasses(File dir, Class setupClass, boolean nonRecursive) throws ClassNotFoundException {
        List&lt;Class&gt; classes = new ArrayList&lt;Class&gt;();
        if (!dir.exists()) {
            return classes;
        }
        File[] files = dir.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
               //only load classes in subpackage if the setup class isn't marked as NonRecursive
                // or its marked as NonRecursive but its not the entry point class
                if(!nonRecursive ||(nonRecursive &amp;&amp; !isEntrySuite))
                classes.addAll(findTestClasses(file, setupClass,nonRecursive));
            }
            else if (file.getName().endsWith(&quot;.class&quot;)) {

                String className = file.getName().substring(0, file.getName().length() - 6);

                if (!className.equals(DynamicSuite.class.getSimpleName())) {

                    String packageDirPath = file.getPath();
                    packageDirPath = packageDirPath.substring(packageDirPath.indexOf(&quot;classes&quot;));
                    String pkg = packageDirPath.replace(File.separatorChar, '.').substring(8).replace(&quot;.&quot; + file.getName(), &quot;&quot;);
                    Class cls = Class.forName(pkg + '.' + className);
                    if (cls.isAnnotationPresent(RunWith.class)) {
                        RunWith ann = (RunWith) cls.getAnnotation(RunWith.class);

                        if (ann.value().equals(DynamicSuite.class)) {
                           //ignore the class being run, otherwise the program will crash with StackOverflowError
                            if (!cls.equals(setupClass)) {
                                classes = new ArrayList&lt;Class&gt;();
                                classes.add(cls);
                                break;
                            }
                        } else {
                            classes.add(cls);
                        }

                    } else {
                        classes.add(cls);
                    }

                }
            }
        }

        return classes;
    }

}
</pre>
<p>The Annotation class:</p>
<pre class="brush: java; title: ; notranslate">
/**
 *Used to Mark DynamicSuite as NonRecursive so that:&lt;br&gt;
 * If a Suite that's being run is marked as NonRecursive, it will only run classes&lt;br&gt;
 * within the same package.&lt;br&gt;
 * But If the  Suite being run is not marked as  NonRecursive,&lt;br&gt;
 * it ignores all NonRecursive annotations in Suites contained in subpackages of the package the&lt;br&gt;
 * Suite class belongs to.&lt;br&gt;
 * The rationale is to be able to test only Tests in a package when desired at the same time&lt;br&gt;
 * being able to test all tests in a project or in a package and subpackages when running when the Suite being run is&lt;br&gt;
 * not marked as NonRecursive.&lt;br&gt;
 * @author anjan
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface NonRecursive {

}
</pre>
<p>Sample code:<br />
Running all test classes recursively</p>
<pre class="brush: java; title: ; notranslate">
@RunWith(DynamicSuite.class)
public class EntryPoint {

}
</pre>
<p>Sample code:<br />
Running only test classes in a package</p>
<pre class="brush: java; title: ; notranslate">
@NonRecursive
@RunWith(DynamicSuite.class)
public class EntryPoint {

}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2012/01/automatic-unit-testing-test-packages-recursively-in-junit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hidden Talent of HtmlUnit -Reverse-geocoding using Javascript API</title>
		<link>http://www.anzaan.com/2011/09/hidden-talent-of-htmlunit-reverse-geocoding-using-javascript-api/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hidden-talent-of-htmlunit-reverse-geocoding-using-javascript-api</link>
		<comments>http://www.anzaan.com/2011/09/hidden-talent-of-htmlunit-reverse-geocoding-using-javascript-api/#comments</comments>
		<pubDate>Mon, 19 Sep 2011 20:00:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[front end]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[googlemap]]></category>
		<category><![CDATA[HtmlUnit]]></category>
		<category><![CDATA[reverse-geocoding]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=158</guid>
		<description><![CDATA[Before Google provided HTTP reverse-geocoding service, the world was a dark place if you needed reverse-geocoding in your application. The only way to perform reverse-geocoding was using javascript API that too using third party library. Since the application I was working on a year or so back required reverse-geocoding- worse it was central to our &#8230; <a href="http://www.anzaan.com/2011/09/hidden-talent-of-htmlunit-reverse-geocoding-using-javascript-api/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Before Google provided HTTP reverse-geocoding service, the world was a dark place if you needed reverse-geocoding in your application.<br />
The only way to perform reverse-geocoding was using javascript API that too using third party library.<br />
Since the application I was working on a year or so back required reverse-geocoding- worse it was central to our geo-location based reporting &#8211; I had to find a<br />
 way of reverse geocoding  high volume longitude/latitude pairs on the server side.<br />
After contemplating  various solutions/non-solutions I decided to give myself some time to come up with a solution that didn&#8217;t<br />
 require us to pay for premium service or ditch googlemaps altogether.<br />
That&#8217;s when I came across HtmlUnit. As soon as I read about its capabilities, I suddenly had a brilliant idea!<br />
The idea was to use HtmlUnit to access a page with a small googlemap loaded ( reverse geocoding using GDirection required an instance of googlemap to be present)<br />
 on it, that has a form for entering longitude and latitude, a button to submit reverse-geocoding request and  a DIV element for populating reverse-geocoded address  response<br />
from Google.</p>
<p>Javascript code:</p>
<pre class="brush: jscript; title: ; notranslate">
  // GMap2 object
            var map;
            // GReverseGeocoder object
            var rg;
            // text input fields
            var lat;
            var lng;
            // result div
            var addressText;

            function load() {
                if (GBrowserIsCompatible()) {
                    lat = document.getElementById(&quot;lat&quot;);
                    lng = document.getElementById(&quot;lng&quot;);
                    addressText = document.getElementById(&quot;address&quot;);

                    map = new GMap2(document.getElementById(&quot;map&quot;));
                    map.setCenter(new GLatLng(-33.83955, 151.2084), 15);
                    map.addControl(new GLargeMapControl());
                    rg = new GReverseGeocoder(map);

                    // add listner for the result
                    GEvent.addListener(rg, &quot;load&quot;, function(response){
                        addressText.innerHTML=response.address
                    });
                    //add listener for error response
                    GEvent.addListener(rg, &quot;error&quot;, function(lastpoint){
                        addressText.innerHTML = &quot;ERROR:point &quot; + lastpoint;
                    });

                    // Listener to detect clicks on map to get coordinates to fill in the lat and lng fields-for testing purpose.
                    GEvent.addListener(map, &quot;click&quot;, function(marker, point){
                        lat.value=point.lat();
                        lng.value=point.lng();
                    });

                }  

            }

            // get the input form lat and lng fields and issue a reverse geocode
            // request
            function reverse(){
                var point = new GLatLng(lat.value,lng.value);
                rg.reverseGeocode(point);
                return false;
            }
</pre>
<p>HTML code:</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;form name=&quot;rev&quot; id=&quot;rev&quot;  action=&quot;&quot; method=&quot;post&quot;  onSubmit=&quot; reverse();return false;&quot;&gt;
            &lt;table&gt;
                &lt;tr&gt;&lt;td&gt;Latitude (WGS84)&lt;/td&gt;&lt;td&gt;&lt;input id=&quot;lat&quot; name=&quot;lat&quot; type=&quot;text&quot; size=&quot;20&quot; value='' /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td&gt;Longitude (WGS84)&lt;/td&gt;&lt;td&gt;&lt;input id=&quot;lng&quot; name=&quot;lng&quot; type=&quot;text&quot; size=&quot;20&quot; value='' /&gt;&lt;/td&gt;&lt;/tr&gt;
                &lt;tr&gt;&lt;td&gt;&lt;input name=&quot;submit&quot; id=&quot;submit&quot; type=&quot;submit&quot; onClick=&quot;reverse()&quot; value=&quot;Get Address&quot;&gt;&lt;/td&gt;&lt;td&gt; address:&lt;div id=&quot;address&quot;&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;

                &lt;tr&gt;&lt;td colspan=&quot;2&quot;&gt;&lt;div id=&quot;map&quot; style=&quot;width:400px; height:400px;&quot;&gt;&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;
            &lt;/table&gt;

        &lt;/form&gt;
</pre>
<p>I  wrote a Java method which  accessed the webpage, populated longitude/latitude textbox in the webpage, clicked the submit button, and wait for the response<br />
 to be populated in the div element -all done  using HtmlUnit&#8217;s headless browser.  After sleeping for 2 seconds the method then read the content of the address div element.<br />
 And it worked flawlessly.</p>
<p>Java Code:</p>
<pre class="brush: java; title: ; notranslate">
public static String latLngToAddress(Float lat, Float lon) {

        try {
            WebClient wc = new WebClient();
            wc.setThrowExceptionOnScriptError(false);

            HtmlPage page = (HtmlPage) wc.getPage(&quot;http://localhost:8084/ReverseGeocoder/&quot;);

            HtmlForm form = page.getFormByName(&quot;rev&quot;);
            HtmlInput latInput = (HtmlTextInput) form.getInputByName(&quot;lat&quot;);
            latInput .setValueAttribute(lat.toString());

            HtmlTextInput lngInput = (HtmlTextInput) form.getInputByName(&quot;lng&quot;);
            lngInput.setValueAttribute(lon.toString());

            HtmlSubmitInput button = (HtmlSubmitInput) form.getInputByName(&quot;submit&quot;);
            button.click();

            Thread.sleep(2000);

            return page.getElementById(&quot;address&quot;).getTextContent();

        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }
</pre>
<p>I spent quite a bit of time then  to finally come up with this solution. But before I finished the application, Google finally provided  HTTP reverse-geocoding service which meant that there was<br />
 no need to use my solution. But at least I&#8217;m glad I tried it and came up with a solution when none existed <img src='http://www.anzaan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2011/09/hidden-talent-of-htmlunit-reverse-geocoding-using-javascript-api/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serializing CGLIB enhanced proxy into JSON using XStream</title>
		<link>http://www.anzaan.com/2010/06/serializing-cglib-enhanced-proxy-into-json-using-xstream/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=serializing-cglib-enhanced-proxy-into-json-using-xstream</link>
		<comments>http://www.anzaan.com/2010/06/serializing-cglib-enhanced-proxy-into-json-using-xstream/#comments</comments>
		<pubDate>Sat, 26 Jun 2010 01:34:36 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[CGLIB]]></category>
		<category><![CDATA[enhanced proxy]]></category>
		<category><![CDATA[lazy loading]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[xstream]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=133</guid>
		<description><![CDATA[I use a custom very lightweight persistence library that does lazy loading using CGLIB Enhanced proxy.
THe generated proxy for domain objects use  Key/value Map data fed to it via a static factory method.
When a get or set method is called for the wrapped domain, the proxy check the value for the field in the Map,
if it finds an entry for the field, which means the field hasn't been initialised, it sets the field value from Map and removes <a href="http://www.anzaan.com/2010/06/serializing-cglib-enhanced-proxy-into-json-using-xstream/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I use a custom very lightweight persistence library that does lazy loading using CGLIB Enhanced proxy.<br />
THe generated proxy for domain objects use  Key/value Map data fed to it via a static factory method.<br />
When a get or set method is called for the wrapped domain, the proxy check the value for the field in the Map,<br />
if it finds an entry for the field, which means the field hasn&#8217;t been initialised, it sets the field value from Map and removes<br />
the entry from the Map.<br />
If no entry is found in the Map, the method returns value of the field of the domain object encapsulated by the getter method<br />
rather than getting it from the Map.</p>
<p>Of course if the field is a domain object, then the object is fetched using the PK value in the Map.<br />
That gives me the same  lazy loading voodoo magic like Hibernate- the 10 pound gorrila.<br />
The persistence is backed by a cache which looks at a domain&#8217;s metadata  and<br />
only caches those that are specified as cacheable.</p>
<p>Everything works like a charm except that the CGLIB enhanced  objects  don&#8217;t play nice with XStream at all.<br />
When serializing enhanced objects XStream spits out gory details of classe/superclasses/interfaces and full dissection of a Map that is fed to a static method when creating the proxy object, when all i want is the pojo object wrapped by the proxy.</p>
<p>I believe the XStream library simply gets the value of the field rather than calling the getter method  using reflection when serializing.<br />
That must be the reason that in my case all serialised objects have empty values for fields because the fields don&#8217;t get set  when the proxy is<br />
 created, they get set only setter method is called on it or getter method is called for the first time .<br />
I think that&#8217;s the same problem with Hibernate and I guess that&#8217;s the reason it throws Lazy Initilization Exception.</p>
<p>I tried the CGLIBEnhancedConverter that comes with the library but it didn&#8217;t work for me.<br />
I couldn&#8217;t find a simple enough solution in the internet and the ones I found were all Hibernate specific.<br />
Since this is the second time I had been trying to solve the issue, I decided to push forward and find a work around myself.</p>
<p>After trying out a few different solutions I finally came up with a dead simple solution.<br />
IT involves a static method to deproxy the enhanced domain objects and a XStream custom converter class.<br />
There may be performance cost  as it uses reflection eventhough getter setter methods for domain classes are cached for reuse.</p>
<p>Here&#8217;s the simplified method.</p>
<pre class="brush: java; title: ; notranslate">

  /**
     * Deproxies a CGLIB enhanced proxy object
     * @param &lt;T&gt;
     * @param proxy
     * @return deproxied domain object
     */
    public static &lt;T &gt; T deproxyReflection(final T proxy) {

      Class entityClass = proxy.getClass().getSuperclass();

        T entity = (T) ClassUtil.getInstance(entityClass);

        Field[] fields =  entityClass.getDeclaredFields();

        for (Field f : fields) {
            try {

	 // no need to set the values of collections as they won;t be serialized.
                //we just need the actaul properties taht amp to table columns
                if(List.class.isAssignableFrom(f.getType()))
                    continue;

                //I use a utility method to fetch getter/setter methods.
                //it simply loops through the object and super class to find the methods.
//so instead of screwing arund with the field's security settings we'll use getters/setters to ensure its unintrusive
                Method getter = ClassUtil.getPojoMethod(entityClass, f.getName(), ClassUtil.MethodType.GETTER);
                Method setter = ClassUtil.getPojoMethod(entityClass, f.getName(), new Class[]{f.getType()}, ClassUtil.MethodType.SETTER);

                Object val = getter.invoke(proxy, null);
                setter.invoke(entity, new Object[]{val});

            } catch (Exception ex) {
                Logger.getLogger(EntityProxyFactory.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                f.set(entity, f.get(proxy));
            } catch (Exception ex) {
                Logger.getLogger(EntityProxyFactory.class.getName()).log(Level.SEVERE, null, ex);
            } 

        }

        return entity;
    }
</pre>
<p>We need to register a converter with XStream  that used the above method to sanitize the domain objects before serializing.</p>
<pre class="brush: java; title: ; notranslate">

/**
 * XStream converter to convert a CGLIB enhanced proxy  to the wrapped pojo object.
 *
 */
public class CGLIBEnhancedEntityConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return (Enhancer.isEnhanced(clazz)  || clazz == CGLIBMapper.Marker.class) ;
    }

    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {

            // deproxy before sending it off the chain for serialization. ANd that's it.
           // XStream will get a simple pojo object and it will serialize it like any other pojo object.
         context.convertAnother(EntityProxyFactory.deproxyReflection(source));

    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {

    throw new Error(&quot;not supported&quot;);
    }

}
</pre>
<p>And that&#8217;s it. That&#8217;s all it takes.<br />
If a domain object has other domain objects as fields, those fields will not be handled by the above method.<br />
For that there are two choices. Firstly you can look at the field&#8217;s class type and say if t implements or extends your base Domain class/interface, you can deproxy them recursively.<br />
In my case all domain objects implement a bare minimum interface called IEntity with only one getId() method.</p>
<p> the above method can be modified to recursively deproxy/sanitize a domain&#8217;s fields if they are proxied objects.</p>
<pre class="brush: java; title: ; notranslate">

//.............
            Object val = getter.invoke(proxy, null);

                if (IEntity.class.isAssignableFrom(f.getType()) {
                    val=deproxy(val);//recursively deproxy the fields if they are enhanced objects
                }
                setter.invoke(entity, new Object[]{val});
</pre>
<p>If you only have to serialize a handful of domain objects, it might be better to register converters<br />
 for those fields at startup instead of using the above method.</p>
<p>Say, we have a domain class State with Country as one of its field, we can register the above converter to convert the country object as below.</p>
<pre class="brush: java; title: ; notranslate">

//.............
//entity manager that handles all persistence needs
IEntityManager em= (IEntityManager) BeanFactory.getBean(&quot;entityManager&quot;);

//fetch a list of State objects with id smaller than3
       List&lt;State&gt; list= em.fetch(State.class, &quot;id&lt;3&quot;);

//uses factory method to instantiate Xstream
xstream xstream= XStreamFactory.getXstream(Format.JSON);

CGLIBEnhancedEntityConverter cglibConverter= new CGLIBEnhancedEntityConverter();

//register default converter
xstream.registerConverter(cglibConverter);

//register field converter. country field for State objects
xstream.registerLocalConverter(State.class, &quot;country&quot;, cglibConverter);

//spit out the serialized json objects
 System.out.println(xs.toXML(list));
</pre>
<p>here&#8217;s the result  without deproxying the domain object:<br />
The before version <img src='http://www.anzaan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<pre class="brush: java; title: ; notranslate">

{&quot;list&quot;: [
  {
    &quot;code&quot;: &quot;&quot;,
    &quot;name&quot;: &quot;&quot;,
    &quot;daylightSavingStart&quot;: &quot;&quot;,
    &quot;daylightSavingEnd&quot;: &quot;&quot;,
    &quot;CGLIB$BOUND&quot;: true,
    &quot;CGLIB$CALLBACK_0&quot;: {
      &quot;@class&quot;: &quot;com.barahisolutions.proxy.EntityProxyFactory$EntityMethodInterceptor&quot;,
      &quot;data&quot;: [
        {},
        {
          &quot;default&quot;: {
            &quot;loadFactor&quot;: 0.75,
            &quot;threshold&quot;: 12
          },
          &quot;int&quot;: 16,
          &quot;int&quot;: 8,
          &quot;string&quot;: &quot;id&quot;,
//..................................................
//there's 10 times more of this garbage which i didn;t bother to print out.
</pre>
<p>And here's the nice and clean pojo version of the deproxied proxy objects.<br />
I used the recursive option to inspect properties if objects and deproxy them if they are proxied domain<br />
objects.<br />
The after version <img src='http://www.anzaan.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<pre class="brush: java; title: ; notranslate">

{&quot;list&quot;: [
  {
    &quot;id&quot;: 1,
    &quot;code&quot;: &quot;NSW&quot;,
    &quot;name&quot;: &quot;New South Wales&quot;,
    &quot;utcOffset&quot;: 10.0,
    &quot;daylightSavingOn&quot;: false,
    &quot;daylightSavingStart&quot;: &quot;&quot;,
    &quot;daylightSavingEnd&quot;: &quot;&quot;,
    &quot;country&quot;: {
      &quot;id&quot;: 18,
      &quot;code&quot;: &quot;&quot;,
      &quot;name&quot;: &quot;Barbados&quot;
    }
  },
  {
    &quot;id&quot;: 2,
    &quot;code&quot;: &quot;VIC&quot;,
    &quot;name&quot;: &quot;Victoria&quot;,
    &quot;daylightSavingOn&quot;: false,
    &quot;daylightSavingStart&quot;: &quot;&quot;,
    &quot;daylightSavingEnd&quot;: &quot;&quot;,
    &quot;country&quot;: {
      &quot;id&quot;: 12,
      &quot;code&quot;: &quot;AUS&quot;,
      &quot;name&quot;: &quot;Australia&quot;
    }
  }
]}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2010/06/serializing-cglib-enhanced-proxy-into-json-using-xstream/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grouping Java objects using object&#8217;s properties/fields</title>
		<link>http://www.anzaan.com/2010/06/grouping-objects-using-objects-property/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=grouping-objects-using-objects-property</link>
		<comments>http://www.anzaan.com/2010/06/grouping-objects-using-objects-property/#comments</comments>
		<pubDate>Sat, 12 Jun 2010 13:17:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[Software Development]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=124</guid>
		<description><![CDATA[I recently had to build a HTML select list with items grouped by category . The list had to be populated using ajax as using simple jsp tag wasn’t enough as I needed other properties besides simple key/ value and group for validation and displaying description of the selected item using javascript . Since grouping &#8230; <a href="http://www.anzaan.com/2010/06/grouping-objects-using-objects-property/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I recently had to build a HTML select list with items grouped by category .<br />
The list had to be populated using ajax as using simple jsp tag wasn’t enough as I needed other<br />
properties besides simple key/ value and group for validation and displaying description of the selected item using javascript .</p>
<p>Since grouping objects can be quite quite handy for displaying grouped data in forms and in reports  I ended up creating  a utility method in java which  takes a List of objects and a field name to group the objects by ,<br />
and returns a map with keys as the values of the field name and values a a list of objects under this group.</p>
<p>Here’s the method . </p>
<pre class="brush: java; title: ; notranslate">

    /**
     * Groups objects using field name provided
     *  @param list the list of objects to group
     * @param field the field to group the objects by
     * @return new Map containing list of objects.
     * The Map's key is the property specified in criteria object
     */

public static &lt;V&gt; Map&lt;String,List&lt;V&gt;&gt; group(List&lt;V&gt; list, String field) {

            //used for indexing to avoid too much looping
	     HashMap&lt;String,K&gt; index= new HashMap&lt;String,K&gt;();
      // the container for grouped data. K is the data type for the field's value.
        HashMap&lt;K,List&lt;V&gt;&gt; groupedData= new HashMap&lt;K, List&lt;V&gt;&gt;();

      // the method to invoke to get the value of the 'field' prop from objects
         Method m=null;

        try {
          V obj=list.get(0);
       // Used a handy Util Class's method for getting the getter method for 'field'
          m = ClassUtil.getMethod(obj.getClass(), &quot;get&quot;+StringUtil.getFirstUpper(field));
        } catch (NoSuchMethodException ex) {
            Logger.getLogger(ListUtil.class.getName()).log(Level.SEVERE, null, ex);

            return null;
        }

       //iterate through the list of objects passed as parameter
        for (V object : list) {

	//the 'field' value of object
             K columnVal=null;

             try {
                    columnVal = (K) m.invoke(object, null);

                     // group of objects under columnVal group
                       List&lt;V&gt; group=groupedData.get(index.get(columnVal.toString()));

                if(group==null){
                    group= new ArrayList&lt;V&gt;();
                groupedData.put(columnVal, group);
                index.put(columnVal.toString(), columnVal);
                }
                //add the object to the group
                group.add(object);

                } catch (Exception ex) {
                    Logger.getLogger(ListUtil.class.getName()).log(Level.SEVERE, null, ex);
                }
        }

        return groupedData;

}
</pre>
<p>here&#8217;s a simple test:</p>
<pre class="brush: java; title: ; notranslate">

   List&lt;Command&gt; commands= new ArrayList();

//create objects to populate a list;

        Command comm= new DeviceCommand();
        comm.setCommand(&quot;CONTROL comm1&quot;);
        comm.setCommandType(CommandType.CONTROL);
        comm.setName(&quot; CONTROL command 1&quot;);
        commands.add(comm);

          Command comm2= new DeviceCommand();
        comm2.setCommand(&quot;comm2&quot;);
        comm2.setCommandType(CommandType.CONTROL);
        comm2.setName(&quot; CONTROL command 2&quot;);
        commands.add(comm2);

          Command comm3= new DeviceCommand();
        comm3.setCommand(&quot;INFORMATION comm1&quot;);
        comm3.setCommandType(CommandType.INFORMATION);
        comm3.setName(&quot;INFORMATION command 1&quot;);
        commands.add(comm3);

          Command comm5= new DeviceCommand();
        comm5.setCommand(&quot;SETTING comm1&quot;);
        comm5.setCommandType(CommandType.SETTING);
        comm5.setName(&quot;SETTING command 1&quot;);
        commands.add(comm5);

          Command comm6= new DeviceCommand();
        comm6.setCommand(&quot;SETTING comm2&quot;);
        comm6.setCommandType(CommandType.SETTING);
        comm6.setName(&quot;SETTING command 2&quot;);
        commands.add(comm6);

           Command comm8= new DeviceCommand();
        comm8.setCommand(&quot;OTHER comm1&quot;);
        comm8.setCommandType(CommandType.OTHER);
        comm8.setName(&quot;OTHER command 1&quot;);
        commands.add(comm8);

          Command comm4= new DeviceCommand();
        comm4.setCommand(&quot;CONTROL comm4&quot;);
        comm4.setCommandType(CommandType.CONTROL);
        comm4.setName(&quot;CONTROL  command 4&quot;);
        commands.add(comm4);

           Command comm7= new DeviceCommand();
        comm7.setCommand(&quot;SETTING comm3&quot;);
        comm7.setCommandType(CommandType.SETTING);
        comm7.setName(&quot;SETTING command 3&quot;);
        commands.add(comm7);

          Command comm9= new DeviceCommand();
        comm9.setCommand(&quot;OTHER comm2&quot;);
        comm9.setCommandType(CommandType.OTHER);
        comm9.setName(&quot;OTHER command 2&quot;);
        commands.add(comm9);

          Command comm10= new DeviceCommand();
        comm10.setCommand(&quot;OTHER comm3&quot;);
        comm10.setCommandType(CommandType.OTHER);
        comm10.setName(&quot;OTHER command 3&quot;);
        commands.add(comm10);

      //convert  list of Command objects into a map with commandTpe as key and list of Commands within
    // that group as  map value.
        Map&lt;String,List&lt;Command&gt;&gt; grouped=ListUtil.group(commands, &quot;commandType&quot;);

	//print out the grouped map data.
        System.out.println(grouped.toString());
</pre>
<p> And the string representation  of the grouped data :</p>
<pre class="brush: jscript; title: ; notranslate">
{OTHER=[OTHER command 1, OTHER command 2, OTHER command 3], SETTING=[SETTING command 1, SETTING command 2, SETTING command 3], CONTROL=[ CONTROL command 1,  CONTROL command 2, CONTROL  command 4], INFORMATION=[INFORMATION command 1]}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2010/06/grouping-objects-using-objects-property/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>why css still sucks for layout</title>
		<link>http://www.anzaan.com/2009/06/why-css-still-sucks-for-layout/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-css-still-sucks-for-layout</link>
		<comments>http://www.anzaan.com/2009/06/why-css-still-sucks-for-layout/#comments</comments>
		<pubDate>Thu, 11 Jun 2009 12:21:28 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[front end]]></category>
		<category><![CDATA[layout design]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=109</guid>
		<description><![CDATA[css really sucks for layout <a href="http://www.anzaan.com/2009/06/why-css-still-sucks-for-layout/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m really pissed off with the CSS fanboys let me tell you. Their devotion to CSS-P is so religious that  their collective argument sounds annoyingly rhetorical at best.<br />
Is there such thing as pragmatism?? I&#8217;m aware that pragmatism isn&#8217;t always the desired way to build software and systems. Heck, If I&#8217;m  building a software  to control nuclear reactors, I would be scared to let my pragmatism rule the software design, I can&#8217;t risk blowing a whole city or country and I&#8217;d have to take utmost care in every step I take to ensure I follow proper protocols and procedures so I don&#8217;t  fry a city or entire country accidentally.</p>
<p>But lets face it, designing a website is not the same as designing a nuclear reactor control system.<br />
And as such I can afford to say screw semantics, screw standards, screw them all if they screw up my time and resources and force me to think less of  design  and shitload  more of hacks to just get things right.<br />
I don&#8217;t care to get things just right. I want things to be damn right to start with. And if semantically incorrect methods permit me to do so, so be it. </p>
<p>    I was just wondering, if HTML table was repackaged with absolutely no changes to any of its markup structure and behavior and called grid and renamed tr,td,th too, would all the CSS-P fanboys use it??</p>
<pre class="brush: php; title: ; notranslate">
    &lt;grid&gt;
    &lt;row&gt;
   &lt; unit&gt; &quot;Grid Glory&quot;
   &lt; /unit&gt;
   &lt; /row&quot;&gt;
   &lt; /grid&gt;
</pre>
<p>    To me its utter nonsense to not use a feature just because of semantic concerns and feeble arguments of SEO, accessibility etc.</p>
<p>    The thing that really pisses me off though is the fact that as soon as someone raises concern about CSS/DIV based designs, all the CSS fanboys gang up and point their fingers and tell people that the reason they have problem with CSS/DIV based layout is because they are just plain ass dumb.</p>
<p>    These bright new fanboys are pretty fanatic and everywhere I read, their arguments are just the same. Standard arguments, boxed arguments.</p>
<p>    And they talk about the amount of code in the markup that makes table-based layout horrible to maintain not to mention the bandwidth penalty.</p>
<p>    As if the amount of css hack that has to be conjured to do simple layouts doesn&#8217;t need maintenance and as if it loads by magic on the browser and bandwidth issue becomes non-issue&#8230;.</p>
<p>    CSS /DIV based layout is counter-intuitive to say the least. Who starts thinking in terms of float and clear when designing anyway??<br />
    If I want to add a new element to the a layout, I not only have to think about the size of the element but I have to make damn sure that the rest of the page doesn&#8217;t break by a mere addition of an element in a page. Which forces me to look at the whole design in terms of pixels, margins and paddings to add be able to add<br />
    a new element to a layout item. And that doesn&#8217;t prevent content/elements bleeding off the layout container.</p>
<p>    And how about overlap problems??<br />
    I can break the best laid out CSS site by merely adding one more element to it&#8230;&#8230;</p>
<p>    CSS has merely opened a new job market and allowed people to make loads of money out of it. And the fanboys of CSS/DIV layout guard their self-interest with great zealot because without CSS they will be out of jobs. I mean, who&#8217;s going to write a page full of CSS hack to give us merely a 3-column fluid layout with column-size constraints. And then they write one more page full of CSS hacks to prevent the content from bleeding out of their containers, with partial success.</p>
<p>    Web-development has taken a great leap backward as a result of the push to use CSS/DIV/SPAN for layouts.<br />
    Because we spend most of the time not in designing pages but in applying hacks to make them look devent on most browsers.</p>
<p>    If the fanboys close their eyes for one minute and forget everything bad that had been hammered into their head about tables and think of it as a grid, u&#8217;ll be damn surprised how intuitive it is to design in terms of grids. All decent desktop GUI toolkit provide grid-based layout which allows us to apply constraint to layout grid-elements in relation to other grid elements and so on.</p>
<p>    Why?</p>
<p>    The fanboys might argue that the GUI toolkit designers were mere dumb people who still hold on to the grid-based layout of last century and blah blab and some more blah.</p>
<p>    And when the fanboys run out of ammunition, they fallback to blaming browsers and declare its the fault of browsers and nothing else.<br />
    And meanwhile they bleed to death trying to make a simple layout work in most browsers with tons of css hacks which still doesn&#8217;t quite do the job. why?</p>
<p>    CSS is ill-equipped to handle layouts&#8230;..The language or pseudo-language of CSS was designed by people who have no knack for Designs, if they did, the language would have been more intuitive than this terrible piece of work. I come from a programming background and I love beautiful designs and I like to pretend I can create cool designs and sites. For me CSS/DIV layout makes no sense from either a programmer&#8217;s prespective or a designer&#8217;s.</p>
<p>    From a programmer&#8217;s perspective I like parameter driven development to simplify things, and from a designers perspective, I&#8217;d hate to have to hand-code the whole friggin page design and have to come up with countless hacks to overcome both CSS and browser shortcomings.</p>
<p>    CSS sucks so bad that even though billions of people use the internet everyday, yet no decent visual designing tool has come out so far. The one decent WYSWYG editor Dreamweaver fails miserably when designing layouts in CSS.<br />
    Where&#8217;s the forward mobility promised by this new technology??</p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/06/why-css-still-sucks-for-layout/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why CSS sucks big time for layout</title>
		<link>http://www.anzaan.com/2009/05/why-css-sucks-big-time-for-layout/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=why-css-sucks-big-time-for-layout</link>
		<comments>http://www.anzaan.com/2009/05/why-css-sucks-big-time-for-layout/#comments</comments>
		<pubDate>Thu, 28 May 2009 09:57:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[css]]></category>
		<category><![CDATA[design layout design]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=96</guid>
		<description><![CDATA[Why css sucks and why its poorlt equipped for layout design needs <a href="http://www.anzaan.com/2009/05/why-css-sucks-big-time-for-layout/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I used tables for designing sites from the beginning. And from the beginning I had been using Dreamweaver for designing.<br />
Designing layout with Dreamweaver using tables is no-brainer. Its dead easy to visually manipulate pretty much all aspects of design.<br />
I always considered Dreamweaver a very productive tool. I think it beats everything when it comes to rapid prototyping.<br />
But after really getting curious about all the CSS-P buzz floating around the internet, I decided to look into the ultra-hyped DIV based design using CSS or referred in short as CSS-P..<br />
And All I could hear everyone claiming was people using tables for layout are village-idiot equivalent for designing. And I heard all these people claiming that tables are only used by people who find themselves reluctant or unable to shake off the legacy of last century.<br />
And how semantics mattered and how un-semantic design was deplorable.</p>
<p>And suddenly I found myself worried because I neither liked to be the village-idiot equivalent of design world nor liked being tagged a man from the gone-by century, reluctant to change and still clinging to the world as I knew in that gone by century.</p>
<p>I did a lot of research and I must have read every blog by hippies who claimed to have found the holy grail of  2-column ,3-colum and liquid design.<br />
I eagerly trialed out all those holy-grails.  I was overwhelmed by the amount of hacks that was required to create simple designs that I considered no-brainer when I designed them using tables.  But I didn’t let those insane hacks deter me in my quest to become a better designer.</p>
<p>I was rewriting a CMS I developed at that time and I was busy developing a site for a client using my home-grown CMS.<br />
The site was already in production and I had some back-end stuffs to fix.<br />
And while I was at it, I decided to redesign the front-end that was table based using DIVs and CSS.<br />
And I had fairly good success although I had to use some javascript to give me what I wanted. Of course the overall design was very neat. But after 3-4 weeks shit hit the fan, let me tell you.<br />
Every aspect of the site was dynamic, and depending on the page and user, the site had to shrink and grow. The main content area and the sidebar especially. When the content started piling up and the sidebar needed to grow, the content started bleeding out of the sidebar. And when I fixed that the main area for content started bleeding.<br />
It was a nightmare.</p>
<p>So, there I was again trying to redesign the site again to fix the site up to bring it to a usable state.<br />
And I had no choice but to bring in tables. Gasp! Horror!<br />
That’s the sound of indignation of  CSS purist at my blasphemous mention of tables for layout design.<br />
The hybrid layout did the trick and fixed all the bleeding but I still needed a little help from javascript to give me the desired effect.</p>
<p>Here’s how I needed the layout to be, and CSS/DIV failed me vary badly.<br />
<img class="alignnone size-full wp-image-104" title="layout1" src="http://www.anzaan.com/wp-content/uploads/2009/05/layout1.jpg" alt="layout1" width="636" height="578" /></p>
<p>From that time on I have decided I’ll never listen to religious CSS Purist out there who just design some lousy static site and claim they know it all.<br />
And one argument that I totally utterly despise from CSS purist is that “ YOU DON’T KNOW CSS, THAT’S WHY YOU CAN’T DO THINGS PROPERLY’.<br />
<br />
That smell of arrogance gets me more than anything else.<br />
<br />
CSS is not the end itself fellows, its just a lousy mean to an end.</p>
<p>And you can take your semantic argument and shove it up where the sun never shines.<br />
When the purists harp on about semantics it sound like nothing more than priests harping on about abstinence and the need to keep yourself pure to respect god’s law, thou shall not screw until you are married.<br />
Anything that takes such religious form is very far removed from science. And web-design has shit-load more to do with science than it has to do with religion.</p>
<p>My brother is an artist, his specialty is water color. Mostly he designs by just sketching out coarse outline in pencil and applying color to the canvas.</p>
<p>But when he need precision in his art for say a portrait, he draws out grids in canvas with pencil and starts sketching and then fills up the sketches with paint, and the paintings come alive.<br />
He is a self taught artist and though he never took art classes in his school or anywhere for that matter, yet intuitively he uses grids to get a better layout and precision of his paintings when situation demands</p>
<p>What does that tell??</p>
<p>Maybe nothing, maybe something…..</p>
<p>As for me, it tells me that grids help us organize/arrange content in a layout in an intuitive way, be it an artist’s canvas or a web developer’s HTML markups.</p>
<p>But, on the other hand, using CSS for layout is a fundamentally flawed concept. The concept of emulating table layout with a ton of CSS hack has serious flaws. BOX-Model is conceptually flawed model for designing layouts.<br />
Common sense tells me that if something has a borders and padding, those structures should be contained within that element that gets decorated. It shouldn’t affect its surrounding environment.</p>
<p>Think of it this way. If you want to create fences around your house compound, do you force your neighbor to restructure his house and his compound so u can add a fence (border?? ) or do u just build a fence within your compound??<br />
What if you want to build a really thick wall? Does that mean your neighbor had to make a bigger adjustment? IF your neighbor’s house is very close to the border of your compound, does that mean that your neighbor has to demolish part of his house to accommodate your really thick walls??<br />
Think about the chaos it ensues were things like that in reality.<br />
The side-effect of any structural changes or decoration should only affect only that element and the rest of the elements in your layout shouldn’t have to suffer as a consequence.<br />
Makes sense?</p>
<p>Pragmatism tells me that tables make more sense for layout, but of course all CSS purist will gasp in horror when they hear it.<br />
Every time someone says they prefer Table based layout or hybrid layout, the purists seem to think that those people are against CSS.</p>
<p>Before complicating things too much with purist headset, one should ask themselves a very important quesiton. Is CSS/DIV layout answer to all question?<br />
IF not are there other alternatives to your problems?<br />
IF so and if the alternatives work for you what will stop you from using it??</p>
<p>Oh, I know the answer to the last question for most purists and CSS-P fanboys. ” But, its semantically incorrect…. and it has previewed drawbacks …”.<br />
One thing to keep in mind is all these damn tools available to us have only one purpose, to aid us in our development. So they are supposed to serve us.<br />
So the question is what are semantics for? I don’t serve CSS or W3C, I make CSS serve me the way I see fit for a given situation.<br />
IF CSS doesn’t work for me I don’t cry myself to death or spend days trying to solve something that can be done in an hour using something else.</p>
<p>And one funny argument I keep on hearing is that screen-readers get confused when one use tables for layout because screen-readers take content inside a table as being tabular data.<br />
Hello, people who write those damn things aren’t half that stupid. And screen-reader have been in existence long before this CSS-P fever gripped the general 20-something mass of new breed of  wide-eyed designers.</p>
<p>And, by the way, I&#8217;m not  a designer by profession.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/why-css-sucks-big-time-for-layout/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Javascript variable scope, private protected and public</title>
		<link>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=javascript-variable-scope-private-protected-and-public</link>
		<comments>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/#comments</comments>
		<pubDate>Wed, 27 May 2009 13:30:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[front end]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[closure]]></category>
		<category><![CDATA[javascript varaible scope]]></category>
		<category><![CDATA[module pattern]]></category>

		<guid isPermaLink="false">http://www.anzaan.com/?p=77</guid>
		<description><![CDATA[Private ,public and protected/privileged access of variables and functions in javascript <a href="http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/">Read more <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Javascript is a tricky language. Since I learned programming with Java, I always find myself trying to find its equivalence in other languages I come across.</p>
<p>I know its bad in that in that it kind of stops me from exploring the potentials provided by other languages in full. Its like going to a Chinese restaurant and eating fried rice everytime because fried rice is the only dish that is close to what I&#8217;m used to eating daily.<br />
There&#8217;s such variety in Chinese food, and yet if I go there and I eat fried-rice evertyime Its a sign I have a bit of a problem opening myself up to new things. And that&#8217;s a big problem.</p>
<p>The world has such diversity in every-aspect imaginable, ( with the exception of mob-justice and mob-mentality which seem to cross all cultural and geographical boundary as it seems), and not being able to appreciate the diversity and learn for it is a great pity.</p>
<p>Back to programming, not all constructs  found in languages are sole property of a  given language. They are  generally abstractions provided by languages to solve problems effectively and those abstractions can be applied in other languages even if they don&#8217;t provide such explicit constructs.</p>
<p>There was a time when I treated javascript like lepers, something to avoid at all cost, except when it was really unavoidable.<br />
But then I had a change of perspective, at a philosophical level -dare I day. &#8216;If I avoid something to such length then I must be shit-scared of it for some reason&#8217;.<br />
And by nature I hate to admit my fears for the fear of being tagged a wussy, a chicken.<br />
Of course I can find things to justify my avoidance of javascript to others without admitting my fear, but how about myself?<br />
What do I tell myself when I go to sleep??<br />
And since I couldn&#8217;t find reasonable arguments to fool myself into good sleep because my rational self always counter-argued that &#8216;you  fear what you don&#8217;t understand&#8217;, and  my arguments against javascript were just my lame attempt to hide my fears , I decided to deal with my fears for once and for good.</p>
<p>And since then I have been quite happy with my javascript experience.</p>
<p>Since I&#8217;m still a Java fan-boy, though I have a feeling that it won&#8217;t be for  too long, Scala! here I come,  I tried to find solution to variable scoping in javascript so that I have more control over objects I create and the API&#8217;s I expose. This has been a big issue due to the need for me to use at least 3-4 third-party libraries to get my job done for the current project I&#8217;m rewriting.<br />
And the project has a massive javascript code-base.</p>
<p>Looking back at the code I did last year makes me cringe. There was no modularity and there was too much interdependency between components and objects.</p>
<p>(Hmm&#8230; component decoupling is entirely another topic for another sleepless night.)</p>
<p>And this time around I decided to do thing the right way &#8211; at least to my best knowledge.</p>
<p>After long hours prowling the internet, finally I managed to understand the trick to accomplish what I wanted.</p>
<p>So here&#8217;s an example of an object with everything pubic, the dumbest example.</p>
<pre class="brush: jscript; title: ; notranslate">

var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;

this.getFullName=function(){

return this.surname+&quot;,&quot;+this.name;
}

this.getAge=function(){

return (new Date().getYear() - this.dob.getYear()) ) ;// I'm being lazy here

}

}

// another a little less dumb-looking flavor with prototyping but dumb nonetheless
var Person= function(name ,surname, sex, dob){

this.name=name;
this.surname=surname;
this.sex=sex;
this.dob=dob;
}

Person.prototype.getFullName=function(){
return this.surname+&quot;,&quot;+this.name;
}
Person.prototype.getAge=function(){
return (new Date().getYear() - this.dob.getYear()) ) ;
}
</pre>
<p>All the properties in of the object are accessible to any function/code that instantiates Person object. And getFullName() is nothing more but a handy method for getting both name and surname.<br />
And the calling code can access dob and compute age by itself.<br />
So everything is accessible.</p>
<pre class="brush: jscript; title: ; notranslate">
var person = new Person('inny', 'minny', 'yes please', new Date(1901, 0, 1) );

var fullname= person.surname+&quot;,&quot;+person.name;

var age=  (new Date().getYear() - person .dob.getYear()) ) ;
</pre>
<p>Of course one can argue that we can differentiate the difference between private and public by using underscore for private properties such as _dob ( as a lot of people insist on doing).</p>
<p>But who are we fooling? That&#8217;s just a convention we use, and if you work in a large team there&#8217;s no guarantee that someone else will not get smart and start mutating the underscored variable and shit might hit the fan depending on how critical the property is.</p>
<p>Instead of developing ad-hoc convention I believe its more ideal to use the best of what a language provides without having to define our own rule which can be broken by anyone who cares to break it. Sometimes I don&#8217;t trust myself,let alone trust others.</p>
<p>So if we need to hide the DOB for privacy reason and only expose the age,  and we need to hide the individual name and surname for some reason, here&#8217;s how its done:</p>
<pre class="brush: jscript; title: ; notranslate">
var Person= function(name ,surname, sex, dob){

this.sex=sex;

this.getFullName=function(){

return surname+&quot;,&quot;+name;
}

this.getAge=function(){

return  (new Date().getYear() - .dob.getYear()) ) ;

}
}
Person.prototype.getGender=function(){
var sex=this.sex,tolowerCase();
if( sex=='male' || sex=='m' )
return 'male';
else if( sex=='female' || sex=='f' )
rerturn 'female';
else
return 'god knows';

}

Person.prototype.getSpecies=function(){

return 'mammal';
}
</pre>
<p>In the above example, any instantiating code has only access to getFullName() , getAge() functions and &#8216;sex&#8217; variable of person object.<br />
But we allow &#8216;sex&#8217; variable to be declared in two forms, long and short. And we return &#8216;sex&#8217; in  long format with the help o getGender()  helper function.</p>
<p>The above example can be broken down as following;</p>
<p>All variables except sex are private as they are constructor-scoped.<br />
getFullName() and getAge() are privilaged function that have access to private variables name, surname and sex and thus are privileged/protected functions.</p>
<p>getGender() is a public function that has access to public variable sex.<br />
the new getSpecies() is a public function that returns a value that&#8217;s entirely in its own scope.</p>
<p>So, there we have it, private, privileged and public access in javascript.</p>
<p>If we want to use module pattern the above can be modified to:</p>
<pre class="brush: jscript; title: ; notranslate">
var Person= function(name ,surname, sex, dob){

this.sex=sex;
return{

getFullName:function(){

return surname+&quot;,&quot;+name;
},

getAge:function(){

return  (new Date().getYear() - this.dob.getYear()) ) ;

},
getSpecies:function(){

return 'mammal';
}

}
}
</pre>
<p>An example of creating static object with private and public scope:</p>
<pre class="brush: jscript; title: ; notranslate">
var Human = function() {

var species = &quot;mammal&quot;;

return {

alert: function(){alert(species);}

};
}();

Human.alert();//displays 'mammal'
</pre>
<p>Here the variable species is private.<br />
The function gets executed immediately due to () at the end of the function definition and will return a public static method alert()</p>
<p>That sums up variable scopes in javascript.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.anzaan.com/2009/05/javascript-variable-scope-private-protected-and-public/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

