CoffeeScript – OR – How I learned to stick with JavaScript

February 1, 2013 in Programming, Uncategorized

I have been playing around with building node.js applications using the Cloud9 online IDE.  With node.js, there is a lot of asynchronous programming and, quite often, you fling around anonymous functions as one of the primary constructs to respond to the asynchronous events in node.js and the various node.js packages available.

You end up writing code like this a lot:

someNodeJSOperation(var1, var2).success(function(err, res) {
    someOtherOperation(res.someProperty).on("done", function(obj) {
        console.log("i'm done!");
        res.end("HELLO WORLDZ!");
    });
});

Some of you may, instead, name these, as they currently are, anonymous functions and declare them like normal functions in the local scope, then pass the function names.  Why?  I dunno, perhaps for readability and a way to easily see the separate functions being used.  It doesn’t seem make it THAT much easier to follow, at least to me.  Also, personally, if a callback or event handler is going to be used in just one case, I want to scope it anonymously.  Anyways, however you do it, I do it like the example above.

As I write anonymous function after anonymous function, I get tired of always typing:

function(yadda, blah) { /* some code here */; return yadda.someMethod(blah); }

You see, I am, traditionally, a C# developer.  Recently, I love working in the JavaScript world and, even more recently, digging node.js; however, I miss lambda expressions!  In the C# world, I haven’t typed the actual word delegate in at least four years.  When I need an anonymous function, I simply type something like:

(yadda, blah) => yadda.someMethod(blah); // does roughly the same as the above JavaScript example, but in a type safe C# way

I want something like this in JavaScript for my node.js applications, but node.js uses the V8 engine (good thing, it’s fast) and the V8 engine is ECMAScript compliant – not compliant to Mozilla’s JavaScript.  While Mozilla has given JavaScript some great new features (like their version of lambda expressions in 1.8), none of these are available in ECMAScript.

I know there are a lot of languages that compile into JavaScript, one of them is CoffeeScript.  There is also a node.js module for CoffeeScript (npm install coffee-script) that allows you to run CoffeeScript right in a node.js application without pre-compilation.  Also, CoffeeScript’s default function syntax is pretty much a lambda expression:

(yadda, blah) -> yadda.someMethod(blah)

In fact, all functions in CoffeeScript are constructed this way.  COOL!  So I decided to port part of my Express application, a simple MVC example that is a basic REST-ful API for dealing with a MongoDB database and some more traditional HTML based views.  This MVC application has a custom written wrapper for Express that mimics the default routing behavior of an ASP.NET MVC3/4 application.

My first task was rewriting my wrapper core.  My wrapper automatically routes “/:controller/:action/:id” to default handlers that finds an appropriate <controller>.js file in the /controllers/ folder of my application (which are just node modules with all the actions as exports), then automatically calls the correct <action> method.  If <id> is present, that is passed into the req.params as req.params.id (as Express already does).  I have special response methods to redirect to another action in the controller and to render a view by looking in the /views/ folder of my application and finding the <action>.html file or a named view.

While I got the job done and my code looked “neat”, I wasn’t as happy with it as my original JavaScript code.  Yeah, I like the function syntax and a few other features; however, CoffeeScript has so freaking much unnecessary syntactic sugar.  I am OK with a little bit of that sugar (see my C# syntactic sugar series), but some seemed way more verbose and obtuse than the equivalent JavaScript’s syntax.  The multitude of ways to construct objects and arrays were just asking for inconsistent messiness.  Plus, ultimately, I like a good mixture of compact, performant, but still readable JavaScript.  CoffeeScript looks compact, is somewhat readable, but I am not so sure of the performance benefits.  The JavaScript output of some of my CoffeeScript, while relatively safe, is significant longer, and, honestly, I do not know of the performance impacts, to be honest.

Lets take a look of a couple of CoffeeScript functions I wrote and their JavaScript equivalent:

argRules = (args, rules...) ->
    rules.sort((i1, i2) -> i1.length - i2.length)
    len = args.length
    for rule, i in rules
        if len <= rule.length || i == rules.length - 1 then return rule.func(args) 

view = (args...) ->
    viewName = (if args.length == 0 then @action else (if args[0] instanceof String then args[0] else @action))
    model = (if args.length == 1 && args[0] not instanceof String then args[0] else (if args.length > 1 then args[1] else null))
    fullPath = "#{@controller}/#{viewName}"
    @render(fullPath, model)

Not too bad, right?  Here is the equivalent JavaScript it produces:

var argRules, view,
  __slice = [].slice;

argRules = function() {
  var args, i, len, rule, rules, _i, _len;
  args = arguments[0], rules = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  rules.sort(function(i1, i2) {
    return i1.length - i2.length;
  });
  len = args.length;
  for (i = _i = 0, _len = rules.length; _i < _len; i = ++_i) {
    rule = rules[i];
    if (len <= rule.length || i === rules.length - 1) {
      return rule.func(args);
    }
  }
};

view = function() {
  var args, fullPath, model, viewName;
  args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
  viewName = (args.length === 0 ? this.action : (args[0] instanceof String ? args[0] : this.action));
  model = (args.length === 1 && !(args[0] instanceof String) ? args[0] : (args.length > 1 ? args[1] : null));
  fullPath = "" + this.controller + "/" + viewName;
  return this.render(fullPath, model);
};

Ick!  While, the original that I wrote in JavaScript is somewhat similar to this, the practices that the CoffeeScript compiler employs seem a little verbose to me.  I var all my scoped variables, but usually declare and assign in one go.  I probably wouldn’t have used arguments to manipulate my argument list if I knew I had to write all that; I would have passed in an array, instead, which is what I originally did, but changed it in my CoffeeScript to take advantage of its “features”.  The for loop in the second method has some safety features on length testing, which is nice, but I don’t really need.  Also, using if-then-else instead of the : ? operator – why?? Don’t even get me started on variable declaration and scoping (insert sad face).

There are some nice features. There is an easy way to keep this in a sub-function’s scope. Some of the array shortcuts are useful. Object and array comprehensions and destructuring seems useful. Even with their usefulness, is it creating extra script code that I don’t need under the hood? I dunno.

The price for the convenience, I guess, is less control of the underlying code.  I just would have written it differently.

I just want freakin’ lambda expressions in my freakin’ JavaScript, is so freakin’ hard to ask for?

… hmm, TypeScript, interesting…

Sorry for the lack of updates

January 26, 2012 in Miscellaneous

I have a couple new ideas for articles coming up.  Both are based on JavaScript.  One is based on more jQuery-related stuff and another will be an opinion of node.js from the perspective of a newbie.

Stay tuned!

Sugary C#, part 3 – lambda expressions

November 9, 2011 in Programming

Part 1 explored a part of C#’s syntactic sugar I didn’t care for: LINQ syntax.

Part 2 explored a part of C#’s syntactic sugar, while I used a lot, that could be a source of confusion: var.

Today’s installment covers a syntactic sugar feature that was, to me, long overdue. It is largely responsible for making the LINQ syntax readable.  Also, it makes anything involving an anonymous method less cumbersome to use: lambda expressions.

Simply put, lambda expressions are a C# shorthand for any anonymous method.  They can be used practically anywhere the anonymous method delegate syntax for C# is required.  Here is a simple example:

public int CalcFromDelegate(Func<int, int> func)
{
    return func(50) * 4;
}

// calling with the delegate syntax
var result1 = CalcFromDelegate(delegate(int param) { return param + 5; });

// calling with the lambda expression syntax
var result2 = CalcFromDelegate(param => param + 5);

var match = (result1 == result2);  // match should be *true*

So… what is going on here?  Obviously, the example is meant to show that the two ways of calling the anonymous method are practically identical.  How does the syntax work?

  • Lambda expressions use the => token.  Only lambda expressions use this token, so seeing that indicates there is a lambda expression present.
  • The left side of the => token has the expression’s arguments.  The argument types are inferred from usage, much like var can infer a declared identifier’s type from usage.  In the above example, the left side has the param argument.  Since it is being used in an anonymous method that wants a delegate of type Func<int, int> (which is a delegate that is a method of a a single input parameter of type int and returns an int), we can tell that param is type int.
  • The right side of the => token is the method body.  A lambda expression with a single statement and no curly braces ( { } ) is assumed to be the return value of the method.  The above example simply has param + 5 after the =>, so the method just returns the result of that basic expression. No return keyword is required in this instance.
This allows simple and short syntax to do computations that usually take twice the text to represent in the traditional delegate format.  Let’s look at a practical example using LINQ extension methods (as I dislike LINQ syntax, sue me – not really, please don’t sue me).  The following code has a made-up LINQ chain using various lambda expressions.
// assume listOfData is a enumerated type containing instances of a class
// called Person that includes a Name (string), Age (int), and Salary
// (double) properties

var result = listOfData
    .Where(x => x.Name.StartsWith("John") && x.Age > 30)
    .OrderBy(x => x.Salary)
    .Select(x => new { Name = x.Name, Bonus = x.Salary * 0.10 });

// result is an enumerated anonymous type with properties Name and Bonus,
// sorted ascending by Salary, with People whose name starts with John
// and is over the age of 30

C# 3.5 (and 4.0) can infer the types of the variable x in each of the three lambda expressions (in this case, all three are of type Person).  The OrderBy and Select methods are also generic methods, the compiler can infer their type from the return type of each lambda expression.  The Where expression must return bool, and the return expression in the lambda used there is obviously bool. The code, even if you aren’t too familiar with LINQ and only had this introductory look at lambda expressions, is not too hard figure out:

  • Use Where to filter the list.  It runs the anonymous method for each Person instance, only keeping the ones where the return value of the lambda expression is true.
  • With the filtered list, re-order (ascending by using the OrderBy method) it by the Salary value of each Person instance filtered in the previous call.
  • Finally with the final filtered and ordered set, return a new enumerable set with some anonymous type instances, each only having the Name and their calculated Bonus.  The Select method allows us to make new projections of a enumerable set (using anonymous types – which is another topic, for another day).

Now, what if we didn’t have lambda expressions?  What if LINQ was available, but we had to use the delegate syntax?  Lets look:

var result = listOfData
    .Where(delegate(Person x) { return x.Name.StartsWith("John") && x.Age > 30; })
    .OrderBy(delegate(Person x) { return x.Salary; })
    .Select(delegate(Person x) { return new { Name = x.Name, Bonus = x.Salary * 0.10 }; });
Ouch, that’s an eyesore, at least to me.  It works, it does the same thing, just a lot more verbose, especially in a context that shouldn’t require such verbosity.  This becomes especially true when using the actual LINQ syntax.  Let’s look at the lambda version of the above:
var result = from x in listOfData
    where x.Name.StartsWith("John") && x.Age > 30
    orderby x.Salary
    select new { Name = x.Name, Bonus = x.Salary * 0.10 };

This has an implied lambda expression syntax.  The from statement defines the common parameter name (x for type Person) that will be used in the 3 lambda expressions for the where, orderby, and select clauses.  I do not know if the delegate syntax is even available in the LINQ syntax for LINQ queries. Finally, beyond LINQ usage, you can simply use lambda expressions in most places where an anonymous delegate is required:

// declare a delegate in a class
delegate int SomeNumberFromString(string input);

// later in a method
SomeNumberFromString func = s => s.Length;

var result = func("what");  // result is 4

If the right side of the => token needs to have multiple lines, simply put it in a code block like in a normal method definition.  If you need to return a value in this form, you must use the return keyword:

// declare a delegate in a class
delegate int SomeNumberFromString(string input);

// later in a method
SomeNumberFromString func = s =>
{
    s += "SomeMoreLetters";
    return s.Length;
};

var result = func("what");  // result is 19

Need multiple arguments?  Delineate the arguments with a comma, and put them in parenthesis:

Func<int, string, double> method = (x, s) => (double) s.Length / x;

var result = method(2, "hello"); // result is (double) 2.5

No arguments?  Empty parenthesis says the lambda expression has no arguments:

Func<bool> method = () => true;

var result = method();  // result is *true*

Finally, you can even use lambda expressions for code that has no return value (a void ”return”).  In this case, the right side must always be a statement block (in curly braces):

Action<string> doSomething = x => { Console.WriteLine(x + " w00t!"); };

doSomething("yay");  // outputs to console: yay w00t!

Action doSomethingWithoutParam = () => { Console.WriteLine("w00t!"); };

doSomethingWithoutParam();  // outputs to console: w00t!

Lambda expressions are my favorite addition to C#.  They make using anonymous methods significantly less of a hassle.  I simply hated typing out the delegate syntax.  Once you get use to the syntax, it is pretty easy to read and very concise.

Do you use lambda expressions much?  Do you still rather use the classic delegate syntax for anonymous methods?  Do you see a reason when you must use one or the other?  Give me some feedback, I am interested on you opinions on the use of C#’s lambda expressions.

Now, we just need all browsers to support a lambda expression syntax for the various implementations of JavaScript.

jQuery and jQuery Mobile

October 29, 2011 in Programming

jQuery Mobile logo

jQuery Mobile logo

I promise, this blog isn’t all C#.  I do a significant amount of JavaScript development too.  I am working on, hopefully, a intuitive templating library with JavaScript, but that is nowhere usable by the public yet.

Another part of JavaScript that I am heavily into (as is most JavaScript developers) is jQuery.  jQuery is nothing new, it has had a dominant presence in the JavaScript framework for a little while now.  It is easy to see why, of all the frameworks I have dabbled in, jQuery is:

  • Small.  When gzipped and minified, it is 31K, as of 1.6.4.
  • Easy to learn.
  • Great performance.
  • Leverages knowledge you may already know – primarily CSS selectors.

With jQuery, there are a couple of sister frameworks for building UIs: jQueryUI and jQuery Mobile.  jQuery alone is a utility, event, and DOM manipulation framework.

jQueryUI is a making-web-2.0-applications-alive framework, with a support for styled buttons, auto completes, toggles.  Primarily, it provides rich support for things like dialogs, progress bars, tabs, dragging, dropping, sorting and animation.  It is a mature framework that is going under re-construction for a simplified API so extensibility is even easier.  I use this for the REAL TIME REHAB project I work on on the side.

jQuery Mobile is a new addition to the jQuery suite of frameworks. jQuery Mobile specializes in making mobile- and touch-friendly UIs that can be used across mobile devices and desktops.  It is in an RC2 version (release candidate).  The full version 1.0 is literally in the coming week or two.

jQuery Mobile is something I have used quite a bit in the last few months.  A project at the day job required a touch screen interface, so we started using jQM (a beta version) as the basis of the UI.  We heavily modified a good portion of the CSS and the framework was hacked or extended to support features we needed.  It has serves us well, even though we never got beyond a late beta version of jQM (just too late in our development cycle to upgrade to the RC and trying to fix any breaking changes).

Admittedly, I have become a huge fan of jQM.  In its short lifetime, it has become a real feature complete framework:

  • HTML5 semantic markup defines most the interface.  You can make a mobile friendly website with jQM without writing a single line of code.  You provide “data-” attributes to elements that jQM recognizes and transforms the elements for you.
  • Small.  about 25K gzipped and minified.  That is smaller than the core jQuery library.  The gzipped and minified core CSS is about 7K.
  • Works well on a variety of devices and browsers.  Click here for the graded browser support.
  • Provides support for the major form input elements.  Has custom select list support and support for some of the HTML5 input controls. jQueryUI, on the other hand, doesn’t even address input elements very much at all.
  • Gracefully degrades.  It will simply degrade back to default HTML rendering if your browser sucks.
  • AJAX friendly.  Forms can be a classic style, or automatically use AJAX-submitted forms.

The framework, as of RC2, is easily extensible.  It uses, essentially, the same widget framework that jQueryUI uses.  It is easy to make new components.  They even added a theme-roller to easily make your own theme swatches (http://jquerymobile.com/themeroller/ - it is in beta – also, just to make sure I do not appear totally biased, jQueryUI also has had a Theme Roller for a long time) and get on-demand, custom CSS.

How easy is it to use?  Well, for fun, and because I have meaning to update my resume for a long time, I made a quick interactive, jQuery Mobile-based resume.  I added some custom script to do some list sorting and special handling for the popup menu on the footer of each page.  Everything else is semantic HTML5 that jQM interprets.

Also, note, while the resume looks like it spans several pages, it is actually all just one HTML file.  jQM can split up an HTML document into several jQM “mobile pages”.

The CSS for the interactive resume also is resolution-aware.  Using CSS media queries it can format the layout of the page to support a few resolution levels.  Try looking at it on a desktop, then on a mobile device (portait and landscape).

The page is self-contained.  The custom CSS and scripts are in the page itself.  The external libraries (jQuery and jQM) are included via a public CDN.  You can take this page, change it with your information, and upload it somewhere else, and would probably work just fine.

Personally, I didn’t hand-craft each line of HTML.  On my local development machine, I wrote a quick MVC3 app that spits out the HTML file.  I then just copied it to my web space.  The reason I did it this way is that I can make different views for, perhaps, a PDF version, a highly summarized version or a straight text version as needed without changing my data model (which is a quick and dirty .NETclass with my “resume data”).

Final NOTE:  I am not looking for a new job.  I did want to update my resume as the previous version was getting ugly and dated.

Click this and take a peek at my resume!

Sugary C#, part 2

October 25, 2011 in Programming

What was part 1?  LINQ vs. LINQ was part 1, essentially.  As I was writing about using LINQ syntax versus extension methods, I started thinking about all of the other obvious syntactic sugars in C#.  While, personally, I am not a fan of the LINQ syntax, there are other sugary parts of C# I do not mind so much, and actually use quite a bit.  Today’s article is about a single keyword that seems to have a lot of C# developers (at least the ones I know) split down the middle of usefulness/annoyance.

var

Yup, that keyword seems to get a lot of opinions on why it should be used and why it should not be used.

For the uninitiated (e.g., those who are new to C# or have lived under a rock for three years), var is a shortcut to declaring identifiers in a particular scope.  Unlike JavaScript’s var, which is the only way to declare identifiers and all identifiers are not strictly typed, C#’s var is completely type-safe and bound at compile-time.

That is right, the C# compiler will infer the type of the value being assigned the identifier at compile-time and statically give the identifier the correct type.  There are some caveats:

  • A value must be assigned to the identifier when the identifier is declared.  This is how the type is inferred.
  • Once the type is determined, the type of the identifier does not change for entire scope of the identifier.
  • The type will not change at run-time.
  • If the value assigned to an identifier declared with var is ambiguous, the compiler will complain.  You will have to cast the value to a specific type to compile without errors.  (especially true for assigning a null value)
  • var can only be used in a local method scope.  You cannot use it in member declarations in a class or struct.  It cannot be used as the return type of any method.

var is not a dynamic type (C# 4.0 does provide a dynamic type. I might go over that in a future article.).  An identifier declared with var has full Intellisense enabled.  You can even hit F12 on the var keyword of the identifier being declared and Visual Studio will jump you to the correct declaration in your project.  So, why would you want to use var?

  • You don’t want to worry about identifier type declarations when changing type names or namespaces.
  • Faster to type, no need to find the correct type to declare your identifier with.

Yup, pretty much pure sugar.  So, what would be the reasons to not use var?

  • Lack of readability in some cases, especially if the type of the identifier is not evident in local scope.  Intellisense helps this greatly, but not everyone will be looking at code in Visual Studio.
  • It is lazy.

Maybe laziness is not a problem for you (it certainly isn’t for me), but the readability is a problem for a some developers. Let’s consider a couple of examples.

Example 1:

public string ExampleMethod1(string arg1, int arg2)
{
    string arg2str = arg2.ToString();
    return string.Format("{0} {1}", arg1.Length, arg2.Length);
}

public string ExampleMethod1var(string arg1, int arg2)
{
    var arg2str = arg2.ToString();
    return string.Format("{0} {1}", arg1.Length, arg2.Length);
}

The above example has two methods that have the same exact result.  In fact, the MSIL generated for the above methods (sans the method name) is the same.  The example that uses var has good readability and is understandable from a quick glance.  The type inference is based on a local variable and the fact that it is assigned the result of the ToString() method gives it away that arg2str is a string.

Here is another example:

Example 2:

public string ExampleMethod2(string arg1)
{
    MyClass c = MyStatic.GetInstance(arg1);
    return c.ToString();
}

public string ExampleMethod2var(string arg1)
{
    var c = MyStatic.GetInstance(arg1);
    return c.ToString();
}

The example here that uses var certainly has a readability issue now.  Not knowing anything about the static method MyStatic.GetInstance() raises questions on what type c is.  The compiler knows and Visual Studio knows.  Moving your mouse over c in the return statement will reveal the correct type.  Also, the MSIL should be the same.  The compiler is 100% OK with this.  Your eyes, however, may have “trouble”.  Especially, perhaps, if I gave you just this snippet of code:

public string ExampleMethod2var(string arg1)
{
    var c = MyStatic.GetInstance(arg1);
    return c.ToString();
}

If this was all that was presented, you would have no idea what type c was, without being told.

var - love it or hate it, it does make coding faster and easier.  It is not always readable, however.  Personally, I am guilty of over-using it at times.

Are you a var-hater or a var-lover?

C# – LINQ syntax vs. LINQ extension methods

October 24, 2011 in Programming

The LINQ syntax in C# is purely syntactic sugar for the LINQ extension methods in the System.Linq namespace.  Now, syntactic sugar doesn’t bother me so much if it seems to provide a better coding experience while still being readable.  However, the LINQ syntax in C#, however, has always reeked of “excessive crap that I have trouble formatting and reading.”

In short: I don’t want SQL in my C#, I want C# in my C#!

Anyway, here are two examples of the same LINQ query.  The first example uses the LINQ syntax, the other one just calls extension methods.

C# LINQ Syntax:

from u in Users
where u.Type == UserTypes.Admin
orderby u.Name
select new { Name = u.Name, Email = u.Email }

Regular C# syntax

Users
    .Where(u => u.Type == UserTypes.Admin)
    .OrderBy(u => u.Name)
    .Select(u => new { Name = u.Name, Email = u.Email });

Now, I don’t know about the rest of the C# world, but the LINQ syntax seems very un-C#-like.  Also, for long queries, I am not really sure a of proper way to format the LINQ code.  Also, I can never remember the subtleties of the LINQ syntax (admittedly, this is from disuse).

The second form seems more natural to me.  Each line has it’s own defined lambda expression.  I could use different lamda expression arguments for each individual call.  I can ALSO mix-and-match some of the calls.  Like:

Users
    .Where(u => u.Type == UserTypes.Admin)
    .Select(u => new { Name = u.Name, Email = u.Email })
    .OrderBy(u => u.Name);

The output of this would be the same.   Also, using the regular C# syntax and Intellisense allows me to explore the LINQ extension methods and find alternate ways of tackling a problem with LINQ that the LINQ syntax does not allow me to do.

There is one thing that the LINQ syntax does make easier:  Joins.  The extension method syntax can get a bit messy for join operations, especially when you get into outer-joins.

Your preference? Am I missing something by using the LINQ syntax that would really make using it easier?

Programming, stuffs, and, very occasionally, cats – WELCOME

October 24, 2011 in Miscellaneous

using Cats.Linq;

Yes, I made a blog – the world will not explode, I promise.

Switch to our mobile site