Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

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.

Monday, March 24, 2008

A lil homework

As part of my lil homework yesterday, I had this 'kahani'.

'A toy is controlled remotely over some grid like terrain. Along with its positional coordinates, the toy also maintains its facing (North, South, East, West) so that when remotecontrol commands 'move' - it moves in its facing direction. On turnLeft command, if facing North it would face West. On turnRight command, facing East then would be South. And so on .. '

Well smarty pants, I, declared an enum type.
public enum Facing {North, South, East, West;}


Writing a function to turn things right seemed simple enough!

public void turnRight() {
switch (this.currentFacing) {
case East : this.currentFacing = Facing.South; break;
case West : this.currentFacing = Facing.North; break;
case North: this.currentFacing = Facing.East; break;
case South: this.currentFacing = Facing.West; break;
default: break;
}
}


the similar way to implement the turnLeft() method!!! Now, this didn't seem to tough, eh? Ehrrrrrr! too many conditional statements? If say a new facing (NorthEast) is added, then for things to work, existing code would have to be broken and modified?

Now, Java 5 came with linguistic support for enumerated types enum. All enums implicitly extend java.lang.Enum and allow you to add typical class constructs. 'enum' is also Comparable and Serializable. Now, I could write some complicated program to solve the conditional expressions above. But hey all java enum return an array of declared enums through enum.values(). Voila!

So I wrote:

public enum Facing {North, East, South, West;} //change in order!

public Facing getFace(Facing refFace, int factor) {
int currentIdx = 0;
Facing[] faces = Facing.values();
for (int i=0; i < faces.length; i++) {
Facing face = faces[i];
if (face.equals(refFace)) {
currentIdx = i;
break;
}
}
currentIdx = currentIdx + factor;//the next facing index
if (currentIdx < 0) {
while (currentIdx < 0)
currentIdx = currentIdx + faces.length;
} else if (currentIdx >= faces.length) {
currentIdx = currentIdx - faces.length;
}
return faces[currentIdx];
}


if I consider turning left/anticlockwise as negative ..

getFace(Facing.North, -1); //=>Facing.West
getFace(Facing.North, +5); //=>Facing.East


So in the end, my turnRight() and turnLeft() turned to

public void turnRight() {
this.currentFacing = getFace(1, this.currentFacing);
}
public void turnLeft() {
this.currentFacing = getFace(-1, this.currentFacing);
}

Even if I go and change the Facing declaration to something like
public enum Facing {North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest;}
things would still work as expected if you want to turn left from say North Facing 1 step to NorthWest, 2 steps to West or even turn 720 deg! :)

Think about implementing the same for Days of week, or Months and do similar mathematics on them.
 
day = add(Day.Monday,4);
day = add(Day.Monday,-3);
month = add(Month.January,-3);


You can further generalize things further using
day.getClass().getEnumConstants()

enum is Tiger introduced. Prior to that java, standard way was like declaring a public static final constant usually in an interface/abstract class! For example, how do you add days, month or years to a calendar object?
calendarInstance.add(Calendar.DATE, 2);

Notice the similarity of definition but the differentiation? Declared in Calendar class
public static final int DATE = 5; 

if only java had operator overloading instead of the exotic darker beans and means for the riches! :((

Monday, January 21, 2008

Freerice

[November 14th, 2007]
A friend of mine (Paul) sent me the link. http://www.freerice.com. The endeavor is by “John Breen”, who is a US fundraiser. The idea is to use a game to build vocabulary, to donate rice to the needy. For every correct answer, the website donates 10 grains of rice. Companies advertising on the website provide the money to the UN’s World Food Programme (WFP) to buy and distribute the rice. http://news.bbc.co.uk/2/hi/europe/7088447.stm

While, I do not know why go by grains-of-rice, rather than grams-of-rice, I was free to check the website and contributed to about 500 grains of rice. For many words, (and they keep getting tougher), I had to refer to dictionary.com, but for once there was no guilt factor for cheating. While I was at it, I was thinking that .. this is a great way to increase someone’s vocabulary but this is a game that requires time, and my objective is also to donate more and more rice, which I can achieve only by correct answers. If technology can be used to raise money, I can also use technology to manipulate towards helping the eventual goal.

I can think of writing a program so that I can just keep running it the whole day. J How? Think of writing a simple selenium test case to run through the website, capture the element that contains the word requested, and also capture the choices given. Once I know the requested word, an Ajax call to any semantic search system can give you the results, and run a simple regular expression to match against the choices to come up with a rating. Again, use selenium to select the best possible answer and submit the request. Put this in a loop and keep running through out the day. With java 6’s new scripting apis, you can probably do without a selenium test case. More on java scripting api later.