Archive

Posts Tagged ‘programming’

Closures vs Objects: FIGHT

September 23rd, 2011 12 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.

//object
function Person(name) {
  this.name = name;
}

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


//closure
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 ' + this.name);
    }
  };
}

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');
dave.sayHi();

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) {
  object.name = newName;
}

changeName(dave, 'Bob');


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

dave.changeName = changeName;
dave.changeName('Bob');


//call/apply a function with the object as the context
changeName.call(dave, '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 14 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

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

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) {
  this.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

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.

Wrap-up

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 6 comments

<rant>

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.

</rant>

Categories: Programming Tags: ,

Podcasts I listen to

August 13th, 2011 3 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

ExplicitWeb

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 14 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.

Objects

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.

Classes

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.

Relations

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.

Superclass/subclass

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
end

class Dog < Animal
end

fido = Dog.new

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: ,

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

July 29th, 2011 15 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 _.select!

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 _.select, the function passed to _.select 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:

_.map(collection, func);

you can do:

_(collection).map(func);

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: ,

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

July 27th, 2011 6 comments

So, you’ve been developing in JavaScript for a while, you’re getting on quite well with your for and while loops, when somebody comes along and tells you you shouldn’t be doing that, that JavaScript is a functional programming language and there’s much better ways to solve most problems that with loops. Whaaa…? Well, that’s what I’m here to tell you anyway.

What is functional programming?

Functional programming (FP) is all about the idea of functions as a mapping from one value to another. An FP function just turns one value into another – it doesn’t have side effects. Side effects are anything that happens within the function that changes something outside of the function. For example, changing the value of a variable not defined in the function, or logging output, or showing an alert message … basically anything that happens in the function. The only thing an FP function does is takes in a value, and returns a new value.

Another interesting thing about FP is the use of higher-order functions. These are functions that either take or return functions as values (or both). I’m mainly going to be looking at functions that take other functions as parameters, because there are some interesting things you can do with that.

An underscore, courtesy of Wikipedia

Functional programming in JavaScript is made a lot easier with a suite of functions called Underscore.js all packed into a minified script of just 3kb. Underscore provides a selection of common FP functions for working on collections, like map, each, reduce, select etc. I’ll walk through some of these to demonstrate the power of FP. Note that functional programming isn’t just about working with collections – there are lots of other exciting things you can do – but for now I’ll concentrate on the collections.

Mapping over an array

One of the most widely used Underscore functions is _.map. This takes an array and a transforming function, and creates a new array based on the return value of the transforming function. That’s a bit abstract so I’ll give you an example:

So, _.map is passed an array, and a function. That function is called on each element of the array in turn, and the return value of the function gives the corresponding element in the new array. Note that the original array is left intact. The _.map function takes an array, and returns another array – it’s a mapping from one value to another.

You can do much more interesting things with _.map than just multiplying numbers though. You could transform an array of strings into an array of cats!

I hope you’ll forgive me for using two Underscore functions there. First off, we’ve got _.map. In this case, we’re going through the array of cat names, and creating an array of cats. The second is _.each. This, like _.map, goes through each element of the array, passing them into the function, but it doesn’t care about the return value. It just executes the function and carries on with its life. Now, if you’re concentrating, you may have noticed that each isn’t actually a mapping from one value to another, and you’d be right. _.each is only useful if you allow side effects, for example console.loging. A JavaScript program isn’t much fun without any side effects, because you’d have no idea if anything happened otherwise. The key to functional programming is minimising the side effects.

What’s great about _.map is that once you’ve learned to read it, and understand what it does, it really succinctly explains the meaning of your code. In that cat example, you can see that all the _.map function is doing is turning strings into cats. That’s all you need to know. The old-school JavaScript technique would look like this:

In comparison, isn’t that just damn ugly? I mean, to read that you need to keep track of the array, and the array index, and the length of the array, and you have to make a new blank array to contain the new cats, and … you get the point. It’s mixing up the how with the what. All I care about is that I’m getting an array of cats, from an array of cat names. Don’t bother me with insignificant details like array indices.

Here’s another example: constructing a query string:

This one uses an object, but the same principles apply. From a list of key/value pairs, we’re constructing an array of ‘key=value’ strings. Then all you need to do is join the array with &s. This describes how a query string is formed much more declaratively than the standard

append the key, then an equals, then the value, then an ampersand, then the next key, then the next value, then another ampersand, then – oooh we’re at the end – better get rid of that last ampersand, whoops!

Go forth and map-ify!

I hope that’s given you some ideas as to how functional programming can be used in JavaScript. And I really hope that you can begin to see how much cleaner your code can get when you cast out the for loops and embrace the _.map. If all you’re after is map and each, and you’re using jQuery, you’ll be glad to know both functions have jQuery equivalents: jQuery.map and jQuery.each, albeit with a slightly different API. Next time I’ll be looking at some of Underscore’s other functions, for the times when _.map just won’t cut it.


Part 2 is now up!

Categories: Programming Tags: ,

The Ruby world is nuts

June 8th, 2011 10 comments

Apparently they started out using God, but switched to Bluepill due to its ability to monitor child processes, such as things spawned by Unicorn.

From Episode 166 of The Ruby Show.

Categories: Programming Tags: ,

JavaScript, JSON and modern web MVC

June 2nd, 2011 7 comments

As web developers we’re working through a transitionary period. New technologies are becoming widespread enough to be usable in real web apps – not just toys. After years of stagnation in JavaScript engines, Google Chrome started an arms race in speed, with all the major browser makers competing to make the fastest JavaScript interpreter. These changes are opening up a new world of web app development that hasn’t been fully explored yet, but this means we may have to rethink some of the best practices we’ve been following for the past decade.

MVC today

In a modern web application framework, MVC is well defined: requests get routed to a controller, which requests data from the model (which is probably using an ORM) and instantiates a templated view with this data. This view is sent as HTML to the browser which creates a DOM from the HTML, and renders the DOM (with CSS and images) as a web page.

JavaScript then operates on the DOM, adding a layer of interactivity to the page. As things advance, the JavaScript layer has taken on more importance, reducing the number of page reloads by selectively reloading parts of the page with Ajax.

As the complexity of JavaScript on the client has increased, it’s been easy to end up with unstructured spaghetti code based around the jQuery model of “find something, do something with it”. As more state has moved to the browser, MVC frameworks for JavaScript have stepped in to add structure to the code. The problem is, now we have two MVC stacks:

Current JavaScript solutions suffer from "Double MVC". You need both server and client-side MVC stacks. Conceptual complexity is very high.
@dhh
DHH

MVC of the future

MVCMVC or MMVVCC aren’t just un-catchy, they’re a rubbish idea. If we’re going to make rich apps that rely on JavaScript (and as I said previously, I think we should), we need to lose some redundancy.

The model will usually be accessing some shared database, so in most cases it makes sense for this component to be on the server (authentication usually lives here as well). The view is the DOM, and the controller is the JavaScript. There’ll also need to be model code in the JavaScript – the extent to which the model logic is split between client and server depends on the application.

All the server needs to do is provide JSON responses when the client asks for more data, ideally using simple RESTful resources.

One benefit of the server being a simple JSON store is that it enables us to easily add redundancy to our apps – if server1 fails to deliver a response, fall back to server2.

No more HTML

The DOM is the means by which we display our app to the user. The browser thinks in terms of the DOM. HTML is just a serialisation of the DOM. Modern web app developers shouldn’t be thinking in terms of HTML. HTML is the assembly language of the web, and we should be working at a higher level of abstraction if we want to get stuff done. Most of the time we should be thinking in terms of layouts, widgets and dialogs, like grown-up UI designers.

The problem at the moment is that HTML is being used as a combined data and presentation format, and it should be obvious that this is a Bad ThingTM.

Of course at some point we’ll need to go down to the level of the HTML, and at that point we should be using templates. jQuery.tmpl is one (see my slides and presentation on the subject), but there are many others too. One interesting development (thanks to James Pearce for putting me onto this) is Model-driven Views (MDV).

MDV links JavaScript objects to the DOM in such a way that any changes to the object are automatically reflected in the DOM, and likewise, any user changes to the DOM are automatically reflected in the model objects. Hopefully this will become standard in modern browsers, as it provides a clean and easy way to keep the DOM up-to-date with the model objects without endless wiring, which again helps to insulate us from having to deal with too much HTML.

I’m not suggesting that HTML will go away, or that developers won’t need to learn it – just that most of the time, most developers won’t need to be worrying about it, just like most of the time, most C developers don’t need to worry about assembly code.

Conclusion

Most web-apps are currently halfway there in terms of moving functionality to the client. The problem is that we have ended up in the worst of both worlds as app developers. Our serverside MVC framework provides a nice template-based abstraction over the HTML, which we then break apart on the client. We’re forced to work at too many different levels of abstraction simultaneously, which is never a good thing.

Things were simple when everything happened on the server. Things will be simple again when everything happens on the client. Over time new tools and best practices will emerge to encourage this new way of working. In the meantime, it’s going to take a bit of extra effort, but it’ll be worth it.

The end of progressive enhancement revisited

May 29th, 2011 141 comments

This is a follow-up post to JavaScript and the end of progressive enhancement - you may want to read that first if you haven’t already. The comments are worth a read, as well as the Reddit thread.

The app/doc divide

What I didn’t make clear in my original post (because I wasn’t fully clear about it at the time) is the distinction between document-based web sites, and web applications. Documents are made to be read, whereas apps are made to be interacted with. James Pearce wrote a great description in the comments:

Actually what we’re maybe observing here is a clash of civilisations: the documentistas vs the applicationistas; web-as-a-medium vs web-as-a-technology-stack; designers vs programmers. It’s no wonder that progressive enhancement is a powerful tenet for the former of each pair to rally around… but not necessarily the most architecturally important consideration of the latter.

[James has since written a great, and highly relevant, post on the subject of URLs in JS apps.]

It goes without saying that apps and documents are two completely different things (even though there is a huge amount of overlap between the two). Trying to treat web design/development as a single discipline is a mistake. Anything that is primarily meant for reading, such as a newspaper website or a blog, exists as a collection of documents. I should be able to link to another blogger’s blog post and expect that in a week or a year that content will still be available at that address. I shouldn’t need to have JavaScript enabled in order to visit that address.

Web apps aren’t the same thing. A web app is an application that happens to use web technologies. Most web apps could be desktop apps – what makes a web app a web app is that it is accessed using a browser. No-one expects to be able to hyperlink to a particular view in Microsoft Excel – what would that even mean? In the same way, I can’t share a link to a particular email in Gmail. Web apps don’t always exist in the same web as everything else – many apps are islands.

Historically, web apps have been built in the document-based paradigm, using links to move to different parts of the app and forms to submit data for processing. The only reason they were made like this was because this was all the technology allowed. Now that technology has advanced, first with Ajax and now with HTML5, we aren’t tied to this old practice.

Amy Hoy summed it up nicely:

"graceful degradation" (and likewise, p.e.) died the moment we moved away from document design and into app design.
@amyhoy
Amy Hoy

The problem is that because everyone building stuff online is using the same technologies, there can be a tendency to think that there is one true way of using those technologies, independent of what they’re being used for. This is clearly false.

The end of progressive enhancement?

Progressive enhancement is still the way to make document-based sites on the web – there’s no denying that. But with applications the advantages are less clear. If we can accept the fact that the document-based paradigm isn’t the best way to make web apps, then we should also accept the fact that progressive enhancement doesn’t apply to apps.