Tuesday, August 16, 2011

Book Reviews: CoffeeScript and JavaScript Web Applications

While catching up on my reading backlog, I particularly enjoyed reading two new books I bought recently which I’m going to briefly discuss in this blog post.

1. CoffeeScript - Accelerated JavaScript Development

Cover Image For CoffeeScript

CoffeeScript – Accelerated JavaScript Development, written by Trevor Burnham, gets you up and running with CoffeeScript in no time. This book was recently released by the excellent Pragmatic Programmers which only increased my expectations.  And I must admit that Trevor did a tremendous job explaining the ins and outs of this fairly new programming language. With only a good 120 pages, it’s a very quick read so one is able to start coding away as soon as possible.

The book contains six chapters. The first four chapters basically cover the different language features of CoffeeScript. The last two chapters explain how to use CoffeeScript both on the client-side along with jQuery and the server-side with Node.js. At the end of each chapter there’s an example application (5x5 solitaire) that gets refactored throughout the book as more language features are covered. Every chapter also provides some exercises where you can put your teeth into.

Now, I have to warn you that in order to get the most out of this book, you need to have some decent knowledge of JavaScript. Some of this stuff isn’t trivial and being able to imagine how the underlying JavaScript would look like is almost required.

I highly recommend this book if you want to learn this great little programming language.

2. JavaScript Web Applications

Book cover of JavaScript Web Applications

By the time of this writing, JavaScript Web Applications by Alex MacCaw hasn’t officially been released yet. It’s still in the early release phase which means that there are still a good number of typos in there. That aside, this book contains some rock solid content on how to build client-side JavaScript applications.

This book isn’t about server-side applications with the occasional piece of JavaScript code used in only a couple of web pages. As it’s name implies, this book is all about building MVC applications for the browser using JavaScript.

After the obligatory introductory chapter, chapter 2 up to chapter 6 discuss each part of the MVC pattern and events. The author thoroughly explains each part of this design pattern while implementing his own client-side MVC library. Lots and lots of code here.

Chapter 7 provides a clear explanation on dependency management in JavaScript and how to use module loaders to mitigate this problem. Chapter 8 and 9 cover some of the API’s that come with the upcoming HTML 5 standard, particularly on how to deal with files using JavaScript as well as WebSockets. Chapter 10 deals with testing and debugging. But chapter 11 is definitely my favorite chapter of the book where the author shows a good number of techniques on deploying a JavaScript web application and how to deal with performance. This chapter alone was a real eye opener. Finally, the last three chapters provide an in-depth introduction to three of the most popular open-source client-side JavaScript libraries out there, namely Spine.js, Backbone.js and JavaScriptMVC.

Again I have to warn you that this book is definitely not for JavaScript beginners or the faint of heart. There were times that it even got me scratching my head from time to time. There’s some really neat JavaScript stuff in there, so I highly recommend that you pick up this book some time on your JavaScript learning path.

Happy reading an until next time.

Thursday, August 11, 2011

Dynamic in C# is Broken

Earlier this week, I ran into an issue while using the dynamic keyword in C#. I learned from C# in Depth that there are a couple of restrictions with dynamic, most notably when using extension methods or converting lambda expressions. But apparently there are more restrictions than meets the eye, which came as an unpleasant surprise. Let’s look at some code.

public interface IPresenter
{
    void Start(dynamic startupData);
}

public interface ISpecificPresenter : IPresenter
{}

public class SpecificPresenter : ISpecificPresenter
{
    public void Start(dynamic startupData)
    {
        // ...
    }
}

Here we have an interface called IPresenter with a single method on it named Start. Notice that the Start method has a single parameter which is defined as dynamic. We also have another interface called ISpecificPresenter that inherits from IPresenter. Finally we have a concrete class that implements the ISpecificPresenter interface. So far, so good.

Next we have a class called Activator that we use to kick-off a particular presenter.

public class Activator
{
    public void Start<TPresenter>(dynamic startupData)
        where TPresenter : IPresenter
    {
        var presenter = ObjectFactory.GetInstance<TPresenter>();
        presenter.Start(startupData);
    }
}

The Activator class has a generic Start method with a parameter named startupData that is also dynamic. Here we simply get an instance of a requested presenter from StructureMap and call its Start method. This is how to call the Start method of the Activator class :

var activator = new Activator();
activator.Start<ISpecificPresenter>(new{});

When we run this code, we get the following exception:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'ISpecificPresenter' does not contain a definition for 'Start'.

This had me stumped for a while until I added a cast from ISpecificPresenter to IPresenter in the Start method of the Activator class.

public class Activator
{
    public void Start<TPresenter>(dynamic startupData)
        where TPresenter : IPresenter
    {
        var presenter = (IPresenter)ObjectFactory.GetInstance<TPresenter>();
        presenter.Start(startupData);
    }
}

Now everything works as expected. But I’m not entirely sure why this isn’t behaving as I expected. I guess it has something to do with the fact that the Start method is defined on the IPresenter interface and not on the ISpecificPresenter interface.

image

Although I very much like the flexibility that dynamic objects bring to the C# language, I’m also starting to think that it might not be such a good idea to bring dynamic concepts to a statically typed language. Running into these kind of issues and limitations reinforces this growing opinion.

I would much appreciate it if anyone could enlighten me with a good explanation.

Until next time.

Tuesday, August 09, 2011

Exploring CoffeeScript Part 6 - Show Me the Goodies !

For the final blog post in this series, we’re going to go over a couple of cool little nuggets that one can use to write some elegant CoffeeScript code.

Also check out the previous installments:

  1. And Then There Was Coffee
  2. Variables and Functions
  3. More on Functions
  4. Objects and Classes
  5. Ranges, Loops and Comprehensions

Destructuring Assignments

Destructuring assignments are a great syntactic enhancement for those cases where we want to extract (deeply) nested property values from arrays or objects and store these values into variables.

First let’s have a look at a simple code example written in plain JavaScript where we simply assign some property values of an object to a couple of variables.

var podcast = {
    title: 'Astronomy Cast',
    description: 'A fact-based journey through the galaxy.',
    details: {
        homepage: 'http://www.astronomycast.com',
        rss: "http://www.astronomycast.com/feed/",
        atom: "http://www.astronomycast.com/feed/atom/"    
    }
};

var title = podcast.title;
var description = podcast.description;
var homepage = podcast.details.homepage;

console.log(title);
console.log(description);
console.log(homepage);

Using destructuring assignments in CoffeeScript, we can assign the property values of the object to the variables using a single line of code.

podcast =
    title: 'Astronomy Cast'
    description: 'A fact-based journey through the galaxy.'
    details:
        homepage: 'http://www.astronomycast.com'
        rss: 'http://www.astronomycast.com/feed/'
        atom: 'http://www.astronomycast.com/feed/atom/'

{title, description, details: { homepage } } = podcast

console.log title
console.log description
console.log homepage

Besides objects, destructuring assignments also works for arrays as well.

favoritePodcasts = ['Astronomy Cast', 'Hardcore History', 
                    'Talking Shop Down Under', 'The Changelog', 'Pluralcast'];
[favorite01, favorite02, favorite03, favorite04, favorite05] = favoritePodcasts

console.log favorite01
console.log favorite02
console.log favorite03
console.log favorite04
console.log favorite05

And of course, this can also be used when combine objects with arrays and vice versa.

customer =
    firstName: 'Chuck'
    lastName: 'Norris'
    orders: [
        { 
            Id: 1 
            Item: 'Knuckle Duster'
        },
        { 
            Id: 2
            Item: 'Shuriken' 
        }
    ]

{orders: [ {Item: item1}, {Item: item2}]} = customer

console.log item1
console.log item2

This small little language nugget has definitely come in handy quite more often than I first anticipated. So do keep the availability of destructuring assignments in the back of your head while developing CoffeeScript code.

String Interpolation

The syntax for string interpolation is heavily inspired on the Ruby syntax. Let’s have a look.

podcast = 
    title: 'Astronomy Cast'
    download: (episode) ->
        console.log "Downloading #{episode} of #{@title}."

podcast.download 'the first episode'

In this example we fill in the values of the episode parameter and the title property into the string that we send to the console.log method. Unfortunately string interpolation only works for double quoted strings. I personally prefer single-quoted strings when I’m writing CoffeeScript code. But I gladly make an exception when I want to use string interpolation.

Strict Equality

In JavaScript, we have the == and the === operator. Both equality operators behave the same way only the first performs type coercion while the latter enforces type equality. It's a common best practice in JavaScript to always use the strict equality operator and explicitly perform type casts if needed. CoffeeScript on the other hand only has only one equality operator which always translates to JavaScript's strict equality operator behind the scenes.

So the following equality comparison written in CoffeeScript translates to the JavaScript code shown bellow:

# CoffeeScript
x = 'str'
y = 12
console.log x == y        # Outputs 'false'


// JavaScript
var x, y;
x = 'str';
y = 12;
console.log(x === y);

As I already mentioned in one of the previous blog posts, CoffeeScript emits JavaScript that follows best practices and complies to JSLint without warnings. Always using the === operator is part of being compliant.

Conditionals

CoffeeScript adds some nicely readable syntactic sugar to be used with conditionals using keywords like unless, is, isnt, and and or. Let’s look at an example.

cobol = vb = false
cool = true

unless cobol is cool
    console.log 'CoffeeScript is awesome!'

if vb isnt cool
    console.log 'CoffeeScript is awesome!'

if cobol isnt cool and vb isnt cool
    console.log 'CoffeeScript is awesome!'

I really like how these keywords enable us to write fluently readable conditional statements in CoffeeScript.

The Existential Operator

The existential operator in CoffeeScript, expressed using the ? symbol, returns true except when a particular variable is null or undefined. Let’s look at some code.

someVariable = null
someOtherVariable = 12

console.log someVariable ? someOtherVariable        # Outputs 12

unless someVariable?
    console.log 'someVariable is null'

But the existential operator can also be used to check for null or undefined before accessing a property or the result of a function. This is also called a soak which is the accessor variant of the existential operator. Again some code to clarify things.

podcast =
    title: 'Astronomy Cast'
    description: 'A fact-based journey through the galaxy.'
    details:
        homepage: 'http://www.astronomycast.com'
        rss: 'http://www.astronomycast.com/feed/'
        atom: 'http://www.astronomycast.com/feed/atom/'

    download: -> null

# Outputs 'http://www.astronomycast.com'
console.log podcast.details.homepage    

# TypeError: Cannot read property 'publishingDate' of undefined            
console.log podcast.moreDetails.publishingDate        

# Outputs undefined
console.log podcast.moreDetails?.publishingDate     

# Also outputs undefined
console.log podcast.download()?.data

When the property in question has a valid value, then the expected result is returned. In case the property does not exist or contains null, then undefined is returned instead of a TypeError being thrown.

So that’s it for now. I hope that you enjoyed reading this blog series on CoffeeScript and perhaps you are now also convinced that using CoffeeScript is a viable and productive alternative for writing JavaScript based applications.

Until next time.

Saturday, August 06, 2011

Moving from E-TextEditor to Sublime Text 2

I’ve been using E-TextEditor for more than a year now for doing all my JavaScript, Node.js and CoffeeScript development. You can think of E-TextEditor as TextMate for the Windows platform. I’ve been pretty happy with it throughout this period as it can be extended pretty easily with a whole slew of bundles that are already available for TextMate. E-TextEditor requires you to install Cygwin which happens automatically during installation. Using the Cygwin command-line gave me enough (re-)exposure to a Linux-like environment in order for me wanting to (re-)learn about this other platform. More on that in later blog posts. Although there haven’t been any new versions of E-TextEditor for quite some time now, the current version enabled me to write JavaScript code in a productive way.

Only recently I found out about another editor called Sublime Text 2 (thanks to Ivan Porto Carrero). I downloaded this text editor in order to give it a try and I must say that I haven’t opened E-TextEditor ever since. This second version of Sublime Text is still in development but it’s pretty stable as I haven’t run into any issues so far. The cool part is that this editor is available for both Windows, Linux and OS X which enabled me to move all my Node.js and CoffeeScript development from Cygwin on Windows to Ubuntu Linux. 

CoffeeScript isn’t supported out-of-the-box (yet), so I installed the CoffeeScript  TextMate bundle written by Jeremy Ashkenas (yes, the same one from the CoffeeScript and Backbone.js fame). Also check out this page on the CoffeeScript wiki for more information on how to bring some CoffeeScript happiness to your own favorite text editor.

Setting up this TextMate bundle for use with Sublime Text 2 was actually pretty easy. Just navigate to /home/<my_user_name>/.config/sublime-text-2/Packages in a terminal (or the corresponding file path on Windows) and clone the source of the CoffeeScript TextMate bundle using git:

git clone git://github.com/jashkenas/coffee-script-tmbundle CoffeeScript

Next close all the .coffee files and restart Sublime Text 2. Now we have some nice syntax highlighting and some useful code snippets at our disposal. 

image

It's also possible to hook into the build system of Sublime Text 2. You just need to create a new file named CoffeeScript.sublime-build at the following location:

/home/<my_user_name>/.config/sublime-text-2/Packages/User 

You can add the following to this new file for compiling CoffeeScript

{
     "cmd": ["coffee", "-c", "$file"],
     "selector" : "source.coffee",
     "path" : "/usr/local/bin"
}
or the following for executing/running CoffeeScript code.
{
     "cmd": ["coffee", "$file"],
     "selector" : "source.coffee",
     "path" : "/usr/local/bin"
}

Now when you hit F7, this fresh build command is executed when a CoffeeScript source file is showing in the active tab. It’s also possible to change the build short-key to your own taste through the Preferences menu. 

Unfortunately, there’s only one build command as I would love to create a separate command for compiling and running CoffeeScript code (or perhaps I missed this feature during the excitement Winking smile).

Some more usage is definitely needed for me to learn more about this excellent text editor, but currently I’m pretty happy with it. I also need to find out how well JavaScript is supported and perhaps see how far one can go when doing some C# development using Mono. I expect that there are a good number of productive features in there for me to discover.

I encourage you have a decent look at this excellent tool.

Until next time.

Tuesday, August 02, 2011

Exploring CoffeeScript Part 5 - Ranges, Loops and Comprehensions

For this blog post, we’re going to discuss ranges, loops and comprehensions in CoffeeScript.

Also check out the previous installments:

Ranges

Again a feature that is heavily inspired by Ruby. Using a range we can define an array of consecutive numbers by only specifying the first and the last number.

numbers = [1..10]
console.log numbers        # Outputs [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

This is a so-called inclusive range which is denoted by the two dots separating the bounding numbers. CoffeeScript also provides the concept of an exclusive range which is denoted by three dots instead of two.

numbers = [1...10]
console.log numbers        # Outputs [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

In this case the number of the upper boundary is excluded. Ranges are a small addition to the syntax that can come in handy from time to time.

Loops

As with JavaScript, CoffeeScript also provides us with two different kinds of for loops: one for iterating over an array and one for iterating over the properties of an object.

download = (podcast) ->
    console.log 'Downloading ' + podcast

favoritePodcasts = ['Astronomy Cast', 'Hardcore History', 
                    'Talking Shop Down Under', 'Pluralcast']

for podcast in favoritePodcasts
    download podcast

The for .. in syntax in CoffeeScript is used for iterating over an array while the next example show how a for .. of loop is used for iterating over the properties of an object.

podcasts = 
    'Astronomy Cast': 'http://www.astronomycast.com/',
    'Hardcore History': 'http://www.dancarlin.com/disp.php/hh',
    'Talking Shop Down Under': 'http://www.talkingshopdownunder.com/',
    'Pluralcast': 'http://www.pluralsight-training.net/microsoft/pluralcast/default.aspx'

for key, value of podcasts
    console.log key + ' - ' + value    

A for .. in loop translates to a traditional for loop in JavaScript while the for .. of loop translates to a for .. in loop in JavaScript.  

// Iterating over an array in JavaScript
for (_i = 0, _len = favoritePodcasts.length; _i < _len; _i++) {
    ...
}

// Iterating over the properties of an object in JavaScript
for (key in podcasts) {
    value = podcasts[key];
    ...
}

In the example where we iterate over an array, the for .. in loop can be more compact using the postfix notation. 

download podcast for podcast in favoritePodcasts

How nice is that! Let’s look at some more sweet syntax that CoffeeScript brings us. We can use the ‘when’ keyword for filtering.

for number in [1..10] when number > 5
    console.log number        # Outputs '6, 7, 8, 9, 10'

Filters are supported by both for .. in and for .. of loops. We can also obtain the current index when looping over an array.

favoritePodcasts = ['Astronomy Cast', 'Hardcore History', 
                    'Talking Shop Down Under', 'Pluralcast']
for podcast, i in favoritePodcasts
    console.log (i+1) + '/ ' + podcast

This is only possible when using for .. in loops. We can also use the 'by' keyword to loop over an array with fixed-size steps.

for number in [0..100] by 10
    console.log number        # Outputs '10, 20, 30, ..., 100'

Again, this is only possible when using for .. in loops. Besides all these nice syntax additions for for … in loops, there is also a quite helpful keyword that’s only available when using for .. of loops. We can use the 'own' keyword for iterating over properties that are only defined on the object itself and not on any prototype(s).

Podcast = ->
    @name = 'Astronomy Cast'
    @url = 'http://www.astronomycast.com/'

Podcast::download = ->
    console.log 'Downloading ' + @name + ' from ' + @url

podcast = new Podcast()
for own key, value of podcast
    console.log key + ' : ' + value

Note that we use the :: operator as a shorthand for denoting the prototype property. In this example we used the ‘own’ keyword to skip over any properties defined on the prototype objects, which is simply some syntactic sugar for a hasOwnProperty check in JavaScript. 

var Podcast, key, podcast, value;
var __hasProp = Object.prototype.hasOwnProperty;

Podcast = function() {
    this.name = 'Astronomy Cast';
    return this.url = 'http://www.astronomycast.com/';
};

Podcast.prototype.download = function() {
    return console.log('Downloading ' + this.name + ' from ' + this.url);
};

podcast = new Podcast();
for (key in podcast) {
    if (!__hasProp.call(podcast, key)) continue;
    
    value = podcast[key];
    console.log(key + ' : ' + value);
}

Let’s take this a bit further by diving into comprehensions.

Comprehenions

Everything is an expression in CoffeeScript, which means that this also applies to loops. What better way to demonstrate this than a simple code example? Suppose we want to create an array with even numbers by looping over another array of numbers. This is how it can be solved using the CoffeeScript way.

evenNumbers = (number for number in [1..10] when number % 2 is 0)
console.log evenNumbers        # Outputs [ 2, 4, 6, 8, 10 ]

A for loop in CoffeeScript always returns an array with the result of every iteration which in this case are the even numbers from the first array. Note that we need to enclose this comprehension with parentheses because otherwise we only get the last even number instead of an array with all the even numbers.

If you’re not yet impressed by this language feature, then checkout the following one-line FizzBuzz implementation.

fizzbuzz = (['fizz' unless i%3] + ['buzz' unless i%5] or i for i in [1..100])
console.log fizzbuzz

The implementation comes from this blog post of Ricardo Tomasi which is highly recommended.

While

To make things complete, CoffeeScript also provides a while loop.

count = 0
tenfolds = while (count += 1) <= 10
    count * 10
    
console.log tenfolds    

The while loop in CoffeeScript behaves the same as the one in JavaScript except that it also returns an array of values.

That’s it for now. Until next time.