Friday, April 30, 2010

s/w for social impact

off late, I have got few opportunities to work in s/w for social causes. While its great to be proving value and derive personal satisfaction out of work done for corporates, its something else when I can actually do something for social causes. Recently I was involved in solutioning a student welfare and learning program in Karnataka (yet to be implemented, but if and when its done, its going to be something really really awesome. Even better ... its going to be FOSS). Currently, I am involved in another open source product for a reputed microfinancing solution provider, as part of our company's Social Impact Programme. I have tried and failed before to do something useful for my own state in 2005/2006, for "various" reasons. This time around, I have the support, willingless and "hopefully" commitment from organizations who are really committed towards such causes, and not for propaganda or "easy money". More details later

Thursday, November 5, 2009

GWT or Pure JavaScript?

Off late, I have heard of quite a few stories of GWT being "awesome" choice for complicated web applications. "Ideal", "Awesome" are terms subjective to reuqirements but here's my take.

I am apprehensive of the strategy itself. To take advantage of compile time benefits of static languages for behaviors driven by dynamic language targetting already troublesome host environment!! Personally, I favor either a pure JS driven or RIA approach, depending on website needs.

In favor of pure JS driven approach:
- Browser compatibility problems have long been addressed by most modern JS libraries. Build your JavaScript components as extension to JQuery, ExtJS etc.
- For debugging support, you can't really shy away from browser level debugging. Odd that considering JavaScript is in widespread usage for so so long, that IDEs have remained far behind. But with increased stability in browser specifications (sure!) and absence of dog-fights, most browsers provide good support these days. Mozilla, IE, Opera and growing number of additional plugins are getting pretty good at it.
- During development, tools like JSLint can provide you some degree of dev time checks. Tools JSEclipse, Aptana Studio etc also help.
- Testability: Well its far from XUnit level support and integration, but its getting better everyday. It also depends on how you design your UI (pages, elements, scripts), and to an extent to overall web app architecture. Honestly, isn't it the case for any other system?

I recently discovered, js-testdriver. Its awesome, integrates with Eclipse and CI systems. JSUnit is also helpful, but probably you want to consider testability aspects right at the time of designing your Pages and JavaScript components. (Which you should for any system, always)

More dramatically, using Java 6 scripting apis, you can think of mocking DOM, other dependencies. (Now thats adventure :) .. )

- if you design your web layer such that you only work around visual component's behavior rather than rendering itself, you can greatly influence testability as well. for example, an AJAX call returning XHTML(s) that can be used for rendering than JSON and direct DOM manipulation techniques. This way, if you design your server side actions and templates well, you can reuse the views for both page and AJAX requests.

- finally, writing code in JS, is the best way you will write quality code. No code generation tool can help you achieve better understanding/code/design. Don't shy away from it, embrace JS development. Will you adopt a GWT/Script# like approach for CSS too??

Btw, I have used GWT before and liked it very much till I really understood and used JavaScript as an OOPs language, and worked on various Web architecture approaches. Basically really learnt things about WWW.

Wednesday, September 23, 2009

working with the geeks

Since monday, I am engaged in another consulting gig for a high profile client. I am getting to work with some super dudes, very senior architects. They are luminaries in their own fields ... its quite something,

the amount of stuff you get to learn just by watching them is just phenomenal
- they can immediately recognize the problem areas
- the thought process. Phew, they are just able to co-relate things which may seem absolutely irrelevant and out of context of each other.
- ability to solutionize.
- how they engage with the client.
- obviously the depth of knowlege they pocess.

at the same time, you are sort of scared of not been able to live upto their expectations. which is sort of good in a way I guess, keeps you in your toes. :)

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!

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! :((