This blog has moved to http://ikhwanhayat.net

Friday, August 04, 2006

On-The-Fly Methods

Joel Spolsky several days ago talked about passing anonymous method as argument, and gave these JavaScript example:

function Cook( i1, i2, f )
{
    alert("get the " + i1);
    f(i1);
    f(i2);
}

Cook( "lobster", 
    "water", 
    function(x) { alert("put " + x + " in pot"); } );
Cook( "chicken", 
    "coconut", 
    function(x) { alert("boom boom the " + x); } );

-- output --
get the lobster
put lobster in pot
put water in pot

get the chicken
boom boom chicken
boom boom coconut
Leon Bambrick, quoted Joel's post today, and gave some more example like this in C# by using delegate. His example use the ordinary delegate where you have to declare the delegate up front. But using C# 2.0, you can use anonymous delegate, passing the method body on-the-fly when invoking the caller method. Read comments to Leon's post for example. I really liked this when I first encountered it in JavaScript. Can be really handy at times, like treating methods like "variable". And now, I'm pleased to know that I can do it in Ruby (I try to pick up Ruby just recently). As I understand it, this is the traits from Smalltalk that Ruby inherits from. In fact, lots of thing in Ruby use this kind of technique, they call it block. Quite hard to swallow for first-timers, but definitely exciting. This is the kind of knowledge I seek when learning new languages. Not just different syntax, but different way to do things. And after that, you can try to apply the idea in your "main" programming language.

3 Comments:

At 8/06/2006 11:55:00 pm, Anonymous Anonymous said...

Look nice, but seem this type of programming has been included in Data Structure programming, if i'm not wrong. Anyway, thanks for good explanation!

 
At 8/07/2006 12:41:00 am, Blogger Ikhwan Hayat said...

Ermmm, data structure? Dont remember learning things like this is data structure class (or maybe i was sleeping).

 
At 8/07/2006 02:18:00 pm, Anonymous Anonymous said...

joel ask "Can Your Programming Language Do This?"
yup, pythonistas do this all the time :)

 

Post a Comment

<< Home