Author Archive


January 2nd, 2012 12 comments

It’s time for another one of those self-indulgent “what am I going to do with the next year?” posts. I can’t believe it’s been a whole year since the last one.

First off, I’m going to look at the past year. Finish SICP I definitely progressed with it, but not finished yet. Get a decent online portfolio As a matter of course I put all my toy projects into my Github account, but there’s nothing particularly exciting there. Keep blogging I did pretty well with this until October. Do something good in node.js I started this, and I’d like to carry on at some point. I definitely get Node now, but I want to play more. Learn a functional language I’ve started reading/working through the print version of Learn You a Haskell for Great Good, which is brilliant. Stack Overflow I kinda neglected my SO profile over the latter half of the year. Oh well.

So, those were the steps I’d laid out for myself for last year, but they were all in service of my main goal of 2011, which was to

establish myself as someone who knows what they’re doing and people will pay to code stuff.

With this, everything went better than expected.

In August, two crazy things happened. First, I was approached by a talent scout at Facebook and asked if I was interested. I said hell yes, so they sent me a pre-interview puzzle thing to complete. This was my solution. They liked that, so I went on to have three phone screens. After those they rang me up and asked if I’d like to come out to Palo Alto for an interview! My mind was officially blown at this point.

Things got even crazier when I received an email the night before I was due to fly out to see Facebook, from a recruiter at Twitter. I’d been referred by JavaScript guru Angus Croll, to whom I’m eternally grateful.

Anyway, I went out to Palo Alto, visited San Francisco, had my interviews at Facebook HQ, and flew home. After I got back I had my phone screens with Twitter, followed by another offer of an interview. I found out on my way to the interview in San Francisco that I didn’t get the Facebook job – they were looking for a JS/CSS developer, and my CSS skills aren’t top notch. Also, I think they picked up on my general meh-ness about the actual Facebook product.

So, another trip to San Francisco (which cemented my growing suspicion that SF is the place for me – such an awesome city), more interviews, and then, a few days later, a job offer! So, now I’m living in San Francisco, working on what is probably my favourite thing on the internet, with legends. And it’s awesome.

So, anyway, 2012.


I don’t want to rest on my laurels. There’s still so much more I want to learn.

  • Finish Learn You a Haskell for Great Good

  • Finish SICP

  • Write something decent in Node (still)

  • Read more of the books on the first page of this legendary Stack Overflow question (I’m at about 30% so far)

  • Branch away from JavaScript a bit, maybe with Scala

  • Start blogging again (this is my first post since October – whoops!)

Anyway, here’s to 2012!

Categories: Miscellaneous Tags:

Three years on

October 24th, 2011 6 comments

Portal cake with three candles On 23 October 2008, on holiday in Devon with my girlfriend, I read an article in the Guardian’s Technology section about the UK games industry. From that point on I was certain that I wanted to become a developer of some kind. I wrote more about this in Finding your passion.

It’s now three years and a day since then, and I’m winding down at my current job in preparation for a move to San Francisco, as I somehow managed to land myself a job at Twitter as a junior front-end engineer. Which was nice. I’m unbelievably chuffed that I’ve managed to get to where I am today, and I hope the next three years will be just as exciting as the last :)

Categories: Programming Tags:

Closures vs Objects: FIGHT

September 23rd, 2011 17 comments

In JavaScript, there are two main patterns for creating objects with state - plain JavaScript objects and closures. In this post I’m going to highlight the similarites and consider the pros and cons of the two approaches.

An object is an entity with state and methods to access/modify that state. There are two main approaches to this, which I’ll be calling “objects” and “closures”. For the rest of this post I’ll only use the word object to refer to plain JavaScript objects, in an attempt to avoid confusion.

function Person(name) { = name;

Person.prototype.sayHi = function () {
  console.log('Hi there, my name is ' +;

function person(name) {
  //using object literal but state held in closure, not in object
  return {
    sayHi: function () {
      console.log('Hi there, my name is ' + name);

Now, there are infinite variations to the above. I’m using native JavaScript constructors in the object version, but it doesn’t have to be that way. For example, I could make a function that returns an object, without having to use new:

//alternative object
function person(name) {
  return {
    name: name,
    sayHi: function () {
      console.log('Hi there, my name is ' +;

Alternatively, I could come up with a more convoluted example that caches the sayHi method so it’s shared between instances.

The point is, using objects, state is shared through this. Whenever you call a method on an object, e.g.

var dave = new Person('Dave');

this within the method will be equal to the object it was called upon. When using closures however, state is shared through the lexical scope. This highlights the first key difference between objects and closures: access to the internal state.

There are three ways to mutate the internal state of an object in JavaScript. I’ll illustrate with some examples:

//Obtain a reference to the object and assign new properties
function changeName(object, newName) { = newName;

changeName(dave, 'Bob');

//Attach a function to the object and call it as a method on the object
function changeName(newName) { = newName;

dave.changeName = changeName;

//call/apply a function with the object as the context, 'Bob');

With closures, on the other hand, there is only one way to mutate the internal state – be inside the scope of the closure:

function person(name) {
  //to change `name`, you *must* be defined somewhere inside this function

  return {
    sayHi: function () {
      console.log('Hi there, my name is ' + name);

This can be a blessing and a curse. The advantage of objects over closures is that you’re not limited in the functionality you can add to an object by location in the source code. If you decide that you need to add more functionality to an object, you can do this at any point in your codebase. With a closure the only way to add functionality (with access to the internal state) is to define it somewhere inside the function that creates the closure.

The advantage of closures over objects is the same as the disadvantage but from the perspective of third party code. With an object, anybody can add or change functionality on your object, and access its internal state. With a closure, the internal state is private – it can’t be accessed from outside the closure without the use of accessor functions.

Another advantage that objects have is in terms of memory usage. With a closure, by definition, for a function to have access to the internal state it must be defined inside the closure. That means that each new closure created must have its own version of the function. Objects on the other hand have no such limitation. A function that reads from and writes to this need only be defined once – it can then be added to any object, either shared via the prototype system or through other means.

An advantage that closures have is that you don’t need to keep track of this. With closures it’s simple – you’re either in the correct scope or you’re not. With objects, if you’re in a method called on an object then this is that object, but if the method gets detached from its object (e.g. when passed as an argument) it loses its binding, or if you have a nested function inside the method. Then you need to start messing about with call and apply, and bind and other fun stuff.

So, when should you use objects and when closures? If you’re making hundreds of object-type things then they should probably be objects. If there are only a few and you have security concerns then closures are a better bet.

Privacy isn’t just a security issue – it’s useful for creating a clean separation between the public API and the private implementation. Some developers would say that JavaScript doesn’t provide privacy, so you should get used to writing objects with everything public, and tell users of your code to just not touch certain properties (for example those with a leading underscore). I think it’s useful being able to enforce privacy – it makes sure that no-one will ever write code that’s reliant on an implementation detail of yours.

Because of this, I tend to favour closures, falling back to objects when memory becomes a concern, but that’s largely a personal preference.

Understanding typeof, instanceof and constructor in JavaScript

September 18th, 2011 18 comments

They say in JavaScript “everything is an object”. They’re wrong. Some types in JavaScript are so-called “primitive types”, and they don’t act like objects. These types are:

  • Undefined
  • Null
  • Boolean
  • Number
  • String

The confusion comes from the fact that the boolean, number and string types can be treated like objects in a limited way. For example, the expression "I'm no object".length returns the value 13. This happens because when you attempt to access properties or methods on a primitive value, JavaScript instantiates a wrapper object temporarily, just so you can access its methods. ‘Cause JavaScript’s nice like that. I’m not going to go into more details here, but Angus Croll wrote about The Secret Life of JavaScript Primitives, so that would be a good place to learn more.


typeof is a unary operator, just like the ! operator. It returns a string representing the type of its operand. Here are some examples:

typeof 3; // returns "number"
typeof 'blah'; //returns "string"
typeof {}; //returns "object"
typeof []; //returns "object"
typeof function () {}; //returns "function"

typeof has its idiosyncrasies. For example, typeof null returns "object", and typeof /[a-z]/ returns "function". Again, Angus Croll has written more on this subject than I have space for here.

So, basically typeof is used for telling apart the different primitive types (as long as you don’t care about null). It’s no use for telling different types of object apart though – for most objects typeof will return "object".


constructor is a property available on all objects’ prototypes, and it is a reference to the constructor function used to create the object. So, ({}).constructor returns the Object constructor function (the parentheses are needed to clarify a syntactic ambiguity) and [].constructor returns the Array constructor function. Likewise, it will return your custom constructor function:

function Person(name) { = name;

var dave = new Person('Dave');
dave.constructor === Person; //true

Remember that unlike the typeof operator, constructor returns a reference to the actual function. Another gotcha: because constructor is part of the prototype, if you reassign the prototype to a constructor function, e.g. Person.prototype = {};, you’ll lose the constructor property.


instanceof is a binary operator – its syntax is instance instanceof Constructor. So, to continue the above example:

dave instanceof Person; //true

The difference between instanceof and the constructor property (apart from the obvious syntactic difference) is that instanceof inspects the object’s prototype chain. So, going back to our friend dave again:

dave instanceof Object; //true

This is because Person.prototype is an object, so Object is in dave‘s prototype chain, therefore dave is an instance of Object.


So, if you’re dealing with primitive objects, use typeof to distinguish them. Because typeof returns "function" for functions, it can also be useful for checking if an object member or a function argument is a function. If you’re working out the constructor of an object, use its constructor property. And if you’re dealing with lengthy inheritance chains, and you want to find out whether an object inherits from a certain constructor, use instanceof.

Categories: Programming Tags: ,

If the only tool you have is Java, everything looks like a class

September 3rd, 2011 16 comments


There’s a common phrase used within software development:

If the only tool you have is a hammer, everything looks like a nail

It exists in various forms, but the original source is the Law of the instrument, or Maslow’s Hammer.

I started thinking about this while reading through Head First Design Patterns today (a bizarre book, not quite sure yet whether I can recommend it).

What struck me was that the solution to every design problem in Java revolves around writing a new class. It just astounds me that there’s basically no other means of abstraction in the language. I’ve got so used to languages with lambdas, for example, that the idea of creating a LightOnCommand class that implements the Command interface to encapsulate the act of turning a light on feels like such a waste of brainpower, bytes, and sanity. I’d hate to have my expressivity limited so heavily.


Categories: Programming Tags: ,

Making inheritable objects in JavaScript without objects

August 14th, 2011 4 comments

For a long time I’ve found the subject of the equivalence of closures and objects fascinating. The problem with creating objects using closures is that there isn’t a way to do inheritance (although you should always favour composition over inheritance anyway!). I thought it would be fun to see if it was possible to implement an object system in JavaScript with inheritance, without using any plain JavaScript objects.

To do this, I set myself two rules:

  1. Don’t create any plain old JavaScript objects (functions, arrays etc. are allowed)
  2. Don’t use the dot operator.

For that to work, I wrote some wrappers for the JavaScript methods I would need, like (this becomes callSlice). Apart from those wrappers, there are no dots used anywhere. To dispatch methods based on a string name, instead of using an object (which would have been much easier but would have missed the point of the exercise) I’m passing around functions which dispatch methods using conditional constructs (if, else and switch).

Introducing funcobj!!!

Yeah I know, it’s a rubbish name. Anyway, the Github repo is here and I’ve got a running example on JsFiddle here.

Here’s some examples of how it works:

//call the doSomething method on myObject, with the argument 500

//call the doSomethingElse method on the object's super object
myObject('doSomethingElse', true)();

To make an object like this, call objMaker with a function that defines and dispatches methods:

To inherit, pass a third argument to objMaker, which is the object to delegate to if the new object does not contain the called method (or: if the new object cannot respond to the message). Have a look at this long example in JsFiddle to see how that works:

This is stupid

Yeah, I know. It’s not meant to be used for anything. It’s probably hopelessly inefficient, and the syntax leaves a lot to be desired. But it does work, which was what I was going for. It might be a stupid idea, but it demonstrates the power of JavaScript closures. It also gives the possibility of dynamically responding to unknown messages, like in Ruby’s method_missing.

This is what objMaker looks like. There’s some fairly gnarly code in there, but if you can get your head around what’s doing what, you’ll hopefully learn something new about JavaScript!

Categories: Programming Tags: ,

Podcasts I listen to

August 13th, 2011 8 comments

I listen to a lot of podcasts. Any time I can find to listen to them I do – when I’m cooking, eating, washing up, walking to work, brushing my teeth, going shopping, running …

It’s not always easy to find the best podcasts, so I thought it would be helpful to list them here, along with a quick description, and some selected episodes where appropriate.

This list is in rough order of preference. I’m not saying the ones at the top are objectively better; just that I enjoy them more.

Drunk and Retired

One of my favourite podcasts. Coté and Charles Lowell just chatting, usually about software, but whatever else they fancy as well. Always funny, often enlightening.

Selected episodes

Back to Work

Merlin Mann (of 43 folders and Inbox Zero) and Dan Benjamin (of the Ruby world) chatting about creating, productivity, Buddhism and life. Hilarious and amazing.

Selected episodes

This Developer’s Life

An excellent podcast, unlike any other I listen to. Every episode follows a theme, with storytelling interviews around that theme, backed by good music. Can’t get enough of it.

Selected episodes

Ruby Rogues

This is a fairly new Ruby discussion podcast. It features all your favourite celebrity Ruby developers, like James Edward Gray II, Aaron Patterson, Peter Cooper, Avdi Grimm, Gregory Brown and more. It’s fascinating to hear these at-the-top-of-their-game developers talking about why they do things in a certain way. Each episode is a discussion around a specific topic.

Selected episodes

Software Engineering Radio

“The Podcast for Professional Software Developers”. An excellent, quite formal podcast about software engineering topics. It has a bit of a Java, patterns and model-driven architecture bias, but it’s second-to-none in terms of serious software engineering/development content. Most of the interviewers/editors are German, so it’s got a much more ‘European’ view on things (you may not think there’s any difference, but I think there is).

Selected episodes

The Pragmatic Podcast

This is usually interviews with Prag Prog authors, so can often come across a bit like a sales pitch, but occasionally there’s a real gem.

Selected episodes

A Minute With Brendan

Brendan Eich, JavaScript’s Daddy, talking about the present and future of JavaScript. Hear about JavaScript from the horse’s mouth.

Selected episodes

The Creative Coding Podcast

Fairly informal chats mostly about game development/general creative coding, with the odd interview thrown in.

Selected episodes

IT Conversations

I try to listen to every IT Conversations podcast, but there are a lot of them. It’s always interesting stuff, and it covers a wide range of topics in the tech world, from programming to biotech to robotics, etc. IT Conversations is actually a collection of other podcasts and conference recordings.

Selected episodes

Make All

Coté from Drunk and Retired, with his industry analyst hat on, interviewing programming people.

Selected episodes


Three UK-based web developers talking about web development issues. It’s called ExplicitWeb because it has an Explicit rating on iTunes – be warned.

Selected episodes

The JavaScript Show

Jason Seifer and Peter Cooper with a slightly irreverent round-up of JavaScript news.

The Ruby Show

The Ruby equivalent of The JavaScript show.

Web Dev Radio

A podcast about web development from Michael Kimsal. Partly an interview show with various web developers, partly Michael just talking about stuff.

Selected episodes

The Basement Coders

Informal, Java-heavy discussion about software development. Don’t let the Java put you off though – I’ve never written a line of Java, but I still find it interesting.

Selected episodes

The Pipeline

Dan Benjamin interviewing various trendy tech people.

Selected episodes

The Changelog

“Open Source moves fast. Keep up.” New and cool stuff in open source.

Tech Weekly

The Guardian’s tech podcast, presented by Aleks Krotoski. A wide-ranging look at the tech industry.

There’s a lot here, but I can just about keep up. I never listen to podcasts when I’m not doing something else, so I don’t see it as a waste of time. In fact, I almost see it as a waste of time when I’m doing something mindless (like washing up, running etc.) and I’m not listening to podcasts. Maybe that’s a bit obsessive, but I think it’s a great way of learning masses of new stuff for free. Anyway, I hope you find something interesting in here. Enjoy!

Categories: Miscellaneous Tags: ,

Understanding the Ruby object model

August 7th, 2011 24 comments

Not a very long time ago, I found the Ruby object model very confusing. Part of my problem was that I was trying to model the relationships as a directed acyclic graph, whereas in reality, the model contains cycles. I’m guessing that others have found this confusing, so I’m going attempt to explain how it works in a way that my past self would have understood! Note that this is a basic explanation, and glosses over higher-level concepts like the eigenclass/metaclass (I’ll leave that for a later post).

Different things in Ruby

There are just a few things that exist in Ruby that you need to understand to really grok its object model.


Everything is an object. You can’t get very far into Ruby-land without hearing that phrase. It’s true though, everything in Ruby is an object. The interesting thing is how those objects are linked together and classified.


All objects are instances of a class. There are three special classes that are the key to understanding the Ruby object model: Object, Module and Class. More on them later.


Like I said before, it’s the links between the different objects that explain how the Ruby object model works.

Instance of/class

All objects have a class – they are instances of that class. That means that whenever you have a class, you can call .new on it to get an instance. And whenever you have an instance, you can call .class to get its class. This seems obvious, but it can get confusing when you remember that everything is an object, and so everything is an instance of a class.


All classes have a link to a superclass. If you don’t explicitly inherit from another class in a class definition, that class will inherit directly from the Object class.

How they fit together

Here’s some code to play with:

class Animal

class Dog < Animal

fido =

Once you know what the pieces and the relations are, it’s fairly straightforward to piece them together. All classes are an instance of Class. That includes the class Class, so there’s a circular relation there (which isn’t a problem).

Dog will basically have the following inheritance hierarchy (the superclass links):

Dog < Animal < Object < BasicObject

(Ruby 1.9 introduced BasicObject as Object‘s superclass.)

The Class class has the following inheritance hierarchy:

Class < Module < Object < BasicObject

Anything that’s a class (so BasicObject, Object, Module, Class, Animal and Dog here) has Class as its class – they’re all instances of Class. Any other objects have their own classes. So fido above will have a class of Dog, 3 has a class of Fixnum, “an awesome string” has a class of String, etc. All those classes inherit from Object ultimately (although classes like Fixnum have their own complex inheritance hierarchies).

To finish things off, here’s a little diagram of what I’ve just described, showing all the class and superclass links.

The Ruby object model

Categories: Programming Tags: ,

Reflections from a Kindle owner

August 5th, 2011 7 comments

Back in April I got a Kindle for my birthday. It’s changed my tech-life massively, and I thought I’d write a few words on that here, from a developer’s perspective.

(Disclaimer: the Amazon links in this blog post are Amazon Affiliate links, which means I get a percentage of any sales resulting from you following them. If you don’t feel I deserve that percentage, then feel free to go to or [non-affiliate links] and I’m sure Amazon will be happy to help you find a Kindle.)


I now read most books on my Kindle. In many ways it’s a better experience than a paper book – it’s much lighter than the average programming book, I can rest it on my leg without having to hold it open, turning pages is easier, and with a cover with built-in light I can read in the dark (e.g. I can read in bed without waking up my girlfriend).

It does have its downsides in comparison to a paper book as well – navigating between different spots isn’t as seamless/natural, even with hyperlinks; code listings often wrap (I usually view these in landscape mode, but even then it’s often not enough); it’s significantly more valuable than a book, so I need to take a lot more care with it; some nuances of book formatting don’t always make it through the conversion; and although it’s got a massive battery life, that’s still a consideration.

When I’m buying a new book online now though, I don’t hesitate to get the Kindle version (if it’s available). The benefits far outweigh the downsides.


I’ve been wanting to read the Prag Pub magazines for a long time now, but I don’t like to sit in my computer and leaf through PDFs (and I certainly didn’t want to print them all out onto paper). Luckily, they’re all available for free download in Kindle format, so over the past few months I’ve gradually been catching up with the back issues. It’s a great magazine and I’d highly recommend it, whatever your e-reader of choice.

Blogs and essays

Instapaper is an essential tool for any Kindle owner. It gives you a “Read Later” bookmarklet, which enables you to mark any article to be read later. You can then tell Instapaper to deliver a collection of your unread articles to your Kindle regularly, for free! This has made such a difference to me. I come across so much good material online that I want to read, through Google Reader and Twitter, but when I’m at the computer I don’t just want to sit there reading blog after blog. Having those interesting articles delivered to my Kindle automatically means I don’t need to think at all – I can just read them when I feel like it.

In the same vein, I use Instapaper to catch up on older essays, such as Paul Graham’s massive collection or Steve Yegge’s drunken blog rants, that I’ve been wanting to read for a long time.

Free 3G

What a tongue-twister. It’s amazing though – if you get the 3G version, Amazon give you free web access, wherever you are. FREE. It still astounds me. It’s not particularly fast, and looks pretty ugly, but it works. For looking stuff up on Wikipedia it’s great.


If you’ve got an e-reader, or something e-reader-like, e.g. an iPhone/iPad/Android something, I’m not going to tell you you need a Kindle as well. Maybe you do, maybe you don’t. But for those that don’t have any way of reading electronic material away from a computer, I’d highly recommend getting one. It might change your life :)

Categories: Miscellaneous Tags:

Easy functional programming in JavaScript with Underscore.js — part 2

July 29th, 2011 25 comments

In the previous post I showed how good use of Underscore.js‘s map function can substantially increase the quality of your code. This time I’ll explore some other functional collection favourites: reduce, select and all.

Reduce that array over a low heat until thick and creamy

Have you ever had to do something like this?

Basically, this is going through some kind of list of values, calculating a new value from each one and accumulating some kind of answer. It’s a common pattern, and there’s an Underscore function for it! This is exactly what _.reduce was built for:

_.reduce takes a collection of values, a function, and a starting value. In this case, the starting value is 0 because we’re building up a running total of numbers. The function is passed the running total (which starts at 0) and each element of the collection. The return value of the function becomes the next value for the running total. _.reduce doesn’t just need to be used on numbers:

In this case, I’m reducing an array of animal objects into a single string. Of course there are plenty of ways to do the above, but this shows you the flexibility of _.reduce.

Bo Selecta!

Imagine you have an array of strings, but you want a new array of strings that start with a capital letter. You might do that like this:

Now, you won’t be surprised to learn that there’s an Underscore function for doing just that: introducing!

Isn’t that much cleaner? Again, we’re abstracting away the minutiae of selecting elements from a list, and just declaring that we want the elements that start with a capital letter. Simples!

All the single ladies

Sometimes you just want to know a yes or no answer about a collection. For example, are all my ladies single?

Hell yes they are. You can read _.all as “is this statement true about all the elements in my collection?” In the same way, _.any can be read as “is this statement true about any of the elements in my collection?”

What about this?

Here’s a useful little tip. When you’re working with nested functions in an object context, you’ll find that this in the nested function doesn’t refer to the object’s context, but the global context. The standard way to deal with this is a line like that = this; or self = this;. There’s a nicer way to do this with Underscore. Nearly all the functions for working on collections take an optional context argument, which specifies what this will be inside the function. Here’s an example:

Because we’re passing the value of this to, the function passed to is working with the correct this. Otherwise, this.maxAge would be undefined.

Learning more

I’ve only gone into some of the functionality that Underscore offers. The docs are very approachable and clear – I urge you to go and read them.

@SamirTalwar on Twitter recommended that I show the alternative syntax for Underscore, as described in the docs. Basically, instead of doing:, func);

you can do:


And, coupled with .chain() you can do awesome chaining things like this:

Pretty cool. Anyway, use whichever feels right to you. Enjoy!

Categories: Programming Tags: ,