Tuesday, April 8, 2008

Using anonymous class for command strategy!

In my small consulting bit, I recently came across a client’s requirements, part of which is mentioned below:
1) Data comes in a flat file, in comma delimited format.
2) Each line represents some sort of actions. The server makes sure that the actions represented in each line are sequential.

But he now needs further interpretation and more “actions” and his serverside coders have extended the interpretations and hence requirement for extension at clientside. They have given him a set of “reusable lib” to interpret the textual lines and returning into meaning objects! And conveniently left for the client to decide what to do with those “meaningful” objects. The previous clientside design just took each line and parsed the info, and did some stuff like executing a work flow, persisting the interpreted line details in db, notification to clientele etc.
Many of the older objects and methods are still much applicable even now. Like earlier execution of workflow, persistence and notification codes.

The older “IntegratorObject” (I didn’t name it!) was full of “if-else” conditions and a huge block of code. Would definitely like to refactor that! Factory method, strategy .. all came rushing onto my mind.

Then came my client, “oh! Java is oops, so these would be easily fit using reusable components and codes from older program, right?” (Advice: never tell a client that his existing code is crap! And I needed the money) ... so, I told him that I would make his “reusable” code into extensible code so that he can add and reuse stuff but not have to break exiting. “Whatever! should work as you promise and as efficiently as earlier. And not break anything!”... Okkkayyy!
Step1: I decided that each line must interpret and a “command object” created.

public interface IntegratorCommand {
void execute();
}

Step2: subclassed “IntegratorObject”, since some of the states and methods can only be used from within for sake of the “reusable methods”!! Overrode the onMessage(), and added a method for command object creation which would act as factory method and made the new Class as abstract.

public abstract class AbstractIntegrator extends IntegratorObject {
....
....

@Override
public void onMessage(BufferedReader reader) {
String lineInput;
try {
lineInput = reader.readLine();
while (lineInput != null) {
IntegratorCommand cmd = getIntegratorCommand(lineInput);
cmd.execute();
lineInput = reader.readLine();
}
reader.close();
} catch (RuntimeException e) {
...
}
}
protected abstract IntegratorCommand getIntegratorCommand(final String textInput);

}


[[NOTE: If you are wondering, why I subclassed and broke the onMessage() which is clear violation of all OOD principles, well firstly I didn’t want to do any modification/refactoring to their existing codebase (saving my neck!), secondly, yes I could have used a wrapper class delegating the needed instructions, but I also wanted to show to the client whys and hows. Served my purpose later!]]

Step3: So far, so good, I now derive a new class out of “AbstractIntegrator” and implement the “getIntegratorCommand()”right? Therein lies the problem, because of my client wanted to “reuse” the existing codebase which dependent heavily on states already present on older implementation (and I didn’t want to do touch their code). Building any extrinsic and sharable strategy objects would be difficult, and I would be forced to create intrinsic strategies which must be passed the reference of the “IntegratorObject” so that it can read its various states. And then pre-create strategies in constructor of IntegratorObjects (or use setter method!):



public class IntegratorStrategy {
public IntegratorStrategy(IntegratorObject integrator);
....
}
//in constructor of IntegratorObject types
IntegratorStrategy strategy = new IntegratorStrategy(this);


Now such predefined “typed and named” intrinsic strategies are helpful but can have following limitations
a) Cannot be loosely couple and shared (extrinsic)
b) Must be created within the scope of parent.
c) Circular reference. If you do manage to create sharable instances outside, and use setter methods for IntegratorObject ref and used in multi-threaded applications, you can run into problems because of programming error. Surely if you do not document the ordering of synchronized object method calls.
[Ok, I am thinking too much, just trying to cover possibilities]

Now, I could start thinking of some mindboggling extrinsic strategy design which would still require me to pass “IntegratorObject” states to each strategy making them more and more complicated and prone to breakage during extensions! I want the strategies to have access to the “IntegratorObject” instance and yet be defined concisely and be used in the factory method of “getIntegratorCommand()”. {{thinking! thinking....}} What about using “Anonymous Inner classes”?

Step4:

public class IntegratorV2 extends AbstractIntegrator {
....
....

@Override
protected IntegratorCommand getIntegratorCommand(
final String textInput);
IntegratorCommand cmd = new IntegratorCommand() {
@Override
public void execute() {}
};

//depending on textInput, different command objects are created
if (textInput.startsWith(“WF”)) {
cmd = new IntegratorCommand(){
public void execute() {
//serverside provided utils!!!
Object obj = IntegratorUtils.getWorkflowVO(textInput);
//superclass method
executeFlow(obj);
}
};
} else if (textInput.startsWith(“SND”)) {
cmd = new IntegratorCommand(){
public void execute() {
Object obj = IntegratorUtils.getNotifyMsg(textInput);
//superclass methods
notify(obj);
}
};

}
//and so on...
return cmd;
}
}


[[NOTE: I didn’t like the “if” statements and I fixed them other ways later, but the above should carry the point I am trying to drive]]
Everything works perfectly. Note the use of keyword “final” in getIntegratorCommand()for the String argument passed. This is required for call stack persistence of argument values. Otherwise, you can always use a property (and a setter method) to achieve that.
A nice use of abstraction. (and old way of forming “Closures” although the created command objects never lives outside the scope of the creator, in this case. But nothing stops the commands to be deferred calls. Isn’t that the idea of a command pattern anyway?)
The client finally saw the point and I did get the opportunity to refactor bit of their older code (and earn a bit extra money. Who said consulting was easy!)
I have renamed and changed the contexts a bit and omitted other irrelevant details. Sorry I couldn’t give much detailed information. Secrecy! Blame it on the rain!

P.S: I eventually used mix of anonymous class and genericized strategies.

Sunday, April 6, 2008

I love Spring!

I love Spring! The season as well as the framework. :)
For example, for one of my clients I had to install XPlanner as a project tracking and monitoring tool. (Yeah! I know there maybe a better XP tool available but XPlanner is simple and client likes it!) Anyway .. .

I downloaded xplanner 0.7b7 and tried to install under Vista Premium, running JRE 6 and Tomcat 6. This version of XPlanner is built on Spring 1.2 and I got this error

“org.springframework.beans.TypeMismatchException: Failed to convert property value of type [org.apache.commons.collections.map.LinkedMap] to required type [java.util.HashMap]”

Checking onto source file showed that “MetaRepositoryImpl” takes a “java.util.Hashmap” as its “repositories” property. However for some reason Spring was constructing a LinkedMap instance for “< Map >” declaration in bean configuration. Hmmm .. needed further investigation but I did not have time!
Now I had two options:
1) I could modify the source of “MetaRepositoryImpl”.
2) Think about spring way - Below is what I did.
Previous=>

< property name="repositories">
< map>
< entry>
....
< /entry>
......
< /map>
< /property>



Changed to=>

< property name="repositories">
< bean class="java.util.HashMap">
< constructor-arg>
< map>
< entry>
....
< /entry>
......
< /map>
< /constructor-arg>
< /bean>
< /property>


Done! Spring saves the day!