
<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.2" -->
<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/"
	>

<channel>
	<title>Programming Thoughts @ Work</title>
	<link>http://anirudhvyas.com/root</link>
	<description>A block of code can say more than a great book filled with 'anecdotes' and insights</description>
	<pubDate>Mon, 09 Jun 2008 01:43:21 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.2</generator>
	<language>en</language>
			<item>
		<title>Constants maintainence : Proposed solution</title>
		<link>http://anirudhvyas.com/root/2008/06/09/constants-maintainence-proposed-solution/</link>
		<comments>http://anirudhvyas.com/root/2008/06/09/constants-maintainence-proposed-solution/#comments</comments>
		<pubDate>Mon, 09 Jun 2008 00:55:07 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://anirudhvyas.com/root/2008/06/09/constants-maintainence-proposed-solution/</guid>
		<description><![CDATA[Almost all of us have used some sort of a common Constants class which gets piled with huge number of constants, ranging from things like SOME_IMPORTANT_ID to something trivial like INTEGER_VALUE_1. Whatever may be the reason, but the grouping of these things goes right against separation of concerns (as everything is virtually dumped in a [...]]]></description>
			<content:encoded><![CDATA[<p>Almost all of us have used some sort of a common Constants class which gets piled with huge number of constants, ranging from things like SOME_IMPORTANT_ID to something trivial like INTEGER_VALUE_1. Whatever may be the reason, but the grouping of these things goes right against separation of concerns (as everything is virtually dumped in a single constants class).  Some time back a common practice was to use Interface for declaring all constants and then allow for all classes to implement this interface to get all constants automatically. This solution needless to say was fast, but also outrageously wrong. Josh Bloch sums it pretty aptly:<br/></p>
<ul>
<li> First of all, it causes a leakage of implementation detail into many unrelated classes in your code base, because any of the defined constant will be available to all of your classes        when they implement this interface.</li>
<li> As it is contained in the exported API of implementing class, clients of that class may get easily confused because it if of no consequence to the users of the class that it implements such an interface.</li>
<li> Finally, it puts you into a commitment to ensure binary compatibility in the future, even though the class won&#8217;t need to use any of those constants.</li>
</ul>
<p>Needless to say, I completely agree with all the above points, so what was the solution? well the solution was to come up with a common constants class in which you dump all your constants and add comments to group each in a certain way. Needless to say there will be some groupings which are outrageously funny. Like in one of the projects we had to check and constantize all integers, doubles, numbers. (refer to : <a href="http://en.wikipedia.org/wiki/Magic_number_(programming)"> Magic Numbers</a>), due to lack of time (now thats new ain&#8217;t it? <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ), people were adding things like <i>public static final int INTEGER_1 = 1 </i> !!.</p>
<p>And top that with all things mixed up, one can be assured that the class turns out to be a mess. To top all of this java introduced a feature called static imports. Probably because many lame programmers were complaining that it is &#8220;too&#8221; much of an effort to precede the CONSTANT_NAME with its class, so it my class that has all the constants is called something like CONSTANTS, i would have to do something like CONSTANTS.CONSTANT_EMPLOYEE_ID or something in those lines to refer to any constant; So basically to solve this, java provides for static imports, all you have to do is import static XXX.XXX.XXX.CONSTANTS.* and viola! you don&#8217;t have to do that DOT thing anymore. This is Evil! How am I supposed to know that this constant belongs to this class only and not anywhere else?! needless to say my code gets more obfuscated and hard to read and maintain with static imports.</p>
<p>So where is the solution? Solution my friends lies in creating a common interface, generically tying it up to something and then creating separate place holders for each TYPE of constants. So if you want to group all IDs for example, use IDPlaceHolder which would implement this interface. Lets get started on how to do this. First we will create an interface called IConstantPlaceHolder like this :<br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre class="prettyprint">
// Java docs removed for clarity.
public interface IConstantPlaceHolder&lt;T extends Serializable&gt; extends Serializable {

	// gets the value for the constant
	public abstract T getValue();

        // sets the value for the constant.
	public abstract void setValue(final T value);

}
</pre>
<p></code>
</div>
<p>As you can see IConstant place holder is generically tied to a type &quot;T&quot; (let me know if you think of a better name than just a T <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).  It has two methods setValue and get value. It is a Common interface for constants that serves as a place holder for all constants grouped in a meaningful way. For example, all ID constants could be placed in one spot. A typical implementation would be something like:<br/> </p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
 public enum IDPlaceHolder implements IConstantPlaceHolder&lt;Long&gt; {

       DEFAULT_ID(1008L);

        private Long id;

	 // default constructor sets the value.
       private IDPlaceHolder(final Long id){
          setValue(id);
       }

       // get the value
       public final Long getValue(final Long id){
        	return this.id;
        }

      // set the value
      public final setValue(final Long id){
          this.id = id;
        }

   }
</pre>
<p></code>
</div>
<p>
Now all i have to do in client code is IDPlaceHolder.DEFAULT_ID.getValue() and i will have 1008L at my behest. It is expected and recommended that an IConstantPlaceHolder be implemented with the help of an enum, by using an enum one can take advantage of inherent type-safe features in java language. Similar to above we can/may have something like a place holder for all properties or association paths in Hibernate. For our purposes, lets take a simple example of simple string properties like first name, last name etc for an employee.
 </p>
<p>:<br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
public enum GenericStringPropertyPlaceHolder implements IConstantPlaceHolder&lt;String&gt; {

	// employee's first name.
	EMPLOYEE_FIRST_NAME("Mahadev"),

	// employee's last name.
	EMPLOYEE_LAST_NAME("Shiva"),

	// employee's address.
	EMPLOYEE_ADDRESS("Brahmlok"),

	// employee department
	EMPLOYEE_DEPT("NA");

	// the property value we want to set.
	private String propertyValue;

	// get the value
	public final String getValue() {
		return propertyValue;
	}

	//set the value
	public void setValue(String value) {
		this.propertyValue = value;
	}

	// constructor that sets the property value.
	private GenericStringPropertyPlaceHolder(String propertyValue) {
		setValue(propertyValue);
	}
}
</pre>
<p></code>
</div>
<p><br/></p>
<p>
As you can make out, in my client code, I would do something like GenericStringPropertyPlaceHolder.EMPLOYEE_LAST_NAME.getValue() and i will get Shiva as the result. So basically to sum up what we have done in above to implementations is:</p>
<ul>
<li>Create an Enum which implements IConstantPlaceHolder&lt;TYPE&gt; which is generically tied to the TYPE of placeholder it is or can be.</li>
<li>Set the attribute in the constructor and then basically declare the constants with the actual value being passed to them.</li>
</ul>
<p><b>Advantages</b></p>
<hr /></hr>
<p>Obviously, lot of you might be thinking at this point what is need for all this? well my justification is that when a project grows larger and larger, we will eventually end up with a file that looks bulky, bloated and all over the place and then at that point we would ask where is the separation of concerns that i love so much here ?. Trust me, even in a small project this can serve a lot of purposes by putting a constant to the place it belongs.</p>
<p>
An improvement to the above place holder thing can be adding a MODEL in generic parameters and further restricting constants only specific to a model. I have not come with a final draft for the same, when i do, i&#8217;ll try to post it as a follow up. Btw, thanks for your encouraging emails and support, appreciate it and Stay tuned! <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />
</p>
<p>Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/06/09/constants-maintainence-proposed-solution/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Making Generic DAO &#8220;Operation specific&#8221;</title>
		<link>http://anirudhvyas.com/root/2008/05/31/making-generic-dao-operation-specific/</link>
		<comments>http://anirudhvyas.com/root/2008/05/31/making-generic-dao-operation-specific/#comments</comments>
		<pubDate>Sat, 31 May 2008 02:37:21 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

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

		<guid isPermaLink="false">http://anirudhvyas.com/root/2008/05/31/making-generic-dao-operation-specific/</guid>
		<description><![CDATA[After a long haul in posts, I am back again. Thanks to all of you for you encouraging e-mails, much appreciated. The Generic DAO pattern became a de-facto of sorts in Hibernate / ORM world some time back. In keeping with my never ending quest for improving upon already existing patterns available at hand, let [...]]]></description>
			<content:encoded><![CDATA[<p>After a long haul in posts, I am back again. Thanks to all of you for you encouraging e-mails, much appreciated. The Generic DAO pattern became a de-facto of sorts in Hibernate / ORM world some time back. In keeping with my never ending quest for improving upon already existing patterns available at hand, let us make our Generic DAO pattern more &#8220;specific&#8221; in concerns. For those of you who are not familiar with Generic DAO design pattern, refer to: <a href="http://www.hibernate.org/328.html">Generic DAO</a> Recently while working on a testing framework @ Home , It became apparent to me that operational testing warrants that we must separate out the functional/operational aspects for a DAO. Quickly recapturing what a Generic DAO does:<br/></p>
<ul>
<li>It is Generically typed to a Model.</li>
<li> It concerns itself to a Model and can include &#8216;n&#8217; number of CRUD or combination of CRUD operations</li>
<li> Each Model (known Persistent Class in hibernate world) is a concern of a DAO </li>
</ul>
<p><br/></p>
<p>Why Generic DAO is not perfect?</p>
<hr /></hr>
<p>
For starters a simple justification would be separation of operational concerns; we want our &#8220;operational&#8221; aspects for that Model / Persistent class be separated. So for example in a DAO if i am doing a SAVE operation, i should only be concerned with doing a SAVE in DAO and nothing else, If i have a DAO method which deletes a model, then DAO should only be able to handle DELETE and nothing else.<br />
<br/><br />
Using a Generic DAO can reduce clutter, but to truly separate out operational aspects would make the code even cleaner (off course it adds a &#8220;tad&#8221; extra burden of writing more classes/interfaces but it also would make the code more robust IMHO), the code needs to be functionally separate as well or operationally separate to make it a better suited candidate for writing robust test cases.
</p>
<p>Let&#8217;s Get Started!</p>
<hr /></hr>
<p>Continuing with my philosophy of &#8220;lets get down and dirty&#8221; in code, lets get on with seeing somethings in action. I will start out by creating bunch of interfaces on which I would then elaborate to give an idea as to what I meant when i said &#8220;separation of Operational Concerns&#8221;. Lets pull out a common Generic DAO interface.</p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre class="prettyprint">
 public interface IGenericOperationDAO&lt;OPERATION extends IOperation&lt;TYPE&gt;,
                                           TYPE extends Serializable,
                                          MODEL extends AbstractModel&lt;&gt;,
                                          ID extends Serializable&gt;{

	/**
	 * Performs operation on a model.
	 *
	 * @param operationType
	 *            operation to perform
	 * @param model
	 *            model to be operated upon.
	 * @see IOperation
	 */
	public abstract void performOperation(final OPERATION operationType,
			final MODEL model);
}
</pre>
<p></code>
</div>
<p>Lets examine this interface a little to get a glimpse of what i am talking about. IGenericOperationDAO is tied to a MODEL (an AbstractModel is just an abstract class that extends Serializable and serves as a common model for our Models that match the tables in Database). Our GenericOperationDAO interface has one method, that is well apparently very &quot;Generic&quot;, it just says performOperation takes in an IOperation type and a model. an IOperation type interface is basically something like this:<br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
   	/**
	 * Gets the operation type.
	 *
	 * @return the operationType
	 */
	public abstract TYPE getOperationType();
</pre>
<p></code>
</div>
<p>An operation type can be DELETE, CREATE, READ, UPDATE or anything of that sort. An implementation for this operation is as follows. (For simplicity&#8217;s sake, lets assume that we need to do only a deletion (C-U-D operations will be the same).:<br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
public class DeleteOperation implements IOperation&lt;String&gt; {

	/**
	 * {@inheritDoc}
	 */
	public final String getOperationType() {
		return "Delete";
	}

}
</pre>
<p></code>
</div>
<p>As you can make out that operation type simply returns a delete &#8220;string&#8221; (this can be useful in comparing operation types within a DAO), a string is not very robust approach IMHO, if someone has better ideas,  feel free to share <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> !</p>
<p>Now since perform operation is perhaps too generic, lets extend this interface to incorporate our deletions. Here is an example of a generic Delete interface:<br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
public interface IGenericDeleteOperationDAO extends IGenericOperationDAO&lt;DeleteOperation, String, AbstractModel&lt;Long&gt;, Long&gt; {

	/**
	 * Deletes a model.
	 *
	 * @param model
	 *            model type to be deleted.
	 */
	public abstract void processDelete(final AbstractModel&lt;Long&gt; model);
}
</pre>
<p></code>
</div>
<p>
Notice that our generic delete DAO is generically typed to DeleteOperation type.<br />
As we can make out from the above, the generic delete dao inherits performOperation from its generic counter part and extends it by adding processDelete which basically takes in the model and deletes it. All implementing classes (Concrete that is) are expected to implement <strong>this</strong> method. But as we can make out that we probably don&#8217;t want to do certain kinds of things that are in here by implementing this interface directly. Implementing this interface has to be discouraged here since it does NOT directly enforce me going and implementing performOperation unfortunately. To avoid that from happening, lets create another abstraction (i.e. an Abstract Class which implements certain parts of this functionality), see below:
</p>
<p><br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
// java docs left out for clarity
public abstract class AbstractGenericDeleteOperationDAO implements IGenericDeleteOperationDAO {

	/**
	 * Default constructor. Calls perform
         * operation which in turn calls process
         * delete to delete the model given.
	 */
	public AbstractGenericDeleteOperationDAO(final DeleteOperation operationType, final AbstractModel&lt;Long&lt; model) {
		performOperation(operationType, model);
	}

	// javadocs left out
	public abstract void processDelete(final AbstractModel&lt;Long&lt; model);

	//javadocs left out
	public void performOperation(DeleteOperation operationType, AbstractModel&lt;Long&lt; model) {
		if (!operationType.getOperationType().equalsIgnoreCase("delete")) {
			throw new UnsupportedOperationException("No other operation except DELETE supported");
		} else {
			processDelete(model);
		}
	}

}
</pre>
<p></code>
</div>
<p>Quickly the above code will do this:<br/></p>
<ul>
<li>Constructor calls the default implementation of perform operation to account for any other operations if any being passed in, for example if a user manages somehow to pass in something other than a Delete Operation </li>
<li>calls in process delete which is an abstract method, all extending classes (Concrete) will be <strong>Required</strong> to implement this method (if they are a Delete DAO type)</li>
</ul>
<p>So basically a simple implementation of a DAO from a client perspective would look like this:<br/></p>
<div style="background-color:#faebd7;color:black;font-size:13px;overflow-x:auto;">
<code></p>
<pre>
/**
 * Employee delete dao. Concerns itself with just the delete operations for an Employee Model.
 *
 * @author Anirudh Vyas
 */
public class EmployeeDeleteOperationDAO extends AbstractGenericDeleteOperationDAO {

	/**
	 * Full constructor.
	 *
	 * @param operationType
	 *            delete operation type.
	 * @param model
	 *            model type to be operated upon.
	 */
	public EmployeeDeleteOperationDAO(DeleteOperation operationType, AbstractModel&lt;Long&gt; model) {
		super(operationType, model);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public final void processDelete(final AbstractModel&lt;Long&gt; model) {
		// perform Hibernate Deletes here...
	}

}
</pre>
<p></code>
</div>
<p>Now at real client side for this DAO would be a simple matter of doing something like new EmployeeDeleteOperationDAO(DELETE, employeeModel); and viola! we are done! &#8230; similar pattern can be followed for Creation, Reads, Updates. For combination of CRUD operation, a perform operation should be enough. Later we will see how we can improve upon the operation type to make it a little more dynamic than just comparing it with a string or returning a simple string &#8220;delete&#8221; or a &#8220;create&#8221; in operation type, so stay tuned and thanks for reading!</p>
<blockquote><p> Addendum : understandably there can be improvements done in this; refinements etc. If you have any feel free to comment out here, instead of mailing them. That would keep it consistently here. I will try my best to post whenever i get any emails about the refinement.</p></blockquote>
<p>Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/05/31/making-generic-dao-operation-specific/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Ever controversial Code Reviews</title>
		<link>http://anirudhvyas.com/root/2008/05/04/ever-controversial-and-sometimes-annoying-code-reviews/</link>
		<comments>http://anirudhvyas.com/root/2008/05/04/ever-controversial-and-sometimes-annoying-code-reviews/#comments</comments>
		<pubDate>Sun, 04 May 2008 20:32:52 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[XP]]></category>

		<guid isPermaLink="false">http://anirudhvyas.com/root/2008/05/04/ever-controversial-and-sometimes-annoying-code-reviews/</guid>
		<description><![CDATA[A long haul in posts (at least by my standards) was basically due to combination of work schedule, &#8220;other things&#8221; (don&#8217;t ask  ). For past couple of weeks I have had my code reviewed by some people, which interestingly evoked emotional response in me to write this post. I have been around long enough [...]]]></description>
			<content:encoded><![CDATA[<p>A long haul in posts (at least by my standards) was basically due to combination of work schedule, &#8220;other things&#8221; (don&#8217;t ask <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). For past couple of weeks I have had my code reviewed by some people, which interestingly evoked emotional response in me to write this post. I have been around long enough (hopefully <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) to know what code reviews can do to a developer whose code is being reviewed. More often than not, it turns out that code reviews are a one-on-one sparing match between reviewer and the developer him/herself.</p>
<p>Keeping in  my traditional approach, lets define what a code review is, (taken from Wikipedia off course):</p>
<blockquote><p>
Code review is systematic examination (often as peer review) of computer source code intended to find and fix mistakes overlooked in the initial development phase, improving both the overall quality of software and the developers&#8217; skills.
</p></blockquote>
<p>Types of Code reviews :</p>
<ol>
<li><b>Fagan Inspections:</b>
<p>This was more or less formalized by Michael Fagan. The essence of Fagan inspections lies in comparing output of minuscule operation to the so called &#8220;exit-criteria&#8221; already defined or comparing with output requirements as defined earlier in requirement gathering process. This kind of review makes a lot of sense in keeping the code on track for the end result software product. More often than not, in their ever increasing quest for developing &#8220;cool&#8221; software developers tend to overlook requirements specifications. The idea is to verify (at each step in an iteration) functional aspects of what is being developed, assigned to individual developers. For example if Sam is working on &#8220;search&#8221; aspect of the system (I am using Non Programming language on purpose), Is he following what is &#8220;required&#8221; ?, Is the requirement being &#8220;met&#8221; by what he has written? &#8230; by asking those kinds of questions and validating the code; the end product becomes bug resistant (It obviously can never be Bug free <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). The important piece of the puzzle is to do this in smaller iterations and not at the end of development iteration, where developer has worked on a size able block of code already. If the code written is working and is meeting the functional requirements, it seems that fagan inspections would pass through. In &#8220;real&#8221; world this is off course only one side of the story. More often than not the requirements are not the ONLY factor in doing inspections; sometimes inspections can yield a &#8220;possible&#8221; crack through in the code which off course leads to more rework.  A typical Inspection process involves <i> Planning &#8212;>  Overview &#8212;> Preparation &#8212;> Inspection &#8212;> Rework &#8212;> Follow up.</i></p>
</li>
<li><b> Informal / Traditional Code reviews :</b>
<p> Developers meet one on one, and sit down side by side, to inspect each line of code, and review happens by asking questions; like &#8220;Why is this being done in this way and not &#8220;that&#8221; way? &#8230; Often these kinds of reviews evoke emotional responses from both the developers involved.  ( for more read this great article : <a href="http://www.developer.com/java/other/article.php/3579756">Code Reviews without much pain!</a>). In most cases developers involved are emotionally involved with the code that they write, hence it becomes very important to criticize their code very carefully and not to go overboard about the cynicism. As you would read in the link, More often a senior developer will be reviewing a junior developer&#8217;s code, if that is the case, it is of paramount importance that senior developer shoulder&#8217;s the responsibility of reviewing code in a &#8220;constructive&#8221; manner drawing a line between what is &#8220;required&#8221;, what is &#8220;right&#8221; way, what is officially &#8220;correct&#8221; way of doing things. In many cases, (as I have seen in the past and seeing now) developers will often be asked to rework their stuff for the sake of being &#8220;consistent&#8221;. Understandably that makes the code more readable and maintainable, but more often developers will be reluctant to refactor their code to more OO unless it is absolutely necessary, therefore when i say &#8220;Careful&#8221; i really mean careful in the sense that review should not hinder the overall project time lines. It is very easy to sit there and be an architect stating what could have been done in a better way, than actually refactoring it (by refactoring I meant making it Object oriented yet not breaking functional aspects of the system). Utmost care has to be taken to pass on judgments on what others are writing or doing. In XP world, code reviews form an essential aspect for each iterations to allow a healthy product to move forward. Under pressure deadlines, it is very important to have a few quick sessions (without laying out all the things that &#8220;You&#8221; want as opposed to what &#8220;ALL&#8221; people would agree upon) in which decisions are taken about what is acceptable and what is not. It is VERY VERY important that decision is made by keeping at least 80% of the team happy. This I am speaking from experience; Before my current project, the place where i worked at, code reviews were done at a very late stage, there was an excel sheet that was sent out to the entire team to make changes at Class level. (stating Line Number, methods where the problem is). This is obviously not a good approach, since it can be very annoying for developers who will have to refactor their code at such a late stage in the game, when &#8220;functional&#8221; aspects are already covered. </p>
</li>
</ol>
<p>
Needless to say, code reviews form an important aspect in software development. In doing code reviews aside from emotional aspects, utmost care has to be taken to avoid being &#8220;obsessive&#8221; about style of the code. You can enforce a formatting standard by using common XML or something similar ( depends on platform, I am speaking from Eclipse /IDEA/ Rational Application Developer perspective off course), but that should be the end of it. I have seen this happen in many code reviews where some people prefer somethings written in some ways , for example I usually prefer my If-ELSE constructs leave a line in between (I took this approach from someone just a year back, because that made my own code readable); Now this still adheres to the coding standards / format of the common formatting XML, but reviewers who have their own style of writing the code will often want to enforce that style in the code that they are reviewing. This is obviously a nuisance in the code review process. As i said earlier, utmost care has to be taken to draw a line as where you would want to stop and look at what would be advantages of doing things in such a way. In my experience, If a developer writes code in a certain way, but is a stickler for certain types of constructs (still adhering to a common formatting standard), he/she should be allowed to be at that. Enforcing things that &#8220;YOU&#8221; as a developer want can prove to be decisively spoiling relationships in team dynamics. (I have had this kind of experience in almost every project now, where a senior developer wants code to look in a certain way and then he goes over board in enforcing it.).</p>
<p>
Code inspection and reviews  can be enforced with some of Version Control systems. Especially with products like <i>&#8220;All Fusion Harvest Change Manager&#8221;</i> (now it is renamed to something else), where packages are assigned to be promoted to other stages in a project (for example DEVELOPMENT &#8212;> QA / TEST stage) only when they have passed code reviews assigned by developers. Again, developers developing the code might want to check in their code and test it out on the live server without wasting their time waiting on code reviews (if the reviewer is not available), in such cases , they would still be able to do so with systems like Harvest. In my experience and opinion version control system should be used for checking in &#8220;functional&#8221; code until you reach a logical point where things are working. A non working code or breaking code checked in can be hazardous to the team. In projects where maven is used, Test First (TDD) approach can be very annoying. especially when developers write test cases which off course are broken because the functional pieces for which tests were written are not in working condition. So a simple mvn clean install (used for building projects, more on Maven later). would not work for the entire team, because test cases are executed and they would be fail, off course one can skip the tests altogether but still.  In this respect, a checked in functional piece, however small it might be, can be guaranteed to work since it passes the test. In such cases a code review for such piece of code becomes irrelevant, unless off course as i said in my previous passages people want to play one-on-one tag matches with each other. </p>
<p>
Teams working on projects with stringent deadlines often tend to overlook importance of code reviews. Code reviews can go a long way in eliminating certain kinds of errors / bugs and make code look more consistent and maintainable, provided off course a well thought off plan is executed. Cynics have often pointed out to me that in XP world, code reviews are not needed at all, since doing pair programming can eliminate the need for that. True only for 1% times in my opinion. I am not a pair programming basher, but i do feel sometimes that senior developers will often do almost most of the coding or thinking part, which means that junior developers will not think or grow while writing their code. Constructive pair programming means listening to others and pointing juniors out in right direction &#8230; This off course is too generic or subjective and almost always doesn&#8217;t work. In my experience, pair programming will only help those developers who are &#8220;just starting out&#8221;, for people who have been working for sometime, if and when paired with people who have been in the business for years can be disastrous. Disastrous in the sense that it can often create friction between two passionate programmers who know their stuff and turn pair programming into knowledge matches; this is obviously not good for the team and for the future efforts.</p>
<p>All in all code reviews form crux of every organization, they help in fixing issues that might arise in maintenance  phase which off course are costlier and time consuming to fix than in development phase itself. Beyond not meeting functional requirements, code reviews can help in finding out potential performance bottle necks as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/05/04/ever-controversial-and-sometimes-annoying-code-reviews/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Abuses of DTO pattern in Java world</title>
		<link>http://anirudhvyas.com/root/2008/04/19/abuses-of-dto-pattern-in-java-world/</link>
		<comments>http://anirudhvyas.com/root/2008/04/19/abuses-of-dto-pattern-in-java-world/#comments</comments>
		<pubDate>Sat, 19 Apr 2008 01:05:35 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://anirudhvyas.com/root/2008/04/19/abuses-of-dto-pattern-in-java-world/</guid>
		<description><![CDATA[ Basics

I have to go on a detour for bit (from elegant visitor to strategy pattern to DI &#8230; ) to something that most of the Java people are familiar with; Data Transfer Object, or most commonly known as a DTO. The reasons for this detour are related to something i have been playing with [...]]]></description>
			<content:encoded><![CDATA[<p><strong> Basics</strong></p>
<hr /></hr>
<p>I have to go on a detour for bit (from elegant visitor to strategy pattern to DI &#8230; ) to something that most of the Java people are familiar with; <strong>D</strong>ata <strong>T</strong>ransfer <strong>O</strong>bject, or most commonly known as a DTO. The reasons for this detour are related to something i have been playing with for a while (i&#8217;ll ellaborate in later posts). First of all keeping with my tradition of referring definitions, here&#8217;s what wikipedia has to say about a DTO :</p>
<blockquote><p>
Data Transfer Objects (DTO), formerly known as Value Objects or VO, are a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with Data Access Objects to retrieve data from a database.<br />
The difference between Data Transfer Objects and Business Objects or Data Access Objects is that DTOs do not have any behavior except for storage and retrieval of its own data (accessors and mutators).
</p></blockquote>
<p>Not much insight but still, it explains it in a nutshell. A data transfer object was born to reduce the number of calls through wire in an atypical multi tiered architecture. Usually at the server end there would be an assembler which takes care population of data etc. If anyone of you have ever worked with pre EJB 3.0 days, you would know why they used DTOs. Basically the idea was that an Entity bean would typically expose a method that would copy its entire state into an object that could be serialized. Now this object could be used<br />
by any client in whatever manner needed. Typically code would be something like :</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<pre>
public class CustomerEntityBean implements javax.ejb.EntityBean{

   public CustomerDTO  getCustomerDTO( ){
        // prepare a customer DTO with First Name.
        return new CustomerDTO(this.getFirstName());
   }

}
</pre>
</div>
<p>
Nothing special going on in there, except that customer DTO constructor is called with getFirstName( ) method of the bean being called to allow for populating the customer DTO. In EJB 3 you are saved from doing all this (or so they say <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ) because your entities are detachable (in the sense that they are not ALWAYS managed by the container), so essentially they behave like DTOs when in &#8220;detached state. There are DTOs and then there are something called Value objects. Often both are used interchangeably. Although this is not true. For two DTOs the equality is based on object identity, whereas two value objects are equal in terms of their state. By this i mean for example two customers are equal if : their customer id AND OR customer Name is equal. For two value objects to be equal you can have all properties or subset of properties that uniquely identify each of them dictate the equality. (overriding equals)
</p>
<p>
A good example of Value object would be Date, for example something like 11/11/2011 is value object, as you can make out it is:</p>
<ul>
<li>Immutable</li>
<li>If i have multiple copies of this date, all the copies would be equal</li>
</ul>
<p>A value object should always override equals method. ( refer to : <a href="http://c2.com/cgi/wiki?ValueObject">Value Object </a> for more details ) . A DTO on the other hand is just used as a mutable object. Their equality is based on object identity rather than state identity as stated earlier. (CustomerVO vs CustomerDTO, VO = Value Object).  Although this example is admittedly lousy because ideally i would want to keep my value objects very simple, like a Date for example (as opposed to a Customer).</p>
<p> Apart from all of this lets keep things even more clear, throughout the course of this blog I would be using the term <b><i>Model</i></b> for representation of &#8220;actual&#8221; data to be retrieved or persisted. In Hibernate terms the Model is a &#8220;Model&#8221; of what lies in database or what will lie in database (Talk about puns <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ).
</p>
<p><strong>Abuses</strong></p>
<hr /></hr>
<p>Throughout its long history DTO has been utilized for all kinds of purposes. In EJB days usually the mantra was to use them for making expensive three tiered calls easier, but times have changed since pre-historic EJB 1.x days. While it does make a lot of sense today why DTOs were needed originally, in today&#8217;s world people are simply abusing the term and pattern in their projects mostly. (I am speaking from experience off course, I don&#8217;t claim that everyone is doing this, before someone jumps a gun on me <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ). Some of the common blunders / mistakes / abusive usage is :</p>
<ol>
<li>Using DTOs to pass the data within the tier </li>
<li> Using DTOs inter changeably with Value Objects</li>
<li> Using DTOs to compose other DTOs and finally using one huge DTO for display (it sounds horrifying and dreamy, but i have seen this happen) </li>
</ol>
<p>Lets tackle each one of those abuses one by one, as first one says, there is quite often the case for passing DTOs around simply because parameters are too much in one method call. While this might be a more object oriented approach, but it doesn&#8217;t justify the usage of a DTO for this. If there are two many parameters sitting independently, may be it is required that they all be composed into <b>One Model class</b> and then passed around. If the method that is being called exists in a separate tier (lets assume that tiers are not even in different VMs for now) only THEN should a DTO be considered for usage.</p>
<p>The second one is pretty self explanatory; Value objects being immutable are often used interchangeably with DTOs, while this is not a pain for much of the time, but still as a purist you&#8217;d want to see Value objects being used for what they are.</p>
<p>Finally, In couple of cases I have seen people do this : They compose DTOs with a DTO to transfer some data and retrieve it as a matter of convenience, Although it is not harmful in any sense, One should refrain from composing DTOs within a DTO (as opposed to a <b> Model</b> within a DTO) a DTO can have n number of models, it can have n number of lists, but if we are adding DTOs within a DTO, it tells me that we want to use Outer DTO as a shuttle to transfer Inner DTO because of some stringent need. I don&#8217;t think that plays out really well with a good design.</p>
<p>It is sometimes hard to point out why DTO can be such an anti pattern sometimes (I know a lot of folks believe that it is, but unfortunately i am not one of them.) I have been working on a project that uses a very interesting commons framework, that glorifies the DTO pattern to its most simple, most elegant and pure roots (Which is why I am proud to be part of this project <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> ). I&#8217;ll elaborate on this later. Its a matter of personal taste as to how we write our code, however thinking what is intended use for what you are doing can go a long way in simplifying things for us.</p>
<p>Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/04/19/abuses-of-dto-pattern-in-java-world/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A much better Strategy Pattern - Part II</title>
		<link>http://anirudhvyas.com/root/2008/04/05/a-much-better-strategy-pattern-part-ii/</link>
		<comments>http://anirudhvyas.com/root/2008/04/05/a-much-better-strategy-pattern-part-ii/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 01:29:19 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

		<guid isPermaLink="false">http://anirudhvyas.com/root/2008/04/05/a-much-better-strategy-pattern-part-ii/</guid>
		<description><![CDATA[
So in the last post i talked about how i could make it better with slight twist. Well for those of you who don&#8217;t know what Dependency Injection is read :
Dependency Injection By Fowler. Lets get started. To give you a little refresher, In my last post we discussed, Strategy pattern briefly (refer to : [...]]]></description>
			<content:encoded><![CDATA[<p>
So in the last post i talked about how i could make it better with slight twist. Well for those of you who don&#8217;t know what Dependency Injection is read :<br />
<a href="http://martinfowler.com/articles/injection.html">Dependency Injection By Fowler</a>. Lets get started. To give you a little refresher, In my last post we discussed, Strategy pattern briefly (refer to : <a href="http://anirudhvyas.com/root/2008/04/02/a-much-better-strategy-pattern/"> Strategy Pattern - Part I</a>), we create an IStrategy interface ( with operation method in it, taking two parameters (arguments at runtime). and implemented couple of simple operation-al strategies like SumStrategy (which performs sum in operation implementation), similarly we created MultiplicationStrategy, DivisionStrategy etc. We had a Context on which we set the strategy (context.setStrategy(IStrategy strategy)) and voila we are done, we can isolate each algorithm to its own object. </p>
<p>As may be evident from above, this is not completely flexible approach. Especially because i am doing (as a client) something like context.setStrategy(new DivisionStrategy) or something in those lines. So client &#8220;knows&#8221; about the the strategy really; and our code is tied up in that sense &#8230;</p>
<p>So first lets setup Dependency Injection container. a method setUp( ) demonstrates that below.</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
public static void setUp(Class&lt;? extends IStrategy&gt;  ... strategies){</p>
<p>		for(Class&lt;? extends IStrategy&gt; strategy : strategies){</p>
<p>			System.out.println("( Strategy Interface ) ---> ( " + strategy.getSimpleName() + " )");</p>
<p>			// prepare the type Map ...<br />
			typeMap  = new StrategyTypeMap();</p>
<p>			// prepare the value list<br />
			List<Class&lt;? extends IStrategy&gt;&gt; valueList = new ArrayList&lt;Class&lt;? extends IStrategy&gt;&gt;();</p>
<p>			valueList.add(DivisionStrategy.class);<br />
			valueList.add(MultiplicationStrategy.class);<br />
			valueList.add(SumStrategy.class);</p>
<p>			// configuration complete.<br />
			typeMap.configureTypeMap(strategy, valueList);</p>
<p>		}</p>
<p>	}<br />
</code>
</div>
<p>Lets break the code down in steps and look at it closely. In setting our CustomDIContainer, we use a typeMap (we&#8217;ll talk about that in a bit), we simply loop through classes passed to the method, add the classes to list and finally insert the entry in the Map. This map is a specialized Type map which takes in a Key (which in our case is IStrategy Interface) and a valueList in form of Classes that implement the Key Interface. So we have strategies that are being added here.</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
    public static IStrategy getImplementation(Class&lt;? extends IStrategy&gt; key, String typeToGet){</p>
<p>		// notice how i pass things around here ... be careful ... read this before you proceed!<br />
		return instantiateImplementation(getAppropriateImplementation(key, typeToGet));<br />
	}</p>
<p>	private static Class&lt;? extends IStrategy&gt; getAppropriateImplementation(Class&lt;? extends IStrategy&gt; key, String typeToGet){</p>
<p>		List&gt;Class&lt;? extends IStrategy&gt;&gt; searchList = getCollection(key);</p>
<p>		if(typeToGet.trim().equalsIgnoreCase("DIVISION")){<br />
			Class&lt;? extends IStrategy&gt; returnType = null;</p>
<p>			for(Class&lt;? extends IStrategy&gt; classType : searchList){</p>
<p>				if(classType.isAssignableFrom(DivisionStrategy.class)){<br />
					returnType = classType;</p>
<p>				}</p>
<p>			}</p>
<p>			// return<br />
			return returnType;</p>
<p>		}else if(typeToGet.trim().equalsIgnoreCase("SUM")){<br />
			Class&lt;? extends IStrategy&gt; returnType = null;</p>
<p>			for(Class&lt;? extends IStrategy&gt; classType : searchList){</p>
<p>				if(classType.isAssignableFrom(SumStrategy.class)){<br />
					returnType = classType;</p>
<p>				}</p>
<p>			}</p>
<p>			// return<br />
			return returnType;</p>
<p>		}else if(typeToGet.trim().equalsIgnoreCase("MULTIPLICATION")){<br />
			Class&lt;? extends IStrategy&gt; returnType = null;</p>
<p>			for(Class&lt;? extends IStrategy&gt; classType : searchList){</p>
<p>				if(classType.isAssignableFrom(MultiplicationStrategy.class)){<br />
					returnType = classType;</p>
<p>				}</p>
<p>			}</p>
<p>			// return<br />
			return returnType;</p>
<p>		}else{</p>
<p>			// return finally<br />
			return  DivisionStrategy.class;<br />
		}</p>
<p>	private static IStrategy instantiateImplementation(Class&lt;? extends IStrategy&gt; key){</p>
<p>		IStrategy returnStrategy = null;</p>
<p>		try {</p>
<p>			returnStrategy =  key.newInstance();</p>
<p>		} catch (InstantiationException e) {<br />
			e.printStackTrace();</p>
<p>		} catch (IllegalAccessException e) {<br />
			e.printStackTrace();</p>
<p>		}</p>
<p>		// return<br />
		return returnStrategy;<br />
	}<br />
</code>
</div>
<p>^^ Wow this is a huge block of code to digest; but lets break it into pieces and make it a little easy. Basically we are trying to get Implementation for the IStrategy interface we pass in (It could have been other interface as well, but lets not worry about it at the moment). Now :</p>
<ol>
<li>We get an appropriate Implementation  by looping through the list of classes for a key (IStrategy in our case) and using String passed in (like DIVISION, MULTIPLICATION) etc to distinguish between the values (that is Implementation classes) and return one. So like for example in first If construct we search for a DIVISION key (Client has to perform DIVISION so Division IT WILL! <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ), we check if (one by one in the loop for all values) whether its assignable to DivistionStrategy.class or not, if so, we simply return the class type, same goes for SUM and other operations. </li>
<li>in instantiate, we simply create instance of the class  (apparently) and return back. Notice, though that return type and parameter types are IStrategy and ? extends IStrategy class, so for client its just IStrategy or any interface like that for that matter and simply the String giving container the type of operation it wants to perform. </li>
</ol>
<p>Next, we populate our good old <strong>Context</strong>;</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
public static Context populateContext(String typeToGet){</p>
<p>		Context context = Context.getInstance();<br />
		context.setStrategy(getImplementation(IStrategy.class, typeToGet));</p>
<p>		// return<br />
		return context;<br />
	}<br />
</code>
</div>
<p>Finally here is our much improved TestWithDI (compare this with <a href="http://anirudhvyas.com/root/2008/04/02/a-much-better-strategy-pattern">Strategy Pattern Part - I</a> example and you will know what i meant when i said, cleaner approach).</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
public static void main(String[] args) {</p>
<p>		// SETUP THE DI CONTAINER<br />
		CustomDIContainer.setUp(IStrategy.class);</p>
<p>		// define  context using SUM<br />
		Context context = CustomDIContainer.populateContext("SUM"); // <-- Notice how we do a SUM! no more new SumStrategy in setter of context ...<br />
		Integer result = (Integer)context.getStrategy().operation(400, 200);<br />
		System.out.println("( Result of the SUM with DI was  ) ---> ( &#8221; + result + &#8221; )&#8221;);</p>
<p>		// define  context using Multiplication<br />
                //  Notice how we do a MULTIPLICATION! No more new Multiplication in setter    of context &#8230;<br />
		Context multiplicationContext = CustomDIContainer.populateContext(&#8221;MULTIPLICATION&#8221;);<br />
		Integer multiplicationResult = (Integer)multiplicationContext.getStrategy().operation(400, 200);</p>
<p>                //log<br />
		System.out.println(&#8221;( Result of the MULTIPLICATION with DI was  ) &#8212;> ( &#8221; + multiplicationResult + &#8221; )&#8221;);</p>
<p>		// define  context using Dviision<br />
                 //  Notice how we do a DIVISION! no more new SumStrategy in the setter of context &#8230;<br />
		Context divisionContext = CustomDIContainer.populateContext(&#8221;DIVISION&#8221;);<br />
		Integer divisionResult = (Integer)divisionContext.getStrategy().operation(400, 200);</p>
<p>                //log<br />
		System.out.println(&#8221;( Result of the DIVISION with DI was  ) &#8212;> ( &#8221; + divisionResult + &#8221; )&#8221;);</p>
<p>	}<br />
</code>
</div>
<p>Finally note that in setUp( ) method we <strong>Will</strong> have to add our Interfaces and implementations for our Oh so Hot DI container  <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> . We can move this configuration to XML too, although XML approach can be unreliable because if i or any other developer removes any thing (any interface or alike implementations) your code will fail. (We&#8217;ll explore the DI concept in later posts). Also this Dependency injection is not a full dependency injection demonstration, as you might notice that i am using populateContext explicitly, normally i should be able to do something like context.load() which will load and wire all dependencies for me, which if i add Context as a bean in our setUp of DI container, i could wire the context attribute for implementing strategy very easily, (As a rough idea to you guys (I will explore this concept later on), you add context to a list of dependencies managed by the container, when container loads the Class, it finds that it has an outside dependency, so it will run a check on its list, if it has the class type which is required to populate this setter field, it will do so. I wanted to make concept more clear so i didnt add those things up here.</p>
<p>Next we will take a look at Improvising our visitor pattern in removing &#8220;accept&#8221; method and making it more flexible through Generics. ( For continuation purpose; here&#8217;s the link:<br />
<a href="http://anirudhvyas.com/root/2008/03/20/visitor-pattern-elegance-work/">Visitor Pattern - Part I</a>. Speaking of generics, we can use Generics to improve the above code too &#8230; but thats for another time of the day.</p>
<p>Stay Tuned ! and thanks for your visits. <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/04/05/a-much-better-strategy-pattern-part-ii/feed/</wfw:commentRss>
		</item>
		<item>
		<title>A much better Strategy Pattern</title>
		<link>http://anirudhvyas.com/root/2008/04/02/a-much-better-strategy-pattern/</link>
		<comments>http://anirudhvyas.com/root/2008/04/02/a-much-better-strategy-pattern/#comments</comments>
		<pubDate>Wed, 02 Apr 2008 02:19:33 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

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

		<guid isPermaLink="false">http://anirudhvyas.com/root/2008/04/02/a-much-better-strategy-pattern/</guid>
		<description><![CDATA[In words of Gang Of Four design patterns Book and from Wikipedia, definition of Strategy Pattern is as follows :

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.The strategy pattern is useful for situations where it is necessary to dynamically swap [...]]]></description>
			<content:encoded><![CDATA[<p>In words of Gang Of Four design patterns Book and from Wikipedia, definition of Strategy Pattern is as follows :</p>
<blockquote><p>
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
</p></blockquote>
<p>As i always do, i believe in writing code rather than writing passages of theory. First I will show Simple implementation of strategy and compare it with What it my code would look like without strategy pattern, then i will tell you guys how to tweak my Strategy pattern to allow removal of some of the &#8220;hard wired&#8221; initializations. So lets get on with it, we&#8217;ve got a lot of ground to cover.</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
public interface IStrategy extends Serializable{</p>
<p>	public Object operation(Object firstOperand, Object secondOperand);</p>
<p>}<br />
</code>
</div>
<p>Once again to keep things simple, i have stripped all java documentation etc. (And not to mention that it somehow breaks the flow on Word press). So as you can make out, we have a strategy interface; It has one method namely operation which takes two operands. The &#8220;Whats&#8221; and &#8220;Hows&#8221; of operation are left to implementors. This strategy helps in isolating the algorithm itself and allows it be to implemented in different ways. If you ask me, by now you might already know what strategy pattern is, but devil is in the details as they say.</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code></p>
<p>public class MultiplicationStrategy implements IStrategy {</p>
<p>	private static final long serialVersionUID = 1L;<br />
	private static final int VALUE_ZERO = 0;</p>
<p>	/**<br />
	 * {@inheritDoc}<br />
	 *<br />
	 */<br />
	public Object operation(Object firstOperand,<br />
                                        Object secondOperand) {</p>
<p>		Integer opOne = VALUE_ZERO;<br />
		Integer opTwo = VALUE_ZERO;</p>
<p>		if (firstOperand instanceof Integer<br />
                         &#038;&#038; secondOperand instanceof Integer) {</p>
<p>			opOne = castOperand(firstOperand);<br />
			opTwo = castOperand(secondOperand);</p>
<p>		}</p>
<p>		// return the sum of two integer<br />
		return multiplyOperands(opOne, opTwo);<br />
	}</p>
<p>	// casts the operand without checking anything<br />
       //... this assumes that a check was made already<br />
	private final Integer castOperand(final Object firstOperand) {<br />
		Integer opOne;<br />
		opOne = ((Integer) firstOperand);</p>
<p>		// return here<br />
		return opOne;<br />
	}</p>
<p>	// multiplies two operands.<br />
	private final int multiplyOperands(final Integer opOne,<br />
                                                    final Integer opTwo) {<br />
		return opOne * opTwo;<br />
	}</p>
<p>}<br />
</code>
</div>
<p>^^ The above is an implementation of IStrategy, likewise (without showing any further strategies) assume that we have SumStrategy, DivisionStrategy. (Division will off course have that divide by 0 logic etc. but thats not our concern).</p>
<p>Next we have something called a <strong> Context</strong> now context class holds a reference to a IStrategy type with a setter and a getter for the same. This context will later be used to tie a strategy to applied in a particular scenario. ( For example if client wants to multiply two numbers, a multiplication strategy will be set on this class and so on ).</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
public class Context {</p>
<p>	private IStrategy strategy;<br />
	private static int counter = 0;</p>
<p>	// private constructor.<br />
	private Context(){<br />
	}</p>
<p>	/**<br />
	 * returns the context instance<br />
         * initialized with Strategy type.<br />
	 *<br />
	 * @param strategy<br />
	 *		strategy instance to be set for this context.<br />
	 *<br />
	 * @return context<br />
	 *		 singleton context instance<br />
	 */<br />
	public static Context getInstance(){</p>
<p>		// return instance<br />
		return new Context();<br />
	}</p>
<p>	/**<br />
	 * gives the strategy for this context.<br />
	 *<br />
	 * @return strategy<br />
	 * 			the strategy to get<br />
	 */<br />
	public IStrategy getStrategy() {</p>
<p>		if(counter == 0){<br />
			throw new IllegalStateException(" initialization of context not complete...");</p>
<p>		}</p>
<p>		// return<br />
		return strategy;<br />
	}</p>
<p>	/**<br />
	 * sets the strategy for this context.<br />
	 *<br />
	 * @param strategy<br />
	 * 			strategy to be set.<br />
	 */<br />
	public void setStrategy(IStrategy strategy) {<br />
		this.strategy = strategy;<br />
		counter++;</p>
<p>	}<br />
</code>
</div>
<p>Now for the real deal, lets see how client invokes the same and how everything falls in place.</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
public class Test {</p>
<p>	/**<br />
	 *<br />
	 *<br />
	 * @param args<br />
	 * 		arguments to be passed.<br />
	 *<br />
	 */<br />
	public static void main(String[] args) {</p>
<p>		// $Id - Step 1 : get the Context instance and pass in Strategy type.<br />
		Context context = Context.getInstance();</p>
<p>		// $Id - State ( Context ) : division strategy being set<br />
		context.setStrategy(new DivisionStrategy());</p>
<p>		// perform the operation :<br />
               //Notice that i am not calling any specific operations ( like sum( ) or division( ) etc.)<br />
		Integer result = (Integer)context.getStrategy().operation(400, 200);</p>
<p>		// print<br />
		System.out.println("( Result of Division strategy was ) --> ( " + result + " ) ");</p>
<p>		// $Id - Step 2 : get the Context<br />
               // instance and pass in Strategy type.<br />
		Context sumContext = Context.getInstance();</p>
<p>		// $Id - State ( Context ) : Sum strategy being set<br />
		sumContext.setStrategy(new SumStrategy());</p>
<p>		// perform the operation<br />
              //  Notice that i am not calling any specific<br />
              // operations ( like sum( ) or division( ) etc.)<br />
		Integer sumResult = (Integer)sumContext.getStrategy().operation(400, 200);</p>
<p>		// print<br />
		System.out.println("( Result of Sum strategy was ) --> ( " + sumResult + " ) ");</p>
<p>		// $Id - Step 3 : get the Context instance and pass in Strategy type.<br />
		Context multiplyContext = Context.getInstance();</p>
<p>		// $Id - State (Context) : Multiplication<br />
		multiplyContext.setStrategy(new MultiplicationStrategy());</p>
<p>		// perform the operation<br />
               // Notice that i am not calling<br />
              //  any specific operations ( like sum( ) or division( ) etc.)<br />
		Integer multiplyResult = (Integer)multiplyContext.getStrategy().operation(400, 200);</p>
<p>		// print<br />
		System.out.println("( Result of Multiplication strategy was ) --> ( " + multiplyResult + " ) ");</p>
<p>	}<br />
</code>
</div>
<p>Here&#8217;s what we are doing above in a nutshell :</p>
<ol>
<li> Initialize the context </li>
<li> Set the strategy </li>
<li> get the strategy that was set and perform operation </li>
</ol>
<p>Whats the difference you may ask? well for one, As a client i only used operation( ) and nothing like Multiplication or division etc. (Off course i can think of dozens of other better examples than above, but simplicity is the key to understanding the concept).</p>
<p>Now It is really easy to see what my code would be like without using a strategy, in a nutshell it would be something like :</p>
<div style="background-color:#faebd7;color:black;font-size:11px;">
<code><br />
class Test{<br />
....<br />
 main(String[] args){</p>
<p>client.performOperation("OPERATION_TYPE");</p>
<p>}</p>
<p>...</p>
<p>performOperation(String operationType){</p>
<p>if(operationType.trim().equalsIgnoreCase("blah_blah){<br />
       // do blah blah operation</p>
<p>}else if(operationType.trim().equalsIgnoreCase("blah){<br />
      // do blah blah blah operation</p>
<p>}</p>
<p>... // and so on<br />
}</p>
<p>}<br />
</code>
</div>
<p>One can obviously see separation of concerns here and cleanliness in the code. But thats not all &#8230; Somehow i don&#8217;t find my strategy pattern satisfying. To me, we are using (in setting Strategies in context as you may recall, refer above if you don&#8217;t), but before using them we do an explicit set. But thats not what i want. I want something to wire this dependency on fly based on some criteria given by the client. (.A.K.A Dependency Injection ). I&#8221;ll show how to do that and modify the above to test to make it much better &#8230; so stay tuned! <img src='http://anirudhvyas.com/root/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/04/02/a-much-better-strategy-pattern/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Visitor Pattern : Elegance @ Work</title>
		<link>http://anirudhvyas.com/root/2008/03/20/visitor-pattern-elegance-work/</link>
		<comments>http://anirudhvyas.com/root/2008/03/20/visitor-pattern-elegance-work/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 04:30:08 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Design Patterns]]></category>

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

		<guid isPermaLink="false">http://anirudhvyas.com/root/?p=6</guid>
		<description><![CDATA[Brief Background:

Visitor pattern arose from the need to handle different &#8216;kinds&#8217; of data in a collection differently by some class; for example a list could have Strings, other Lists etc. In such a scenario; you&#8217;d end up writing instanceof checks (ugly); This example of handling different kinds of data in a collection might not be [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Brief Background:</strong><br/></p>
<p>
Visitor pattern arose from the need to handle different &#8216;kinds&#8217; of data in a collection differently by some class; for example a list could have Strings, other Lists etc. In such a scenario; you&#8217;d end up writing instanceof checks (ugly); This example of handling different kinds of data in a collection might not be the best; but just bear with me for the moment. (I mention this different type thing because i will give a &#8216;generified Visitor pattern example in next post).
</p>
<p><br/><br />
I believe in posting code and getting down to it; its like the source talks to me, saying all kinds of things that went in developer&#8217;s head while he was writing it. I had to strip Comments and javadocs out of this, because for some strange reason it seemed to break the post; I&#8217;ll post the files / project instead if someone asks for it.</p>
<p>Lets get on with it! <br/></p>
<div style="background-color:#faebd7;color:black;">
public interface IVisitable extends Serializable {</p>
<p>	public void accept(IVisitor visitor);</p>
<p>}
</p></div>
<p>The above is an interface for abstracting all visitable objects. A visitable object could be anything visitor &#8216;visits&#8217;; Typically vistable object (like a Destination for example) &#8216;accepts&#8217; a visitor and calls visitor.visit(this) in accept method to delegate the responsibility of handling the logic for this visitation. (excuse the pun, i am a poor writer i guess).</p>
<div style="background-color:#faebd7;color:black;">
public interface IVisitor extends Serializable {</p>
<p>	public void visit(IVisitable visitable);</p>
<p>}
</p></div>
<p>^^ A visitor interface that All visitors must implement. A visitor visits a &#8216;Visitable&#8217; object (which in turn &#8216;accepts&#8217; its visit) and calls this method to let the visitor handle business logic.</p>
<p>To understand and make it all concrete; lets consider a classic Transaction example; where we need to handle two types of transactions; viz. Deposit Transaction; Withdrawal Transactions. I could accomplish this without visitor off course (It turns and looks ugly and Not very OO apparently but it can work, as i will show below). In our example assume that Transaction is a IVisitable type given below. <br/></p>
<div style="background-color:#faebd7;color:black;">
@SuppressWarnings(&#8221;serial&#8221;)<br />
public class Transaction implements IVisitable {</p>
<p>	private Integer type;</p>
<p>	public void accept(IVisitor visitor) {<br />
		visitor.visit(this);</p>
<p>	}</p>
<p>	public Integer getType() {<br />
		return type;<br />
	}</p>
<p>	public void setType(Integer type) {<br />
		this.type = type;<br />
	}</p>
<p>	@Override<br />
	public String toString() {<br />
		return &#8220;&#8221; + getType();</p>
<p>	}<br />
}
</p></div>
<p>Next we implement two kinds of visitors (each for handling the type of transactions viz Deposit, Withdrawal).</p>
<div style="background-color:#faebd7;color:black;">
@SuppressWarnings(&#8221;serial&#8221;)<br />
public class DepositVisitor implements IVisitor {</p>
<p>	public void visit(IVisitable visitable) {</p>
<p>		System.out.println(&#8221; Performing a deposit on &#8221; + visitable.toString());</p>
<p>	}</p>
<p>}
</p></div>
<p>Sounds naive, but hey! thats what my example tries to accomplish; elucidate concepts and not bloat the code.</p>
<div style="background-color:#faebd7;color:black;">
@SuppressWarnings(&#8221;serial&#8221;)<br />
public class WithdrawVisitor implements IVisitor {</p>
<p>	public void visit(IVisitable visitable) {</p>
<p>		System.out.println(&#8221; Performing withdrawal on &#8221; + visitable.toString());<br />
	}</p>
<p>}
</p></div>
<p>Next we create a visitor Factory which will be responsible for creating visitors; You will typically get hold of visitors using this. (I have not concentrated on making visitors singleton and other blah blah, i&#8217;ll leave that to you Java gurus out there).</p>
<div style="background-color:#faebd7;color:black;">
public class VisitorFactory {</p>
<p>	private static final Integer DEPOSIT = 100;<br />
	private static final Integer WITHDRAW = 200;</p>
<p>	private static VisitorFactory visitorFactory; </p>
<p>	private VisitorFactory(){<br />
		// Nothing here<br />
	}</p>
<p>	public static VisitorFactory getInstance(){</p>
<p>		if(visitorFactory == null){<br />
			visitorFactory = new VisitorFactory();</p>
<p>		}</p>
<p>		return visitorFactory;<br />
	}</p>
<p>	public IVisitor getVisitor(IVisitable visitable){</p>
<p>		IVisitor returnVisitor = null;</p>
<p>		if(((Transaction)visitable).getType().compareTo(DEPOSIT) == 0){<br />
			returnVisitor = new  DepositVisitor();</p>
<p>		}else if(((Transaction)visitable).getType().compareTo(WITHDRAW) == 0){<br />
			returnVisitor = new WithdrawVisitor();</p>
<p>		}else{</p>
<p>			// default visitor<br />
			returnVisitor = new DepositVisitor();</p>
<p>		}</p>
<p>		// return<br />
		return returnVisitor;<br />
	}</p>
<p>}
</p></div>
<p>Next; I illustrate the crux of the idea. I will first show how clean and flexible the code is, by showing A test case with VisitorPattern.</p>
<div style="background-color:#faebd7;color:black;">
public class ConcreteTestWithVisitorPattern {</p>
<p>	private static final Integer DEPOSIT = 100;<br />
	private static final Integer WITHDRAWAL = 200;</p>
<p>	public static void main(String[] args) {<br />
		Transaction tx = new Transaction();<br />
		tx.setType(DEPOSIT); // SETTING TYPE AS DEPOSIT &#8230; NOTICE HOW CLEAN THIS CODE LOOKS<br />
		processTransaction(tx);</p>
<p>		Transaction tx0 = new Transaction();<br />
		tx0.setType(WITHDRAWAL); // SETTING TYPE AS WITHDRAW &#8230; NOTICE HOW CLEAN THIS CODE LOOKS<br />
		processTransaction(tx0);</p>
<p>	}</p>
<p>	private static void processTransaction(Transaction tx) {<br />
		processTransaction(tx, VisitorFactory.getInstance().getVisitor(tx));<br />
	}</p>
<p>	private static void processTransaction(Transaction tx, IVisitor visitor) {<br />
		tx.accept(visitor);<br />
	}</p>
<p>}
</p></div>
<p>Notice that if i want to add another type of transaction visitor; i can do so easily (hook it up in factory) and delegate back to the same method. My &#8216;above code&#8217; remains the <strong>same</strong>.</p>
<p><strong>Now the Ugly code without the above pattern &#8230; =) </strong></p>
<div style="background-color:#faebd7;color:black;">
public class ConcreteTestWithoutVisitor {</p>
<p>	private static final Integer DEPOSIT = 100;<br />
	private static final Integer WITHDRAWAL = 200;</p>
<p>	public static void main(String[] args) {</p>
<p>		Transaction tx = new Transaction();<br />
		processTransaction(tx);<br />
	}</p>
<p>	public static void processTransaction(Transaction tx) {</p>
<p>		if(tx.getType() == DEPOSIT){<br />
			System.out.println(&#8221; Do the deposit &#8230;&#8221;);</p>
<p>		}else if(tx.getType() == WITHDRAWAL){<br />
			System.out.println(&#8221; Do the Withdrawal &#8230;&#8221;);</p>
<p>		}</p>
<p>	}</p>
<p>}</p>
</div>
<p>As you can make out it looks ugly; if i wanted to add another type of transaction; i&#8217;d have to add another if. While this is not such a strong example; it does show the concept of it. I can never imagine Wikipedia&#8217;s examples (they give a Car, Engine example) while it is a great example in every way; but i find it hard to directly apply the concept in daily work without the examples related to work i do. (thats the reason i hate Head First Design patterns book so much).</p>
<p><strong>State Maintenance</strong></p>
<p>
I should point out however that wikipedia stresses an important point pretty well. In &#8216;visiting&#8217; an IVisitable type; a visitor can maintain state of its previously visited IVisitable(s) and form a tree or graph of Nodes of sort. This can particularly useful if you want to form a tree structure and then modify the structure at a later stage to do some business process transformations.
</p>
<p>More To follow : &#8216;Generics&#8217; Version of the above.<br />
Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/03/20/visitor-pattern-elegance-work/feed/</wfw:commentRss>
		</item>
		<item>
		<title>JSR 305 : Movement towards Software defect detection within the Code</title>
		<link>http://anirudhvyas.com/root/2008/03/20/jsr-305-movement-towards-software-defect-detection-within-the-code/</link>
		<comments>http://anirudhvyas.com/root/2008/03/20/jsr-305-movement-towards-software-defect-detection-within-the-code/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 03:43:26 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://anirudhvyas.com/root/?p=4</guid>
		<description><![CDATA[Following are the notes / observations from video session (you can find video at google videos:
Google Video of JSR
I&#8217;ll express my opinion about Annotations over the course of next few posts ( I don&#8217;t like them personally; I will state my reasons later).
Core topics in Software development boils down to two things:
1.) How do you [...]]]></description>
			<content:encoded><![CDATA[<p>Following are the notes / observations from video session (you can find video at google videos:<br />
<a href="http://video.google.com/videoplay?docid=-1531727105949862857&#038;q=java&#038;total=25610&#038;start=10&#038;num=10&#038;so=0&#038;type=search&#038;plindex=9%29">Google Video of JSR</a><br />
I&#8217;ll express my opinion about Annotations over the course of next few posts ( I don&#8217;t like them personally; I will state my reasons later).</p>
<p>Core topics in Software development boils down to two things:<br />
1.) How do you write bug free / less bug prone code; meaning if you are writing a simple method for example doing something trivial as taking two arguments (i am saying arguments and NOT parameters) and dividing both; returns remainder of the division, you would want two things to happen in this case :<br />
•	  Both arguments are non null OR at the very least the denominator is NEVER null.<br />
•	 Even though arguments are not null, sometimes my arguments be of incompatible types &#8230;<br />
•	 How do you provide enough information about program behavior being predictible by using either tools or doing a &#8220;dry run&#8221; of the code (i.e. running code mentally).</p>
<p>Out of all of the above reasons; the general consensus is that &#8220;there is never enough information&#8221; for the compiler to &#8220;infer&#8221; things on its own by parsing the code and analyzing it. Therefore whereas additional information can be added on the behalf of the compiler, (like synthetic stuff in Java may be or something else) or annotations by users that go along with the code to provide some help as an add on info to compiler.<br />
Basic idea of an Annotations (for Non knowers):<br />
For those of you who are not familiar with annotations; i suggest you go through :<br />
<a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html%C2%A0">Annotations</a></p>
<p>For those of you coming from C#, you guys are already familiar with annotations I am guessing (I am looking for how it is in C# though, I am not familiar with it completely).<br />
In short for helping Java Compiler, you provide additional information for it to infer some things on its own using them. For example; you could write something like:<br />
@Test<br />
Public void testSomething( )</p>
<p>And the frameworks (frameworks like TestNG, JUNIT use the above), would simply use the above annotation to invoke this method as a test. (Yeah … for those of us who have done a bit of coding in past with JUNIT may agree that It was such a pain to stub out test cases by doing something like: public void _testSomething( ) to allow the framework to ignore it; but anyways)<br />
But the most common usage that comes to mind (it happens often) to some us is; wont it be great if we could have something like @NonNull or something of that sorts that provides compiler with enough information to infer and allow / disallow addition of certain values to a reference type or anything for that matter?<br />
JSR 305 addresses above issues and allows (as part of language) to add annotations in more places … ( like List<@NotNull String> for example). If there’s something that all of us as programmers want it is that method parameters being annotated with NotNull so that at some point some tool gives some warning that the value “might” be null as soon as it is de-referenced somewhere.<br />
3 Cases proposed:</p>
<ol>
<li>@NonNull – Should be non null, for fields should be non null when the object is initialized. Tools (following this spec, or implementing this spec) will try to generate a warning  when they see a possibly null value being used where a non-null value is required. (Note that all this happens at Compile time! Just to be clear; otherwise there’s no use of this tool or spec  </li>
<li>  @Nullfeasible – code should always worry about the fact that this value might be null. Tools will flag a warning whenever a de-reference is NOT preceded by a null check.</li>
<li> @UnknownNullness – default annotation, similar to having NO annotations at all. Reason they are going to that route, they would introduce default and inherited annotations (to </li>
<li>over-ride a default behavior, say for example for this package I don’t know anything about nullness, but oh! For a specific case I might need Null check.)</li>
</ol>
<p>Other suggestions include @NonNegative, @Signed, @NonSigned etc… work is still in progress.</p>
<p>Another interesting aspect that was discussed was to add something like: </p>
<div>
createStatement(ResultsetType, resultsetConcurrency, resultsetHoldibility)
</div>
<p>when you pass parameters in a different order, you get weird behavior at Runtime! Rather than compiler complaining about it, this is because all above “parameters” are integer types … (small ints!); so it doesn’t matter.<br />
The fix of this was pretty cool; you basically add @ResultSetType annotation (you must create such an annotation yourself and add this annotation to the method parameter that you want to typify ( for example in above I would write @ResultSetType annotation followed by resultSetType name) and the next time a programmer calls things in wrong order, well guess what compiler would complain!  (assuming that you add the @ResultSetType to small int static constants of ResultSetTypes you declared, which should have been an Enum in the first place.</p>
<p>For full details, refer to above video link.<br />
Regards<br />
Vyas, Anirudh</p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/03/20/jsr-305-movement-towards-software-defect-detection-within-the-code/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Apache Wicket : The greatest Java Web Framework Ever!</title>
		<link>http://anirudhvyas.com/root/2008/03/20/apache-wicket-the-greatest-java-web-framework-ever/</link>
		<comments>http://anirudhvyas.com/root/2008/03/20/apache-wicket-the-greatest-java-web-framework-ever/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 03:39:56 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Frameworks]]></category>

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

		<guid isPermaLink="false">http://anirudhvyas.com/root/?p=3</guid>
		<description><![CDATA[There has been a lot of confusion in Java Web world, as to what &#8220;will&#8221; work eventually with advent of so many Web Frameworks; each reinventing the wheel in some way or the other; trying to solve one problem ignoring others altogether.
I have accumulated fair amount of experience working with following frameworks ( UI / [...]]]></description>
			<content:encoded><![CDATA[<p>There has been a lot of confusion in Java Web world, as to what &#8220;will&#8221; work eventually with advent of so many Web Frameworks; each reinventing the wheel in some way or the other; trying to solve one problem ignoring others altogether.</p>
<p>I have accumulated fair amount of experience working with following frameworks ( UI / Web ): <br/></p>
<div style="background-color:#ffefd5;color:black;" align="left">
<ol>
<li>Struts 1.x ( Old, Stupid monolithic giant, which unfortunately many are still using).</li>
<li>JSF ( Component based framework; customization of components is a nightmare &#8230; Configuration files crap still exists)</li>
<li>Tapestry ( Great component based framework, best apart from Wicket )</li>
<li>Spring MVC -> Customizable, perhaps too much flexibility; </li>
<li> Struts 2.x -> Decent improvements over Struts 1.x but still the same with configuration files etc.</li>
<li>GWT ( Google Web Toolkit )&#8211;> great, but requires a separate compiler; </li>
<li>DWR ( Direct Web Remoting ) &#8211;> decent for AJAX. haven&#8217;t had a chance to explore it in entirety.</li>
</ol>
</div>
<p>
Out of all the above, I think Apache Wicket Framework stands out as the PROUD WINNER HANDS DOWN ( YeaH yEAH all you Tapestry people out there, try APACHE WICKET! ). Apache Wicket reminds me of Swing Model of programming; the best part is that while programming in Web Paradigm; i dont feel that i am in Web kind of programming mode. For example if i am coding things in struts or any other so called MVC framework, i would be doing JSP and writing configuration files and god knows what not.
</p>
<p>Bottom line : WHY? WHY? WHY? WHY? what is the need for all of this ?</p>
<p><strong>Flaws in frameworks which call themselves &#8220;MVC&#8221;  </strong></p>
<p>
The truth is that i knew about this flaw for a long time ( Recently someone reminded me of this flaw over again, hence the rush to type in    ) Basically, ( for those of you who are not familiar with MVC, refer to : <a href="http://en.wikipedia.org/wiki/Model-view-controller">MVC</a> ) in almost all frameworks you&#8217;d find JSP which is a view, a controller servlet which handles and delegates to other classes some responsibility and controls the flow of application, the model which could be a Plain Old Java Object (POJO). Now the problem with JSP is that it simply (in almost all cases) is never a pure view, why? well because it has something called EL (expression language) which can provide for conditional constructs ( like for example <c:if> or <c:forEach> etc etc.) (Not to mention in Model 1 we can have scriptlets; which suck all hands down) Which all tells me that some of the data handling (well some is an exaggeration, with most applications, the conditional tags are almost always used in abundance) is always done, So how is it a view? </p>
<p> <strong>Here comes Apache Wicket! </strong><br />
To understand how Apache wicket solves above annoying issues, i think it&#8217;d be appropriate to go through with a simple application flow:</p>
<p><a href=" http://wicket.apache.org/examples.html">Wicket Examples</a></p>
<div style="background-color:#ffefd5;color:black;" align="left">
<ol>
<li>you only needed 1 xml file (that is web.xml, d-oh!)</li>
<li>You do what you &#8220;should&#8221; be doing as a java developer in the first place; write Java classes, each Java class (for example a Page type ) can have components, you add components the &#8220;same&#8221; way (almost) as you were used to adding in  Swing framework back in old days (for me at least, haven&#8217;t worked in Swing for while). Your response or page navigation is based on classes and Classes Only! ( for example you have a button&#8217;s onSubmit( ) method in which you mention setResponsePage(NextClass.class, params); // where params is parameters you want to pass in ( And No they are not from request object! you would not need request object here &#8230; which is why i love this framework (i know &#8230; feels a little weird)).</li>
<li>You html files DONOT contain logic of any sort, they are pure HTML files (well almost). </li>
</ol>
</div>
<p>I have to try Flex and OpenLaslo yet, but Wicket is HOT!<br/></p>
<p>Note : I haven&#8217;t been through the typical sequence of what happens when a request comes in, how Wicket handles it; I&#8217;ll cover those things in later posts &#8230;  </p>
<p>For now try this site : <a href="http://wicketstuff.org/"> Wicket Stuff</a><br />
Regards<br />
Vyas, Anirudh </p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/03/20/apache-wicket-the-greatest-java-web-framework-ever/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Auto Fetch : A great Add on to Hibernate!</title>
		<link>http://anirudhvyas.com/root/2008/03/19/hello-world/</link>
		<comments>http://anirudhvyas.com/root/2008/03/19/hello-world/#comments</comments>
		<pubDate>Wed, 19 Mar 2008 20:35:04 +0000</pubDate>
		<dc:creator>Administrator</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false"></guid>
		<description><![CDATA[I was rummaging through Hibernate forums and I stumbled upon something interesting   

The goal of Autofetch is reduce the modularity penalty and programmer burden of specifying associations which should be loaded with an object query. These specifications are sometimes are called fetch profiles, prefetch directives, or joins. These specifications are an important performance [...]]]></description>
			<content:encoded><![CDATA[<p>I was rummaging through Hibernate forums and I stumbled upon something interesting   </p>
<p>
The goal of Autofetch is reduce the modularity penalty and programmer burden of specifying associations which should be loaded with an object query. These specifications are sometimes are called fetch profiles, prefetch directives, or joins. These specifications are an important performance optimization because they reduce the number of round-trips to a persistence store whether that be a relational database, object database, or flat file. Autofetch is a library which integrates with object persistence tools and automatically handles prefetching data. Using dynamic program profiling, Autofetch determines the right prefetch directives for each query a program executes.<br />
For example, Autofetch integrates with Hibernate to eliminate the need for the programmer to specify fetch directives in queries and laziness in entity mappings. Autofetch currently only integrates with Hibernate. However, we are interested in integrating with other object persistence technologies including object databases and other object relation mappers.<br />
Autofetch was developed at the University of Texas at Austin by Ali Ibrahim for research by Ali Ibrahim and William Cook. An initial implementation was used for a paper submission to the ECOOP conference in 2006. Subsequently it was rearchitected and improved for open source release. Autofetch is licensed under the LGPL license.
</p>
<p> For more check out :<br/></p>
<p><a href="http://www.cs.utexas.edu/~aibrahim/autofetch/ ">AutoFetch</a></p>
]]></content:encoded>
			<wfw:commentRss>http://anirudhvyas.com/root/2008/03/19/hello-world/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.750 seconds -->
