This is what happens when you are reading a great functional programming book , looking at imperative code makes you cry . Here is what I did to console myself out of my grief today ( whatever makes you happy right ? )

The code below wraps google collections , in a thin java DSL like wrapper

 public class IterableQuery {

   public static  Where from(Iterable originalCollection) {
      return  new Where( Iterables.transform(originalCollection, IterableQuery.SAME()));

   private static  Function SAME() {
      return new Function(){
         public T apply(T arg0) {
            return arg0;

   public static class SelectOrderBy{

      private final Iterable iterable;

      public SelectOrderBy(Iterable iteable) {
         this.iterable = iteable;

      public  SelectOrderBy orderyBy( Comparator sort ){
          Ordering.forComparator(sort).sort((List) iterable);
          return new SelectOrderBy( iterable);

      public   Iterable select(  Function function){
         return Iterables.transform(iterable, function);
      public  Iterable selectEveryThing( ){
         return iterable;

   public static class Where{

      private final Iterable iterable;

      public Where(Iterable iterable) {
         this.iterable = iterable;

      public    SelectOrderBy where(Predicate predicate) {
         return  new SelectOrderBy( Iterables.filter(iterable, predicate));


Now collections could be queried like

 Iterable currentlyAssigned =

In C# 3.0 a lambda expression can be converted into either an expression tree or a delegate ..former of which lets you treat code as data ..this mechanism is source of all the coolness behind linq to sql .

But this is doesnt have to be limited to frameworks, You can take advantage of this mechanism in your day
to day coding .. here are just two examples of the stuff I’ve used this in the past ( examples below are made up equivalents)

Builders :

Lets say you are writing a weekly activity recorder , the traditional ( boring ..) way of creating it would be

  WeeklyActivityRecorder weeklyActivities = new WeeklyActivityRecorder ();
  weeklyActivities .AddActivity( new Activity{Day = DayOfWeek.Monday , Activity = "Lawn Moving" });
  weeklyActivities .AddActivity( new Activity{Day = DayOfWeek.Tuesday , Activity = "Cooking" });

The ” Code as Data ” way would be ..

  WeeklyActivityRecorder weeklyActivities = new WeeklyActivityRecorder () .WithActivities( Monday => "Lawn Moving",Tuesday => "Cooking");

This looks more readable ( and fun :) ).. and there is very little work involved to actually achieve this

 public static WeeklyActivityRecorder WithActivities(this WeeklyActivityRecorder recorder, params   Expression<Func<DayOfWeek, string>>[] activities)
  foreach( var activity in activities )
     LambdaExpression expression = activity;
     ConstantExpression activity= expression.Body as ConstantExpression;
     DayOfWeek day =  expression.Parameters[0];
     recorder.AddActivity(new Activity {DayOfWeek = day , Activity = activity});
 return recorder ;

Here I define a new extension method on WeeklyActivityRecorder which takes varargs lambda expressions
I then parse the lambda expression to create the appropriate activity , pretty straightforward stuff.

The second example is creating a hibernate criteria from expression tree

Once again the *old* way of querying by property would be by passing in the property by string

  protected IList<T> _FindByProperty(string propertyName , object value)
            return _hibernateTemplate.Execute(
                            session => session.CreateCriteria(typeof(T)).
                            Add(Expression.Eq(propertyName, value)).List())

Code is obviously fragile since you have to use strings as property names which cannot be checked at compile time..

So instead of calling that method directly we could call it through a method which accepts an expression instead of string

protected IList<T> _FindByProperty<TResult>(Expression<Func<T, TResult>> expression, TResult value)
 return _FindByProperty((expression.Body as MemberExpression).Member.Name, value);

The Above method could now be called as

 IList<User> costCenters = _FindByProperty( user=> user.Name, "surya");

Existence of property “Name” is now checked at compiled time ..Although this technique is powerful, it feels
limited when compared to what you can do in LISP dialects.

Often in a query based api’s ( for example  REST based apis )  there is a need for providing a capability for the client to specify the field and depth  while retrieving an object graph ..

For example, Windows Live contact Api

let you specify Field and Depth Filtering via the query param Filter , for example a request like<lid>/rest/livecontacts&Filter=LiveContacts(Contact(ID,CID),Tag)

Would retrive live contacts contact with id , CID and tag for live contact .

You could make this infinitely recursive to pick and choose fields you want at any graph depth .

Here is the  antlr grammer for doing just that .. Instructions for how to generate code is available on antlr website

grammar Response;

options {output=AST;}
tokens {
response:  root (',' root)* -> root+ ;
root 	:fieldshortcut|'*'| (nodewithchildren);
nodewithchildren: (ID LPAREN response RPAREN) -> ^(ID response)
	|ID -> ^(ID STAR)
	|ID '()'-> ^(ID) ;
	:	'{'ID'}' -> ^(FIELDSHORTCUT ID);	

ID  :   ('a'..'z'|'A'..'Z')+ ;
INT :   '0'..'9'+ ;
LPAREN 	:	'(';
RPAREN 	:	')';

NEWLINE:'\r'? '\n' ;
WS  :   (' '|'\t')+ { $channel=HIDDEN;} ;

A line on code speaks for 1000 lines of  explanation :) .. so here it is

jQuery.extend(jQuery.expr[':'], {
	classStartsWith: function(a, i, m){
		var classes = $(a).attr("className").split(" ")
		var found = false;
		for (var i = 0; i < classes.length; i++) {
			if (classes[i].startsWith(m[3])) {
				found = true;
		return found;

The above code plugs in a custom selector for matching all the elements which have class starting with a certain string so


a selector like above would select all the input elements with class starting with highlight .
I guess the code is pretty straight forward so I’m not going to go exegetic on the code .

Client side javascript validation often ends up being  ugly and really boring ..while on the serverside validations usually tend to be more domain related ,something like “order.Qty > 0″ on the serverside endsup looking something ugly like “document.get(…….).val()….”

I ended up writing a jquery plugin which reads the form inputs and converts it into an object graph based on the name attribute, so for an form with the following  inputs

<input  name="order.customerName"  />
<input  name="order.orderItem.qty"  />

you could just say

 var order = $('#myform').params2Object();
 test(order.customerName ==='john');
 test(order.orderItem.qty > 0 );

Here is the actual plugin code ..HTH

jQuery.fn.params2Object = function(){
    var d = this.serializeArray()
    var data = {};
    for (var i = 0; i < d.length; i++) {
        var tokens = d[i].name.split('.');
        _setValue(data, tokens, d[i].value);
    return data;

    function _setValue(obj, tokens, value, index){
        if (tokens.length == 1) {
            if (typeof index != 'undefined') {
                obj[index] = obj[index] ||
                obj[index][tokens[0]] = value;
            else {
                obj[tokens[0]] = value;
        else {
            var prop = _getProperty(tokens[0]);
            obj[] = obj[] || (prop.isArray ? [] : {});
            _setValue(obj[], tokens.slice(1, tokens.length), value, prop.index);

    function _getProperty(token){
        var arraySplit = token.split('[');
        if (arraySplit.length > 1) {
            var propName = arraySplit[0];
            var index = arraySplit[1].split(']')[0];
        else {
            var propName = token;
        return {
            name: propName,
            index: index,
            isArray: token.indexOf(']') > 0



I happened to catch up on my “mainstream” listening this week .. so I picked 3 albums and all three of them had *traditional* indian instruments in them..

Or .. I guess it was just a coincidence that the three ablums I picked up happened to have indian instruments in them ..

Either way its cool .. my brain subconsciously puts a seal of approval on a song which has even a minor smattering of sitar , tabla , flute or any other awesome instruments ..

Bonus : *Teen Mar* in British Accent (

Just a fun comparision between C# and Java ..I am obiviously not comparing stuff like LINQ, Lambda expressions which dont have java equivalents

Round 1.0 – GENERICS

  1. No Type Erasure in C # , new T() anyone ??
  2. Value types like int or Enumeration can be be used as type parameter so MyClass<int> is perfectly valid.
  3. No Wildcards in C# which I terribly miss , Cast<>() from Linq Enumerable doesnt look too pretty
  4. Java has better support for covariant and contravariant for type parameters , I dearly miss ” ? ” from java.
  5. Assignment Type inference works in Java but not C#
    in Java,
    public T <T> myMethod()
    T var = myMethod() ; // T is inferred here !!!
    in C#
    public T MyMethod<T>()
    T var = myMethod() ; // T cannot be inferred from the assignment here!!!

This round clearly goes to C# …Generics done right ( almost ..)

Round 2.0 Enums

Java has enum support too..but whats different with enums in C# is

  • They can’t define their own methods.
  • They can’t implement interfaces.

  • Both of which can be done in java side ..Ok so this round goes to Java

    Round 3 : IDE’s
    Ok ..this has nothing to do with language itself ..but most people’s ( me included ) overall experience with the language includes the IDE too ..if this was not the the factor dynamic languages would have won the battle ages ago..

  • Visual studio almost does justice to the word “Integrated” in IDE ..not more running around using 10 different tools just to put a database on the website..
  • There is no Concept of a “Power User ” in visual studio..and its still catching on to the word “refactoring” even after 15 yrs.. without resharper it would be like coding with your mouth with your hands tied behind.
    This round is a TIE..
    Round 4 : Packaging
  • C# does a pseudo OSGI with internal access modifier
  • TODO
    Round Goes to C# ..

    Round  5 : Boilerplate Code
    This is a Staticlly typed language ‘s kryptonite .. I know know who is going to win this round..

  • Using blocks ..null coalescing operator , lambda expressions , Linq , automatic properties ..long list of awesome features
    Round clearly goes to C# again…no contest at all..

    Round 6 : Libraries / Frameworks

    Again this obviously has nothing to with language itself but still contributes to overall experience ..

  • Java has vast array of open source libraries to choose from ..( paradox of choice ?).. .Net libraries are mostly from Microsoft .. .Net equivalents of good stuff from JAVA like Nhibernate and Spring.NET are  generally lagging behind and receive much less attention than their java equivalents..

    This Round goes to Java

  • Follow

    Get every new post delivered to your Inbox.