27.8.09

Don't ask me who this is. SWMBO thinks it is an ad for Parag Sarees :)

More on Generics...

My pet peeve with Generics I think is generic methods. They are actually a useful construct. Here's an example (untested) :
static List<Shape> history = new ArrayList<Shape>();
public void drawAll(List<? extends Shape> shapes)
{

history.addLast(shapes);
for (Shape s: shapes)
{

s.draw(this);
}
}

In short, the compile guarantees that the list history can only take in objects of type Shape. So when you pass in the argument shapes to method drawAll, the compiler would have checked the contents of shapes and only allowed them if they were of type Shape.Its a mouthful but adds a lot of type safety.

Now lets look at another way of doing this:
public class GenericsMain {

public <I,O> O getOutput(final I input)
{
return (O) ((String) input).toUpperCase();
}

public static void main(String[] args)
{
GenericsMain main1 = new GenericsMain();
main1.getOutput(100);
}

}
Does this look correct? Its actually compiler-safe. Not that that means its runtime safe of course. There are no guarantees that I or O will be checked by the compiler as it is not. Try to compile and run this. You get a ClassCastException. That's because, at runtime the JVM converts 100 into a new Integer object which we then proceed to cast as a String. Instant implosion.

This is real live code. The idea was that there would be one instance of this class,with multiple if...else constructs. the conditional would check the typeof the input like so:
if(input instanceof String)
That ways all users can benefit from reuse and fill in all possible business objects conditionals and wreck havoc from there on. Not wanting to divert my attention from the solution to this, I will keep away from the ranting. The solution looks something like this:
public class GenericsMain<Integer, String>
Of course it won't solve the problem in this particular piece of code, I'll leave that as an exercise. Using an interface might improve things.

So in end what I want to emphasize is typecasting any object while paying lip-service to generics is harmful. Unchecked conversions like these only throw a warning and you would never know till Mrs. Chadda got a bong instead of a bangle, in production, 5 days after the product goes live.

That brings us to Type Erasure. More on that later.

25.8.09

Murder she wrote...

Its been a long time since I have read a good detective novel. The last ones I remember had too little storyline and more fluff than required. So it was nice to lay my hands on S.J.Rozan's LydiaChin and Bill Smith novels.

The pace is fast, the character sketches are very good and the conversations are excellent. The narrative is first person and is voiced by NYC chinatown PI Lydia Chin. The banter between the two protagonists is quite unlike Watson and Holmes. There is a slight memory of Remington Steele here, only Bill is the more experienced and Lydia is the more active of the duo. By habit, I avoid first person narratives. I haven't read a lot of good one's, I suppose. But Lydia is a great character. Somewhere in the family-bound, confused second generation Chinese twenty-something, I probably see shades of my friends and myself. Its reassuring to see detectives who are all too human, who make mistakes and don't stumble into coincidental success. The books so far have been typical masala,potboiler scenarios and highly enjoyable because they don't tend to take themselves seriously.

That said, there is of course the usual amount of luck involved and some scenarios can be far fetched. Reflecting the sky is set in Hong Kong and imagine her surprise when she finds a friend of the family who is not only her age and single but also a cop in the HKPD. How lucky!

Reflecting the Sky and Shanghai Moon are the two books I have read so far. Hoping to pick some more up. Definitely recommended. I am not sure if there is a book rating scale, lets call it PWs for now. So on a scale of 10, 6.5 PWs.

p.s PW is of course P.G.Wodehouse who rates 1/0 on a scale of 10, but that is for later.

Stick figures...yay...


I call this one : aiming without a target in sight.

23.8.09

Java Generics

I am going to keep and track some of the knowledge I pick up on Java and Groovy in the blog for SWMBO and me. Here's the first of them.

Java is a statically typed OO language, laying a lot of emphasis on the particular type of an Object. Is it is a bird, a plane or Superman? But in the inheritance model of Java everything subclasses an Object. In effect where a bird should be, you could coerce an Object to be. Like so:
Bird bird = (Bird) object;
Now if the object happens to be a particular static type at compile time, which is not Bird, the compiler will throw an error. BUT if we resolve the value of object from a method which returns an Object (say a Java 1.4 collection method), we can typecast it into anything including a bird. Whats worse here is that typecasts should typically be along an inheritance tree, but what we get it is people attempting to make a bird out of a plane and so on.

Defeats the overall purpose of a statically typed language doesn't it? That's why ages ago in Java 5, Generics were introduced. The idea was to allow Collections (which had the most problems with unsafe types) to confidently identify the type of the contained elements. It does restrict your Collection to a particular type of course, but how usually do you want a List to contain Integers and Strings?

Generics introduced its own syntax, notations, wildcards and vm changes, most of which no one understands. I will try to compile (*snicker*) some of my thoughts here, more to learn generics correctly than to disseminate any information. Why am I bothering to gather info freely available with a google search? Simple, a lot of info out there is wrong. Like I said not a lot of people completely understand OR correctly use generics.

Consider it my first internet brain-drain exercise.

Ingluorious Basterds

What a movie! First off, SWMBO enjoyed it. A lot. Which helps my cause.

Secondly the treatment of the subject matter was very ballsy and Tarantino has definitely pulled it off well. The movie is essentially a bunch of conversations. Two people talk about the nature of rats, featuring over sized smoking pipes. Three people meet a woman in an obscure tavern, featuring a lot of mayhem. And all these conversations lead to the unconventional, frankly bizarre, but thoroughly enjoyable climax. At the end of all the mayhem, the director remembered to introduce just a quiet post-script, mocking the master race and creating an ending, which probably, people will try to imitate for a long time to come.

Like a character in the movie says, 'You are getting pretty good at this'. 16 years after Reservoir Dogs ,Tarantino shows the same maniacal genius with which he is able to convince us to shell out our money to walk into an unlikely story which leaves people equally horrified and begging for more. The pace is actually pretty slow, punctuated by moments of violence and extreme emotion - be it Shoshanna reacting after the completely placid hotel conversation over Strudel or Stiglitz accounting for himself in the marksmanship department in the tavern. The pace picks up to the end, the climax is out of this world. The movie studiously avoids dramatics until in one brief scene it leaps at you, out of the blue, and leaves you spellbound. Its truly like reading a book and thank you, QT for a wonderful narration.

And the epilogue must come in for special mention. In all this nonsense about Branjelina, how we missed the fact that Brad Pitt can act like no one else. If anything, this is probably Brad's masterpiece. He has very little screen time - but he has massive screen presence. No one could have pulled off the initiation scene, where he picks 8 soldiers for his elite Nazi killing squad, like him.

But the true and real star of the movie is Hans Landa. An unknown Cristoph Waltz, in the role of a lifetime. As the character walks through his seemingly innocuous patter, he injects this little bit of fear in you - its hard to imagine that a man talking innocently of strudel, milk and reading out of census details, in a time of great fear and tragedy, can be anything BUT evil. Outlandish and full of pent-up rage, Hans Landa could have been the everyman caricature of a Gestapo officer, but turns out to be a different kind of an antagonist. It is he who is the real tie-in, who carries the whole movie on his shoulders - the story would not have been possible without Landa.

Its hard to see someone take on history and come up with a non sequitur ending. On the whole a great watch on a rainy night.

21.8.09

Sab Kaminey hain ...faale

*Warning* longish post... got carried away a little...

'Arre fa ko fa nahin toh kya la bolega, huh?' This pretty much covers the general feeling of people who have seen Kaminey. No one is sure if we want to call it a B-Grade action flick or an amazing tribute to everything great about masala action movies. 'Fa' hai ya 'La' hai? Bhope bhau (Amol Gupte playing the most fascinating caricature of a Mumbai don is amazing) calling out the obviousness of Charlie (Shaid Kapoor is awesome as well) saying 'main fa ko fa bolta hoon' is midway in the movie and by then we have already fallen over laughing at Guddu, Sweety and all the assorted kamineys. But picture abhi baki hai and we are treated to an erratic and fast paced climax which, like summer rain crashes suddenly on us and leaves us wanting more.

I am amazed by the breadth of imagination shown here by Vishal. In this movie, which I see as a tribute to the masala action movies of not that long ago, Vishal blends dark humor with craziness, insanely funny dialogues and some of the best cameos I have ever seen. Be it the irascible Lobo (Ek gaana ga na) or the quirky Tashi (I'm not America) or the stoned pub crawler Mikhail (don't you love communist influences) - the cameos are what underwrite a strong cast and amazing timing. The dialogues are the eventual star of the movie. The storyline is actually different and strongly punctuated by distinct character sketches - from the lisping Charlie and the stammering Guddu to the cowardly, bullying Lele - everyone has their share of the writers attention.

The music is not much to write home about. I love 'Dhan ta nan'- ohh how I love it. Its on loop at work and at home. All day long. But then what? The background score is repetitive and sounds boring after a while. Plus it could have been better :P

So whats with all these forum entries then? I have read so much about people hating the movie, or the movie being more hype than substance. The general consensus is "Could have been better". I for one, don't know what could have been better. What is funnier than Sweety charging out of a room screaming 'toh kya main ne tera r*** kiya hai' and Guddu promptly going into the toilet, on which of course is scrawled 'apna haath jagannath'? Who adds subtle details like that in a lover's spat? There are just so many funny dialogues and situations, each so well handled a post for each scene would not be amiss. It was a masala movie - I don't think any amount of hype hid that fact. Probably even the ultimate masala movie.

I don't know what people felt missing, but I am guessing this was just like the reaction to Satya or Rangeela. So much of the plot and dialogues are Mumbai centric, so much of the humor is subtle (yes, there is subtlety involved, refer toilet door). Maybe the crudity of Mikhail and Charlie groping each other?

Then there was this comparison to 'Lock Stock' and 'Snatch'. People, grow up. The camera tripping away in one song and a comedy of errors does not mean its in the same vein. It is a truly home-grown (might I add 'Amchi Mumbai') story. And even in that comparison, the movie comes trumps. Fast-paced, funny, dark and violent.

I wonder if it was the unpredictability of the movie that turned off people. The twins actually grow up together and don't get separated at Kumbh ka mela - or at the Bandra Fair, take your pick. Everyone knew that the twins would be matching wits against the others antagonists - it is a comedy of errors, no. Did anyone expect them to go back to their real villains - Charlie to Tashi and the keystone cops and Guddu to his 'mehuna' Bhope? Did anyone expect Lele to kill Lobo for 'ek aur chance'? Or did anyone expect Priyanka Chopra to come up with the performance of a lifetime :P ? Probably no to all the above and that turned them off.

Maybe it was the large cast. There are at least 11 distinct characters we follow, never mind the flash backs. The movie jumps from character to character in a flurry of half-scenes. We simultaneously follow the twin's interrogations and it does tend to be hard to keep track if you don't pay attention. After all watching a movie is more a social activity then for the sake of the movie. And the threads of the story were sometimes so intertwined, it might have been difficult to unravel the real 'meaning'.

Or maybe it was the ending? I heard a lot of complaints about the ending - a little overblown, not very funny, too incongruous... what do you expect in a masala movie? If anything that was one of the funniest endings ever especially all the bargaining (3,33,333.33 rupees to be exact). Did people rather want the twin's father to be kidnapped adding another dimension? Did they find the brother willing to sacrifice himself a little too corny?

I don't know what triggered the negativity. Maybe its isolated to me. But, I loved the movie. After a long time, I saw a movie retake on the masala genre - comedy,action,emotion...a little bit of everything. If that does not make a movie awesome, I wonder what does.

ps. did I mention I loved Priyanka Chopra in this movie and have had to reconsider dismissing her as a non-entity. She can act.

11.8.09

Groovy and why I want to use it more

Like I said in my previous post, Groovy is something which I am trying out. It's a nifty scripting language which runs on the JVM. I figured since I work with Java and need to meet my goal of one new language this year, it would be a good start. I needed a script to automate some file parsing, which would save me perhaps 10 minutes of copy-paste hell and I figured I would use Groovy. It was pretty impressive.

Parsing a text file in Java can be very difficult. Its one of the first things you are taught to do with Java. And it is not simple. Here's a simple snippet which would read a file from java and print out each line from the file:
package javaapplication2;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fstream = new FileInputStream("/home/umesh/febsec.txt");
DataInputStream in = new DataInputStream(fstream);
String strLine;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((strLine = br.readLine()) != null) {
System.out.println (strLine);
}
}
}
Here's the same piece of code written in Groovy.
package javaapplication2

new File("/home/umesh/febsec.txt").eachLine {println it}
I am sure I gloss over some things, which make Java robust and all that good stuff. But that's the essence - simple and dynamic. Of course, no typing is also good.

The learning curve for me was minimal - I spent some time reading about Groovy, courtesy Google and no I don't Bing. I had a parser to write and I was able to cobble it together within the 2 hours. What astounded me were 2 things which I never get to do easily with Java:
  • Having class files without all that overhead of imports and packages - just so you know,my original script has no package line. I am not sure how this all works, but I am going to find out, because this simple thing means I get to write command line apps in Java with very little overhead and lots of Groovy magic.
  • Closures - I never quite understood what closures meant. It's difficult to treat functions as first class objects. But this example definitely got me interested. Much has been written about closures, which I won't repeat, suffice to say they are pretty powerful and compact.
So two simple things have gotten me interested and I hope to use Groovy more. There is of course more to Groovy and my example is at best elementary-grade. Time to put my deerstalker cap on and examine the Groovy SDK.

What can I do with it? I am not sure. I don't want to fall into the 'there are so many things to do, I'm sure I will find one' hole. Been there too many times. This is not to say I believe Groovy can solve every problem. It has its own set of vulnerabilities. And I definitely do not like the idea of having a dynamic language handle ,say, financial transactions. But since I know Java, using this as my primary scripting tool should make automation a breeze.

A fresh new start...

Today I did something I never thought I would do - I wrote a small script in Groovy.

Who cares? Probably no one. Here's the thing, I have been procrastinating about working with a Programming language other than Java for, what, 4 years now. 4 years... and today I wrote a small snippet of script. It was a revelation. I realised that I can go ahead and work my way through anything with ease IF I make an attempt and don't care about how it would turn out. Yes, I am quoting the Gita, but that was incidental. You never realize the significance of something like that, till you face a situation like that.

So that brings us to this post. I burnt all my boats and deleted all my older posts. Kinda skipped the apology post, because ... hey... who is reading this anyways :D