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);
Filed under: Uncategorized | Leave a Comment
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.
Filed under: Uncategorized | 1 Comment
Object Graph Retrival DSL ..
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;} ;
Filed under: Uncategorized | Leave a Comment
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;
}
});
The above code plugs in a custom selector for matching all the elements which have class starting with a certain string so
$('input:classStartsWith('highlight')')
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 .
Filed under: Uncategorized | Leave a Comment
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[prop.name] = obj[prop.name] || (prop.isArray ? [] : {});
_setValue(obj[prop.name], 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
};
}
};
Filed under: Uncategorized | 3 Comments
Tags: jquery
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..
- Sitar , Yes – Viva La Vida , Coldplay ( http://www.imeem.com/dazhini/music/3IS9giaS/coldplay_yes_chinese_sleep_chant/
- Tabla , Citizen of the Planet – Flavors of entanglement Alanis Morissette
( http://www.youtube.com/watch?v=TmnLBPENNys) - Tabla Again , Pity And Fear – Narrow Stairs , Death Cab For Cutie ( http://www.youtube.com/watch?v=pyyaSbSC61MAhh..Now I get what they meant when they said this is their *Experimental* Album
- Sitar , Loser – Mellow Gold , Beck ( http://www.youtube.com/watch?v=TJN3PGqDRNg )
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)
Filed under: Uncategorized | 1 Comment
Java 5.0 vs C# 3.0 Shootout
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
- No Type Erasure in C # , new T() anyone ??
- Value types like int or Enumeration can be be used as type parameter so MyClass<int> is perfectly valid.
- No Wildcards in C# which I terribly miss , Cast<>() from Linq Enumerable doesnt look too pretty
- Java has better support for covariant and contravariant for type parameters , I dearly miss ” ? ” from java.
- 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
Both of which can be done in java side ..Ok so this round goes to Java
Round 3 : IDE’s
This round is a TIE..
Round 4 : Packaging
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..
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 ..
This Round goes to Java
Filed under: Uncategorized | Leave a Comment
