Greatest Hits (Vol. 1)

I've never heard of him, but SEVEN VOLUMES of Greatest Hits? That's impressive.

Image from

I’m just realizing that this here blog just celebrated its first birthday — my first ‘hello world‘ post here was May 1, 2012. This seems like a good opportunity to go looking through the archives and point to some older posts that newer visitors/subscribers may not have read.

Ryan Brubaker did a great three part series on using CoffeeScript and Backbone.js:

CoffeeScript has been all the rage lately and I’ve been wanting to hop on board the bandwagon. I’ve also seen Backbone.js mentioned quite a bit and was even more intrigued after listening to this .NET Rocks podcast. I decided to convert some plain JavaScript code I had in a side project to use both CoffeeScript and Backbone.js and see how things went.

The project is a simplified morse code simulator that animates morse code being sent over a telegraph line. The complete source is available here and the running code can be seen here.

I was interested to learn this week that the folks at github recently updated their JavaScript style guide to require that all new JavaScript code be written using CoffeeScript. That’s a pretty significant vote of confidence in my eyes — if you’ve been assuming that CoffeeScript is just a fad, maybe this will prompt you to re-evaluate that stance.

Steve Huey dropped a whole bunch of useful iOS/OS X-related posts:

Along the way, I contributed a few pieces talking about the idea of programming as a liberal art, and as something that most people should learn how to do at some level:

I believe that everyone should learn to write a little code, and play an instrument, and make things out of wood, and tend a garden, and cook, and, yes, do a little plumbing, too. They shouldn’t learn these things because they’ll use them every day to earn a paycheck, they should learn them because it makes them better thinkers, and better able to take care of themselves. On top of that — if vast empires were being built on top of plumbing the way that they’re being built on software, I’d say that anyone who was happy to ignore it as a black art practiced by wizards was making a big mistake. The value of acquiring a new mode of thinking isn’t affected by the fact that most people won’t need to use pointers or recursion on a daily basis.

If you missed these the first time around — check them out.

Game On

Software screen capture

I assume that like many developers, I first became interested in computers while playing computer games. Our family owned a Commodore 64 and I can only wonder how many hours I wasted collecting cave artifacts, dodging neighborhood obstacles on my paper route, and conquering the new world. And the theme song to M.U.L.E. will forever be ingrained into my memory (side note: A really interesting article on the creation of M.U.L.E.).

Unfortunately, I spent all of my time playing games and not learning how to create them. My BASIC knowledge didn’t get past:


I’ve always wanted to learn more about game development and decided to start learning some of the basics. I thought a good first step would be looking into collision detection. One quick Google search later and I came across a great post by Paul Firth on that exact topic. I only needed to get halfway through the article to learn how to animate balls bouncing in a box, animate balls bouncing in a rotated box, and to develop a simple game of Pong (source code can be found here). Paul’s blog contains a wealth of in-depth information about game creation and I hope to get through many more of his posts.

With the advent of HTML5 canvas and the large number of JavaScript libraries/frameworks supporting it, game development has become accessible to anyone with a modern browser and a text editor. It will be very interesting to see how gaming on the web evolves into the future.

The Annotated Turing (with Simulator)

Image of book coverI’m currently making my way through Charles Petzold’s book The Annotated Turing. Petzold’s book, Code: The Hidden Language of Computer Hardware, is a must read for any software developer and is my favorite computer-related book. The Annotated Turing is proving to be just as interesting.

I’m only halfway through the book so I can’t provide a complete review. The first few chapters discuss Alan Turing’s educational background along with some introductory information on computability and number theory.

Petzold then breaks down Turing’s seminal paper, On Computable  Numbers, With an Application to the Entscheidungsproblem. I started this book thinking much of the information would be over my head, but Petzold does a great job of breaking things down and providing easy-to-understand explanations.

Along with Petzold’s commentary, I decided it wold be helpful to create a Turing Machine simulator that I could use as I read through the book. The source code can be found here and a running demo can be found here. The demo includes some pre-configured Turing machine samples from the book, but allows you to define your own machine. Since I’m only halfway through the book, the simulator likely does not simulate the Universal Turing Machine that Turing ultimately designed. I’m hoping to continue updating the code as I finish the rest of the book.

So go out and grab the book, test out different machines on the simulator (or better yet, write your own simulator) and see how the computing age began. It’s a great way to learn about number theory, state machines, and is also a great reminder that we are all standing on the shoulders of giants.

Prototypal vs. Functional Inheritance in JavaScript

Image of code from markus-spiske

If you ever found JavaScript’s prototypal inheritance confusing, do yourself a favor and open this article, open a JavaScript console and code each example in the article. You will definitely come away with a better understanding of how prototypal inheritance works in JavaScript.

After reading the article, I thought a good exercise would be to compare CoffeeScript class definitions vs. the prototypal inheritance style those definitions generate vs. Douglas Crockford’s functional inheritance style outlined in his book JavaScript: The Good Parts.

CoffeeScript Class Definitions

The CoffeeScript homepage gives the following example to demonstrate CoffeeScript’s class syntax:

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

sam = new Snake "Sammy the Python"

Anyone experienced with class-based inheritance should have little trouble understanding this code.

Prototypal Inheritance 

The JavaScript generated by the CoffeeScript compiler uses prototypal inheritance. The compiler first generates a utility function that sets the properties on the child constructor and then sets up the prototype chain. It also creates a convenient super property that allows an object to call methods on its prototype.

__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) 
   for (var key in parent) 
      if (, key)) 
         child[key] = parent[key]; 

   function ctor() 
      this.constructor = child; 
   ctor.prototype = parent.prototype; 
   child.prototype = new ctor(); 
   child.__super__ = parent.prototype; 
   return child; 

The constructor functions are then generated as follows:

Animal = (function() 
   function Animal(name) 
   { = name;

   Animal.prototype.move = function(meters) 
      return alert( + (" moved " + meters + "m."));
   return Animal;

Snake = (function(_super) 
   __extends(Snake, _super);
   function Snake() 
      return Snake.__super__.constructor.apply(this, arguments);

   Snake.prototype.move = function() 
      return, 5);
   return Snake;

sam = new Snake("Sammy the Python");

Notice how easily the Snake constructor can access its Animal prototype using the super property.

Functional Inheritance

In JavaScript: The Good Parts, Crockford advocates a functional inheritance style. Converting the original CoffeeScript code to this style results in the following:

Function.prototype.method = function(name, func)
   if (!this.prototype[name])
      this.prototype[name] = func;
      return this;

Object.method('superior', function(name)
   var that = this;
   var method = that[name];
   return function()
      return method.apply(that, arguments);

var Animal = function(spec)
   var that = {}; =;

   that.move = function(meters)
      alert( + ' moved ' + meters + 'm.');
   return that;

var Snake = function(spec)
   var that = Animal(spec);
   var super_move = that.superior('move');

   that.move = function()
   return that;

sam = new Snake({name:'Sammy the Python'});

The functional style does nothing with prototypes. Inheritance is implemented by creating an object from a base function, similar to a constructor, but without the need for the new operator. Access to super methods is accomplished by extending the built-in Object and Function objects. Notice that any child object wanting access to a super method must create a new function pointing to the super method.

Which One?

So which method is better? Because I’m more familiar with class-based inheritance, I’d rather just use CoffeeScript and ignore the underlying JavaScript implementation altogether. I like the fact that I can look at a CoffeeScript class definition and see on a single line both the name of the "class" and the name of the "class" it extends. In both JavaScript implementations, I have to search other lines to find the object that my object is extending. I find the use of the super property a much more elegant solution when it comes to super methods. The functional method for accessing super methods would not scale well if there are a large number of super methods you want to access.

Even if you decide to work at the CoffeeScript level, it’s imperative that you understand the JavaScript it compiles into. Again, read the article referenced above and the generated JavaScript becomes trivial to understand.

Finally, if you want a much more thorough comparison and richer examples of prototypal vs. functional inheritance styles, this article provides both and makes a very strong case for the use of prototypal inheritance.

Fun with CoffeeScript and Backbone.js : Part 2

Part 1 of this series can be read here.

The project is a simplified morse code simulator that animates morse code being sent over a telegraph line. The complete source is available here and the running code can be seen here.

In this post I’ll discuss the code that handles updating the UI.

Communication Line View

class DecoderView extends Backbone.View
   initialize: ->
      @model.bind('parsedCharacter', @render)

   render: (token) =>
      messageBox = $('#messageBox')
      messageBox.val(messageBox.val() + token)

The CommunicationLineView class is a Backbone.js view class that handles the animation of signals sent across the communication line. In Part 1, I mentioned that the model representing the communication line fires a hasNewData event each time the tokens progress one step through the line. As you can see above, this view is bound to that event and rerenders itself every time it receives the event. The render method iterates over the current tokens and draws the appropriate token shape for each line position.

Decoder Model

class MorseDecoder extends Backbone.Model

   initializeKey: =>
      Omitting code that initializes the morse code key 

   initialize: =>
      @inputTokens = []
      @numEmptyTokensInARow = 0

   processToken: (token) =>
      if token == ''
         @parseTokens() if 
          ++@numEmptyTokensInARow >= 10
      else if token == kWordStopToken
         @parseTokens() if @inputTokens.length > 0
         @trigger('parsedCharacter', ' ')
         @numEmptyTokensInARow = 0

   parseTokens: =>
      if @inputTokens.length > 0
         token = @key[@inputTokens.join('')]
         @trigger('parsedCharacter', token) if 
          token != undefined
      @numEmptyTokensInARow = 0
      @inputTokens.length = 0

The Decoder model is responsible for determining what characters the user has sent across the line. The processToken function is called each time the tokens on the communication line progress one step through the line. The decoder processes the current tokens sent by the user anytime it sees 10 or more empty tokens in a row or receives a word-break token. If the decoder parses a known morse code sequence it fires a parsedCharacter event letting the message field know it needs to rerender itself.

Decoder View

class CommunicationLineView extends Backbone.View
   initialize: ->
      @model.bind('hasNewData', @render)

   render: (tokens) =>
      context = document.getElementById(

      context.clearRect(0, 0, context.canvas.width, 29)
      tokenNum = 0
      for token in tokens
         do (token) ->
            if kDotToken == token
               context.moveTo((50 * tokenNum) + 15, 15)

               context.arc((50 * tokenNum) + 15, 15, 10, 
                0, Math.PI*2, false)

            else if kDashToken == token
               context.fillRect((50 * tokenNum) + 15, 
                15, 25, 10)
            else if kWordStopToken == token
               context.fillRect((50 * tokenNum) + 30, 
                5, 10, 20)
            tokenNum += 1

The Decoder view is a Backbone.js view class that represents a simple text box to display the characters the user has sent across the line. Anytime the Decoder model emits a parsedCharacter event, the Decoder view appends the parsed character to the end of its text box.