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 =
             IterableQuery.
              from(orders).
              where(placedInLast10Days).
              orderBy(lastName).
              select(orderToNewOrder);

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())
                            .Cast<T>().ToList();
        }

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

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

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

https://livecontacts.services.live.com/users/@L@<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 {
   FIELDSHORTCUT;
   STAR;
}
response:  root (',' root)* -> root+ ;
root 	:fieldshortcut|'*'| (nodewithchildren);
nodewithchildren: (ID LPAREN response RPAREN) -> ^(ID response)
	|ID -> ^(ID STAR)
	|ID '()'-> ^(ID) ;
fieldshortcut
	:	'{'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; break; } } return found; } }); [/sourcecode] The above code plugs in a custom selector for matching all the elements which have class starting with a certain string so [sourcecode language='javascript'] $('input:classStartsWith('highlight')') [/sourcecode] 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&#91;i&#93;.name.split('.');
        _setValue(data, tokens, d&#91;i&#93;.value);
    }
    return data;

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

    function _getProperty(token){
        var arraySplit = token.split('&#91;');
        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 ( http://www.youtube.com/watch?v=fZv-G7IISgs)


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 ..you 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


  • Option 1 : Subclass Enummapping class

    But that forces us to create several meaningless little classes just for the sake of mapping and if its always the string name of the enum why go through all that ?

    Option 2 : Create a Generic Enum mapping usertype ..which might look like …

    public class EnumMappingType : IEnhancedUserType , IParameterizedType
        {
            private Type enumClass;
    
            public  string Name
            {
                get { return "enumstring - " + enumClass.Name; }
            }
    
            public  Type ReturnedClass
            {
                get { return enumClass; }
            }
            public object StringToObject(string xml)
            {
                return null;
            }
    
            public object FromXMLString(string xml)
            {
                throw new NotImplementedException();
            }
    
            public string ObjectToSQLString(object value)
            {
                return GetValue(value).ToString();
            }
            public virtual object GetValue(object code)
            {
                //code is an enum instance.
                return code == null ? string.Empty : code.ToString();
            }
    
            public void SetParameterValues(IDictionary parameters)
            {
               enumClass = Type.GetType((string) parameters["enumClass"],true);
            }
    
            public  object FromStringValue(string xml)
            {
                return GetInstance(xml);
            }
            public virtual object GetInstance(object code)
            {
                //code is an named constants defined for the enumeration.
                try
                {
                    return Enum.Parse(enumClass, code as string, true);
                }
                catch (ArgumentException ae)
                {
                    throw new HibernateException(string.Format("Can't Parse {0} as {1}", code, enumClass.Name), ae);
                }
            }
    
            public  string ToString(object value)
            {
                return (value == null) ? null : GetValue(value).ToString();
            }
    
            public  bool Equals(object x, object y)
            {
                return (x == y) || (x != null && y != null && x.Equals(y));
            }
    
            public int GetHashCode(object x)
            {
                throw new NotImplementedException();
            }
    
            public object NullSafeGet(IDataReader rs, string[] names, object owner)
            {
                object code = rs[rs.GetOrdinal(names[0])];
                if (code == DBNull.Value || code == null)
                {
                    return null;
                }
                return GetInstance(code);
            }
    
            public void NullSafeSet(IDbCommand cmd, object value, int index)
            {
                IDataParameter par = (IDataParameter)cmd.Parameters[index];
                if (value == null)
                {
                    par.Value = DBNull.Value;
                }
                else
                {
                    par.Value = Enum.Format(this.enumClass, value, "G");
                }
            }
    
            public object DeepCopy(object value)
            {
                return value;
            }
    
            public object Replace(object original, object target, object owner)
            {
                return original;
            }
    
            public object Assemble(object cached, object owner)
            {
                return cached;
            }
    
            public object Disassemble(object value)
            {
                return value;
            }
    
            public SqlType[] SqlTypes
            {
                get { return new[] { SqlTypeFactory.GetString(10) }; }
            }
    
            public Type ReturnedType
            {
                get { return enumClass; }
            }
    
            public bool IsMutable
            {
                get {return false; }
            }
        }
     

    And the corresponding mapping file can be ( you can also create shortcut typedef’s btw )

    <property  name="EnumPropertyName">
          <column name="EnumPropertyName" sql-type="nvarchar(50)" not-null="true"/>
          <type name ="....EnumMappingType, Assembly.Name">
            <param name ="enumClass">Your.Enum.ClassName</param>
          </type>
    </property>
    

    Hope that helps someone out there !!!


    This  is a cookbook for creating Python extensions in C/C++ under Windows with SWIG, distutils and gcc (MinGW version).
    I am using to the following versions

    1 . SWIG Version 1.3.24

    2 . Python 2.3.4

    3.mingw 3.0.0

    1. Get and install MinGW gcc
    Download the compiler from http://www.mingw.org. This GCC compiler runs under Windows and compiled programs do not require support DLL like CygWin GCC.

    You only need to download MinGW-1.1.tar.gz (roughly 10,6 Mb). It contains the whole compiler, support utilities, documentation, librairies and header files.

    Once decompressed, you should add the \bin directory of MinGW to your path environment variable.
    (Example : Under Windows 95/98/ME, if you installed MinGW to c:\gcc, you would add SET PATH=c:\gcc\bin;%PATH% to your AUTOEXEC.BAT.)

    If installed properly, you should be able to run gcc –version anywhere. (Mine displays : 2.95.3-6).

    2 . Get and install Python
    Download the executable from http://www.python.org . As usually set the path to run python from anywhere.

    3 . Create libpython23.a
    To create Python extensions, you need to link against the Python library. Unfortunately, most Python distributions are provided with Python23.lib, a library in Microsoft Visual C++ format. GCC expects a .a file (libpython23.a to be precise.). Here’s how to convert python23.lib to libpython23.a:

    Download pexport (from here or http://starship.python.net/crew/kernr/mingw32/pexports-0.42h.zip).
    Get Python23.dll (it should be somewhere on your harddrive).
    Run : pexports python23.dll > python23.def
    This will extract all symbols from python23.dll and write them into python23.def.
    Run : dlltool –dllname python23.dll –def python23.def –output-lib libpython23.a
    This will create libpython23.a (dlltool is part of MinGW utilities).
    Copy libpython23.a to c:\python23\libs\ (in the same directory as python23.lib).
    This trick should work for all Python versions, including future releases of Python. You can also use this trick to convert other libraries.

    4. Get and install SWIG
    SWIG is a wrapper for C/C++ sources. It allows you to use C/C++ functions and classes to Python with a minimum effort.

    Download SWIG binaries for Window ( Swigwin ) from http://www.swig.org, decompress them and add swig directory to your path (the directory where swig.exe is located).

    5 . Write .i files
    Write the .i files corresponding to your c++ files ( for more on how to write these files visit http://www.swig.org )

    6 . Use the following commands to get it going

    A . swig –python –c++ example.i

    output: example.py & example_wrap.cxx
    B. g++ -c *.c++

    output: .o files corresponding to your C++
    C. g++ -c example_wrap.cxx -Ic:\python23\include

    output: example_wrap.o
    D. g++ -shared *.o -o _example.pyd -Lc:\python23\libs -lpython23

    output: _example.pyd

    Hopefully this worked . Now you can do an “ import example “ in python .


    I finally managed to get a 0.1 release out of the door for my breakable toy itunes-importer .

    This is a windows only release , I still have to iron out few kinks for the Mac version .

    You can choose the providers which get queried and can edit ( or paste your own) lyrics before applying them to a track.

    The UI is primitive ( but usable ) , on which I plan to work after I get the mac version working.

    lyrics importer 0.1