Saturday, June 30, 2012

Eight Simple Rules for Maintainable Javascript

All projects start out small. This is true for the javascript part of any web app. In the beginning, it's always easy to read, and easy to debug.

I've put together some of my learnings for client side Javascript

1. Do not let your .js file be the entry point to your code

I've seen this anti pattern in most of the codebases I've inherited.

The Trap: The javascript that binds to the DOM

$(".submit-button").click(function(){
  server.submit();
});

This is a trap for multiple reasons:

  1. It's really hard to figure out what happened when you clicked on a button. Did some callback get triggered? Where is the code for this?
  2. You'll can easily get a bunch of callbacks that interfere with each other. Another page of mine has another button called submit button. I need to make sure that this JS is not loaded on that page
  3. It's not possible to compile all your javascript assets into a single application.js

Solution: Wrap everything that is binding to an element, and call that from the html

function bindElementToSubmit(element) {
  element.click(function() {
    server.submit();
  });
}

Binding things in the HTML helps you keep in your head what is going on in a particular page. It also helps you answer things like how an element is bound (was it ".submit-button", "#page-submit-button", or "form > .submit-button"), and makes sure that it's easy to find when searching for code later.

Caveat: One caveat to look out for is the order of loading of JavaScript files. The above code requires jQuery loaded for $(document).ready() to work. One alternative is to use window.onLoad(), though that waits for the entire DOM and assets to load.

2. Understand how this works in Javascript

Everything is lexically scoped in Javascript. Except for 'this', which is something that is set depending on how a method is called. Some libraries like jQuery even set the value of 'this' to mean things like the object on which a callback is called.

The Trap: Using a this pointer that's pointing at the wrong object.

$("some-div").click(function() {
  this.html("loading"); // replaces the current div with 'loading'
  $.get("/foobar", function(result){
    this.html(result); // no such function html!!
  });
});

Granted, this isn't all that dangerous because it will be obvious that your code is not working.

The Solution: Have a convention for what the current object is. I prefer self.

$("some-div").click(function() {
  var self = this;
  self.html("loading");
  $.get("/foobar", function(result){
    self.html(result);
  });
});

3. Structure your JS code into logical units

Javascript is a prototype based language. There are a lot of cool things you can do with a prototype based language, but very few of them will help you write a good UI. Most people take the lack of 'class' keyword in Javascript to mean the lack of Object Orientation.

The Trap: A bunch of methods floating around in space

function processResults(results) {
  // do Something
}

function bindElementToSubmit(element) {
  element.click(function(){
    server.submit(function(result){
      processResults(results);
    });
  });
}

bindElementToSubmit($(".submit-button"));

This is a trap because you aren't able to group logically related methods together. This would be similar to a bunch of static methods on your server side.

The Solution: Build some sort of object oriented abstraction over your javascript functions. You can either hand roll your own using javascripts prototype functionality, or you can just drop in something like class-js

SubmitPage = Class.extend({
  processResults: function(results) {
    // do Something
  },

  constructor: function(element) {
    var self = this;
    element.click(function(){
      server.submit(function(result){
       self.processResults(results);
      });
    });   
  }
});

new SubmitPage($(".submit-button"));

4. Use client side templates to render content

Again, this can go into another blog post by itself, and I'll be writing about this soon.

The Trap: Having your server return HTML output as the response to an AJAX request, and having the client just dump it into the DOM somewhere

The Solution: Use something like Mustache.js to render your server side template. I'll be posting more about this soon.

5. Test your javascript

Just because this is javascript, and not the backend code, does not mean that you should ignore your JS. JS faces just as many (if not loads more) regression bugs than your backend code.

The Trap: A lot of code without any test coverage

The Solution: Test your code with something like jasmine. Use one of the addons to jasmine like jasmine-jquery, which lets you bootstrap your tests with a sample DOM, and then run your tests against that DOM.

Check out the example specs

6. MetaProgramming #ftw

Ruby programmers would already be familiar with some sort of metaprogramming, and JS is almost as powerful. The main feature I miss from ruby is the method_missing.

You can open up a class and add methods:

String.prototype.alert = function() {
  alert(this);
};

"foobar".alert();

You can use [] like a poor man's send:

alertFunction = this["alert"];
alertFunction("blahblahblah"); // Note that alert will no longer get the same value of this

You can also use [] to define dynamic methods:

for(i = 0; i < 5; i++) { 
  var times = i; // need to save this in our closure
  String.prototype["alert" + i] = function() {
    alert(this + times);
  }
};

"foobar".alert3()

7. Know your javascript libraries

This could cover multiple blog posts in itself.

Know your options for manipulating the DOM, as well as other things you want to do

As a primer, check out the following projects:

8. Use CoffeeScript

CoffeeScript is a neat little language that compiles down to JS, and has support for almost all of these features baked right in. It namespaces things for you, and fixes the this/self problem, and provides a lot of the functionality that underscore would provide.

As an additional benefit, it's much less code to read. And it's baked right into rails.

You can read more on coffeescript.org


If you liked this post, you could:

upvote it on Hacker News
or just leave a comment

Using bundler with executables

What Is Bundler?

Bundler is a ruby gem loading system. It loads up all the relevant gems for your project, and ensures the versions are correct, before your app takes over.

How do I ensure that my executables are bundler aware?

When doing a bundle install (or just bundle), always add the option --binstubs. This will create binary wrappers in the bin/ folder of your project. bundle --binstubs

Instead of executing commands directly like this: rake

Execute the command command that is in the bin folder. ./bin/rake

Do I check these /bin/* files in?

I usually git ignore them, but, according to the documentation, it's safe to check in.

I hate typing ./bin/rake every time!

No problem. You can add a relative path like ./bin to your $PATH

  • If you are using rbenv, just add ./bin to your path in your ~/.bashrc
  • If you are using rvm, add ./bin into every .rvmrc

Proxy Pattern

Problem Statement

I have a method which does something great, and is nice and small. It does everything i want, except some small feature that isn't core to the class. For example, I want to do some fudging for the input parameters and/or fudging the output parameters. I want to create another class to handle these orthogonal requirements.

TL;DR - Short summary

Wrap the original object in a proxy which looks like the original object to the outside world. Delegate calls to the original object eventually. This is an example of Aspect Oriented Programming.

Code Example

I'm building this example up as a series of requirements

Requirement 1: I want to be able to get my bank balance from the bank.

Requirement 2: I want to be able to log the fact someone has checked their bank balance

Requirement 3: I want to tell everyone that their bank balance is double of what it is really. But logging should log the correct value.

Requirement 4: I've changed my mind. It's hard for me to have plausible deniability if i log actual bank balances. Fudge that as well

Requirement 5: I want to cache the balance. I still expect logging and doubling.

A note on the example: Requirement 3 (the doubling filter) should probably go into the first class, it's core to the business. I just made it a proxy filter to illustrate the point about output fudging.

Conditions for a good proxy

  • The constructor accepts the item it is proxying.
  • The proxy passes requests to the original object in at least one branch of the code
  • The proxy honors all methods of the original object with the same signature (in java world, implements the same interface)
  • Proxies must be composable (this will follow from the point above): Proxy1.new(Proxy2.new(Proxy3.new(object)))
  • That does not mean the order of proxies is immaterial

Practical Uses

  • A proxy that caches the response from the inner method
  • A proxy that runs the inner method in a single database transaction
  • A proxy that adds logging before and after the method is called
  • A proxy that validates inputs

DynamicProxy

In the examples above, we overrode a single method bank_balance. Now, imaging you want a proxy to overwrite 50 different methods of an object. Enter DynamicProxy for java, and DynamicProxy/SimpleProxy for .NET. These let you override all methods in a particular interface.

Of course, ruby doesn't need that thanks to method_missing!

Rack filters

Rack provides an easy way to add proxy pattern to the app called via filters (rails cleans this up as around filters). A filter which does nothing will be as follows (notice what the constructor accepts, and what methods the filter implements)

Further Reading