Wednesday, August 12, 2009

the importance of syntax sugar, ctd.

A while ago I ranted that the common term "syntax sugar" minimizes the practical importance of programming language syntax. One example is when people sometimes state (or imply) that their preference for dynamic languages is tied to the languages' sweeter syntax.

While that may be true, it's a mistake to assume that the saccharine in the syntax is dependent on a language's dynamic typing. This point is amply demonstrated for those who've been keeping up with the development of C#, a static language whose syntax is sufficiently honeyed that the below snippet is remarkably comparable to the Javascript version after it. I tried to match up the code as much as possible to make the comparison easier.

C#

public class myClass
{
public string myProp { get; set; }
static void Main(string[] args)
{
var myc = new myClass() { myProp = "English" };
myc.manhandleStr();
System.Console.Out.WriteLine(myc.myProp);
}
}

public static class ExtMethodClass
{
public static void manhandleStr(this myClass cl)
{
var palaver = new
{
myName = "Nym",
myTaskList = new List<Action<string>>
{
next => { cl.myProp = next + ".com"; },
next => { cl.myProp =
next.Replace("l","r").ToLower(); }
}
};
palaver.myTaskList.ForEach(task => task(cl.myProp));
}
}

Javascript

var myc =
{
myProp: "English"
};

myc.manhandleStr = function() {
var palaver =
{
myName: "Nym",
myTaskList:
[
function(next) { myc.myProp = next + ".com"; },
function(next) { myc.myProp =
next.replace("l","r").toLowerCase(); }
]
};
palaver.myTaskList.forEach(function(task) { task(myc.myProp); });
}

myc.manhandleStr();
alert(myc.myProp);


By the way, other C# programmers might scold you for writing code like this. And yes, I realize that fundamentally (i.e. semantically rather than superficially) the dynamic Javascript object "myc" differs from the static C# instance "myc". Keep tuned for the "dynamic" keyword that's on the way in C# for duck-typing variables going to and from CLR dynamic languages.

No comments:

Post a Comment